context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class ChainTests { [Fact] public static void BuildChain() { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (var unrelated = new X509Certificate2(TestData.DssCer)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.ExtraStore.Add(unrelated); chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; // Halfway between microsoftDotCom's NotBefore and NotAfter // This isn't a boundary condition test. chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; bool valid = chain.Build(microsoftDotCom); Assert.True(valid, "Chain built validly"); // The chain should have 3 members Assert.Equal(3, chain.ChainElements.Count); // These are the three specific members. Assert.Equal(microsoftDotCom, chain.ChainElements[0].Certificate); Assert.Equal(microsoftDotComIssuer, chain.ChainElements[1].Certificate); Assert.Equal(microsoftDotComRoot, chain.ChainElements[2].Certificate); } } /// <summary> /// Tests that when a certificate chain has a root certification which is not trusted by the trust provider, /// Build returns false and a ChainStatus returns UntrustedRoot /// </summary> [Fact] [OuterLoop] public static void BuildChainExtraStoreUntrustedRoot() { using (var testCert = new X509Certificate2(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword)) using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword, X509KeyStorageFlags.DefaultKeySet)) using (var chainHolder = new ChainHolder()) { X509Certificate2Collection collection = ic.Collection; X509Chain chain = chainHolder.Chain; chain.ChainPolicy.ExtraStore.AddRange(collection); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationTime = new DateTime(2015, 9, 22, 12, 25, 0); bool valid = chain.Build(testCert); Assert.False(valid); Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.UntrustedRoot); } } public static IEnumerable<object[]> VerifyExpressionData() { // The test will be using the chain for TestData.MicrosoftDotComSslCertBytes // The leaf cert (microsoft.com) is valid from 2014-10-15 00:00:00Z to 2016-10-15 23:59:59Z DateTime[] validTimes = { // The NotBefore value new DateTime(2014, 10, 15, 0, 0, 0, DateTimeKind.Utc), // One second before the NotAfter value new DateTime(2016, 10, 15, 23, 59, 58, DateTimeKind.Utc), }; // The NotAfter value as a boundary condition differs on Windows and OpenSSL. // Windows considers it valid (<= NotAfter). // OpenSSL considers it invalid (< NotAfter), with a comment along the lines of // "it'll be invalid in a millisecond, why bother with the <=" // So that boundary condition is not being tested. DateTime[] invalidTimes = { // One second before the NotBefore time new DateTime(2014, 10, 14, 23, 59, 59, DateTimeKind.Utc), // One second after the NotAfter time new DateTime(2016, 10, 16, 0, 0, 0, DateTimeKind.Utc), }; List<object[]> testCases = new List<object[]>((validTimes.Length + invalidTimes.Length) * 3); // Build (date, result, kind) tuples. The kind is used to help describe the test case. // The DateTime format that xunit uses does show a difference in the DateTime itself, but // having the Kind be a separate parameter just helps. foreach (DateTime utcTime in validTimes) { DateTime local = utcTime.ToLocalTime(); DateTime unspecified = new DateTime(local.Ticks); testCases.Add(new object[] { utcTime, true, utcTime.Kind }); testCases.Add(new object[] { local, true, local.Kind }); testCases.Add(new object[] { unspecified, true, unspecified.Kind }); } foreach (DateTime utcTime in invalidTimes) { DateTime local = utcTime.ToLocalTime(); DateTime unspecified = new DateTime(local.Ticks); testCases.Add(new object[] { utcTime, false, utcTime.Kind }); testCases.Add(new object[] { local, false, local.Kind }); testCases.Add(new object[] { unspecified, false, unspecified.Kind }); } return testCases; } [Theory] [MemberData(nameof(VerifyExpressionData))] public static void VerifyExpiration_LocalTime(DateTime verificationTime, bool shouldBeValid, DateTimeKind kind) { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); // Ignore anything except NotTimeValid chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags & ~X509VerificationFlags.IgnoreNotTimeValid; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationTime = verificationTime; bool builtSuccessfully = chain.Build(microsoftDotCom); Assert.Equal(shouldBeValid, builtSuccessfully); // If we failed to build the chain, ensure that NotTimeValid is one of the reasons. if (!shouldBeValid) { Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.NotTimeValid); } } } [Fact] public static void BuildChain_WithApplicationPolicy_Match() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; // Code Signing chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3")); chain.ChainPolicy.VerificationTime = msCer.NotBefore.AddHours(2); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; bool valid = chain.Build(msCer); Assert.True(valid, "Chain built validly"); } } [Fact] public static void BuildChain_WithApplicationPolicy_NoMatch() { using (var cert = new X509Certificate2(TestData.MsCertificate)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; // Gibberish. (Code Signing + ".1") chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3.1")); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2); bool valid = chain.Build(cert); Assert.False(valid, "Chain built validly"); Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue); Assert.NotSame(cert, chain.ChainElements[0].Certificate); Assert.Equal(cert, chain.ChainElements[0].Certificate); X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus; Assert.InRange(chainElementStatus.Length, 1, int.MaxValue); Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage); } } [Fact] public static void BuildChain_WithCertificatePolicy_Match() { using (var cert = new X509Certificate2(TestData.CertWithPolicies)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; // Code Signing chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.18.19")); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; bool valid = chain.Build(cert); Assert.True(valid, "Chain built validly"); } } [Fact] public static void BuildChain_WithCertificatePolicy_NoMatch() { using (var cert = new X509Certificate2(TestData.CertWithPolicies)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.999")); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2); bool valid = chain.Build(cert); Assert.False(valid, "Chain built validly"); Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue); Assert.NotSame(cert, chain.ChainElements[0].Certificate); Assert.Equal(cert, chain.ChainElements[0].Certificate); X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus; Assert.InRange(chainElementStatus.Length, 1, int.MaxValue); Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage); } } [Fact] [OuterLoop( /* May require using the network, to download CRLs and intermediates */)] public static void VerifyWithRevocation() { using (var cert = new X509Certificate2(Path.Combine("TestData", "MS.cer"))) using (var onlineChainHolder = new ChainHolder()) using (var offlineChainHolder = new ChainHolder()) { X509Chain onlineChain = onlineChainHolder.Chain; X509Chain offlineChain = offlineChainHolder.Chain; onlineChain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; onlineChain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2); onlineChain.ChainPolicy.RevocationMode = X509RevocationMode.Online; onlineChain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; bool valid = onlineChain.Build(cert); Assert.True(valid, "Online Chain Built Validly"); // Since the network was enabled, we should get the whole chain. Assert.Equal(3, onlineChain.ChainElements.Count); Assert.Equal(0, onlineChain.ChainElements[0].ChainElementStatus.Length); Assert.Equal(0, onlineChain.ChainElements[1].ChainElementStatus.Length); // The root CA is not expected to be installed on everyone's machines, // so allow for it to report UntrustedRoot, but nothing else.. X509ChainStatus[] rootElementStatus = onlineChain.ChainElements[2].ChainElementStatus; if (rootElementStatus.Length != 0) { Assert.Equal(1, rootElementStatus.Length); Assert.Equal(X509ChainStatusFlags.UntrustedRoot, rootElementStatus[0].Status); } // Now that everything is cached, try again in Offline mode. offlineChain.ChainPolicy.VerificationFlags = onlineChain.ChainPolicy.VerificationFlags; offlineChain.ChainPolicy.VerificationTime = onlineChain.ChainPolicy.VerificationTime; offlineChain.ChainPolicy.RevocationMode = X509RevocationMode.Offline; offlineChain.ChainPolicy.RevocationFlag = onlineChain.ChainPolicy.RevocationFlag; valid = offlineChain.Build(cert); Assert.True(valid, "Offline Chain Built Validly"); // Everything should look just like the online chain: Assert.Equal(onlineChain.ChainElements.Count, offlineChain.ChainElements.Count); for (int i = 0; i < offlineChain.ChainElements.Count; i++) { X509ChainElement onlineElement = onlineChain.ChainElements[i]; X509ChainElement offlineElement = offlineChain.ChainElements[i]; Assert.Equal(onlineElement.ChainElementStatus, offlineElement.ChainElementStatus); Assert.Equal(onlineElement.Certificate, offlineElement.Certificate); } } } } }
using System; using System.IO; using System.Collections; using System.Text; using GenLib; namespace StandardFormatLib { /// <summary> /// Standard Format File /// </summary> public class StandardFormatFile { private ArrayList m_Records; private string m_FileName = ""; public const string kBackSlash = "\\"; public StandardFormatFile () { m_Records = new ArrayList(); m_FileName = ""; } public string FileName { get {return m_FileName;} set {m_FileName = value;} } public int Count() { if (m_Records == null) return 0; else return m_Records.Count; } public bool LoadFile(string strFileName, string strFirstRecordMarker) { bool fReturn = false; m_Records = null; m_FileName = strFileName; strFirstRecordMarker = StandardFormatFile.kBackSlash + strFirstRecordMarker + Constants.Space; //need to add for backslash and ending space StandardFormatRecord sfr; if (File.Exists(strFileName)) { try { using (StreamReader sr = new StreamReader(strFileName)) { string strRecord = ""; string strLine = ""; int nLenFRM = strFirstRecordMarker.Length; bool fMoreLines = true; bool fFoundFirstRecord = false; // look for first record strLine = sr.ReadLine(); if (strLine == null) fMoreLines = false; while (fMoreLines && !fFoundFirstRecord) //find start of first record { if (strLine != "") //skip empty lines { if (strLine.StartsWith(strFirstRecordMarker)) fFoundFirstRecord = true; //found it else { strLine = sr.ReadLine(); if (strLine == null) fMoreLines = false; //no more lines to read } } else { strLine = sr.ReadLine(); if (strLine == null) fMoreLines = false; } } //end search for first record if (fFoundFirstRecord) { strRecord = strLine; m_Records = new ArrayList(); while ((strLine = sr.ReadLine()) != null) //next line { if (strLine != "") //skip empty lines { if (strLine.StartsWith(strFirstRecordMarker)) { if (strRecord != "") { sfr = new StandardFormatRecord(strRecord); m_Records.Add(sfr); } strRecord = strLine; } else strRecord += Environment.NewLine + strLine; } } if (strRecord != "") { sfr = new StandardFormatRecord(strRecord); m_Records.Add(sfr); } m_Records.TrimToSize(); } //else no first record } // end using } catch { fReturn = false; } } // else file does not exist if ( (m_Records != null) && (m_Records.Count > 0) ) fReturn = true; return fReturn; } public void SaveFile() { string strFileName = m_FileName; SaveFile(strFileName); } public void SaveFile(string strFileName) { if (strFileName == "") return; StandardFormatRecord sfr = null; StandardFormatField sff = null; string strLine = ""; if ( File.Exists(strFileName) ) File.Delete(strFileName); StreamWriter sw = File.CreateText(strFileName); int nRecs = this.Count(); for (int i = 0; i < nRecs; i++) { sfr = this.GetRecord(i); int nFlds = sfr.Count(); for (int j = 0; j < nFlds; j++) { sff = sfr.GetField(j); strLine = StandardFormatFile.kBackSlash + sff.GetFieldMarker() + " " + sff.GetFieldContents(); sw.WriteLine(strLine); } sw.WriteLine(""); //write blank line between records } sw.Close(); } public ArrayList RetrieveAll() { return m_Records; } public StandardFormatRecord GetRecord(int nRec) // nRec - nth record { StandardFormatRecord sfr = null; if ( nRec < m_Records.Count) { sfr = (StandardFormatRecord) m_Records[nRec]; } return sfr; } public int AddRecord(StandardFormatRecord sfr) { m_Records.Add(sfr); return m_Records.Count - 1; } public void InsertRecord(int ndx, StandardFormatRecord sfr) { m_Records.Insert(ndx, sfr); return; } public void DelRecord(int nRec) { m_Records.RemoveAt(nRec); } public string GetField(int nRec, string strFM ) // nRec - nth record // strFM - Field marker { StandardFormatRecord sfr = null; string strField = ""; if ( nRec < m_Records.Count) { sfr = (StandardFormatRecord) m_Records[nRec]; strField = sfr.GetFieldContents(strFM); } return strField; } } }
// // MetadataRowWriter.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Generated by /CodeGen/cecil-gen.rb do not edit // Thu Feb 22 14:39:38 CET 2007 // // (C) 2005 Jb Evain // // 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. // namespace Mono.Cecil.Metadata { using System; using System.Collections; using Mono.Cecil.Binary; class MetadataRowWriter : BaseMetadataRowVisitor { MetadataRoot m_root; MemoryBinaryWriter m_binaryWriter; IDictionary m_ciCache; int m_blobHeapIdxSz; int m_stringsHeapIdxSz; int m_guidHeapIdxSz; public MetadataRowWriter (MetadataTableWriter mtwv) { m_binaryWriter = mtwv.GetWriter (); m_root = mtwv.GetMetadataRoot (); m_ciCache = new Hashtable (); } void WriteBlobPointer (uint pointer) { WriteByIndexSize (pointer, m_blobHeapIdxSz); } void WriteStringPointer (uint pointer) { WriteByIndexSize (pointer, m_stringsHeapIdxSz); } void WriteGuidPointer (uint pointer) { WriteByIndexSize (pointer, m_guidHeapIdxSz); } void WriteTablePointer (uint pointer, int rid) { WriteByIndexSize (pointer, GetNumberOfRows (rid) < (1 << 16) ? 2 : 4); } void WriteMetadataToken (MetadataToken token, CodedIndex ci) { WriteByIndexSize (Utilities.CompressMetadataToken (ci, token), Utilities.GetCodedIndexSize ( ci, new Utilities.TableRowCounter (GetNumberOfRows), m_ciCache)); } int GetNumberOfRows (int rid) { IMetadataTable t = m_root.Streams.TablesHeap [rid]; if (t == null || t.Rows == null) return 0; return t.Rows.Count; } void WriteByIndexSize (uint value, int size) { if (size == 4) m_binaryWriter.Write (value); else if (size == 2) m_binaryWriter.Write ((ushort) value); else throw new MetadataFormatException ("Non valid size for indexing"); } public AssemblyRow CreateAssemblyRow (AssemblyHashAlgorithm _hashAlgId, ushort _majorVersion, ushort _minorVersion, ushort _buildNumber, ushort _revisionNumber, AssemblyFlags _flags, uint _publicKey, uint _name, uint _culture) { AssemblyRow row = new AssemblyRow (); row.HashAlgId = _hashAlgId; row.MajorVersion = _majorVersion; row.MinorVersion = _minorVersion; row.BuildNumber = _buildNumber; row.RevisionNumber = _revisionNumber; row.Flags = _flags; row.PublicKey = _publicKey; row.Name = _name; row.Culture = _culture; return row; } public AssemblyOSRow CreateAssemblyOSRow (uint _oSPlatformID, uint _oSMajorVersion, uint _oSMinorVersion) { AssemblyOSRow row = new AssemblyOSRow (); row.OSPlatformID = _oSPlatformID; row.OSMajorVersion = _oSMajorVersion; row.OSMinorVersion = _oSMinorVersion; return row; } public AssemblyProcessorRow CreateAssemblyProcessorRow (uint _processor) { AssemblyProcessorRow row = new AssemblyProcessorRow (); row.Processor = _processor; return row; } public AssemblyRefRow CreateAssemblyRefRow (ushort _majorVersion, ushort _minorVersion, ushort _buildNumber, ushort _revisionNumber, AssemblyFlags _flags, uint _publicKeyOrToken, uint _name, uint _culture, uint _hashValue) { AssemblyRefRow row = new AssemblyRefRow (); row.MajorVersion = _majorVersion; row.MinorVersion = _minorVersion; row.BuildNumber = _buildNumber; row.RevisionNumber = _revisionNumber; row.Flags = _flags; row.PublicKeyOrToken = _publicKeyOrToken; row.Name = _name; row.Culture = _culture; row.HashValue = _hashValue; return row; } public AssemblyRefOSRow CreateAssemblyRefOSRow (uint _oSPlatformID, uint _oSMajorVersion, uint _oSMinorVersion, uint _assemblyRef) { AssemblyRefOSRow row = new AssemblyRefOSRow (); row.OSPlatformID = _oSPlatformID; row.OSMajorVersion = _oSMajorVersion; row.OSMinorVersion = _oSMinorVersion; row.AssemblyRef = _assemblyRef; return row; } public AssemblyRefProcessorRow CreateAssemblyRefProcessorRow (uint _processor, uint _assemblyRef) { AssemblyRefProcessorRow row = new AssemblyRefProcessorRow (); row.Processor = _processor; row.AssemblyRef = _assemblyRef; return row; } public ClassLayoutRow CreateClassLayoutRow (ushort _packingSize, uint _classSize, uint _parent) { ClassLayoutRow row = new ClassLayoutRow (); row.PackingSize = _packingSize; row.ClassSize = _classSize; row.Parent = _parent; return row; } public ConstantRow CreateConstantRow (ElementType _type, MetadataToken _parent, uint _value) { ConstantRow row = new ConstantRow (); row.Type = _type; row.Parent = _parent; row.Value = _value; return row; } public CustomAttributeRow CreateCustomAttributeRow (MetadataToken _parent, MetadataToken _type, uint _value) { CustomAttributeRow row = new CustomAttributeRow (); row.Parent = _parent; row.Type = _type; row.Value = _value; return row; } public DeclSecurityRow CreateDeclSecurityRow (SecurityAction _action, MetadataToken _parent, uint _permissionSet) { DeclSecurityRow row = new DeclSecurityRow (); row.Action = _action; row.Parent = _parent; row.PermissionSet = _permissionSet; return row; } public EventRow CreateEventRow (EventAttributes _eventFlags, uint _name, MetadataToken _eventType) { EventRow row = new EventRow (); row.EventFlags = _eventFlags; row.Name = _name; row.EventType = _eventType; return row; } public EventMapRow CreateEventMapRow (uint _parent, uint _eventList) { EventMapRow row = new EventMapRow (); row.Parent = _parent; row.EventList = _eventList; return row; } public EventPtrRow CreateEventPtrRow (uint _event) { EventPtrRow row = new EventPtrRow (); row.Event = _event; return row; } public ExportedTypeRow CreateExportedTypeRow (TypeAttributes _flags, uint _typeDefId, uint _typeName, uint _typeNamespace, MetadataToken _implementation) { ExportedTypeRow row = new ExportedTypeRow (); row.Flags = _flags; row.TypeDefId = _typeDefId; row.TypeName = _typeName; row.TypeNamespace = _typeNamespace; row.Implementation = _implementation; return row; } public FieldRow CreateFieldRow (FieldAttributes _flags, uint _name, uint _signature) { FieldRow row = new FieldRow (); row.Flags = _flags; row.Name = _name; row.Signature = _signature; return row; } public FieldLayoutRow CreateFieldLayoutRow (uint _offset, uint _field) { FieldLayoutRow row = new FieldLayoutRow (); row.Offset = _offset; row.Field = _field; return row; } public FieldMarshalRow CreateFieldMarshalRow (MetadataToken _parent, uint _nativeType) { FieldMarshalRow row = new FieldMarshalRow (); row.Parent = _parent; row.NativeType = _nativeType; return row; } public FieldPtrRow CreateFieldPtrRow (uint _field) { FieldPtrRow row = new FieldPtrRow (); row.Field = _field; return row; } public FieldRVARow CreateFieldRVARow (RVA _rVA, uint _field) { FieldRVARow row = new FieldRVARow (); row.RVA = _rVA; row.Field = _field; return row; } public FileRow CreateFileRow (FileAttributes _flags, uint _name, uint _hashValue) { FileRow row = new FileRow (); row.Flags = _flags; row.Name = _name; row.HashValue = _hashValue; return row; } public GenericParamRow CreateGenericParamRow (ushort _number, GenericParameterAttributes _flags, MetadataToken _owner, uint _name) { GenericParamRow row = new GenericParamRow (); row.Number = _number; row.Flags = _flags; row.Owner = _owner; row.Name = _name; return row; } public GenericParamConstraintRow CreateGenericParamConstraintRow (uint _owner, MetadataToken _constraint) { GenericParamConstraintRow row = new GenericParamConstraintRow (); row.Owner = _owner; row.Constraint = _constraint; return row; } public ImplMapRow CreateImplMapRow (PInvokeAttributes _mappingFlags, MetadataToken _memberForwarded, uint _importName, uint _importScope) { ImplMapRow row = new ImplMapRow (); row.MappingFlags = _mappingFlags; row.MemberForwarded = _memberForwarded; row.ImportName = _importName; row.ImportScope = _importScope; return row; } public InterfaceImplRow CreateInterfaceImplRow (uint _class, MetadataToken _interface) { InterfaceImplRow row = new InterfaceImplRow (); row.Class = _class; row.Interface = _interface; return row; } public ManifestResourceRow CreateManifestResourceRow (uint _offset, ManifestResourceAttributes _flags, uint _name, MetadataToken _implementation) { ManifestResourceRow row = new ManifestResourceRow (); row.Offset = _offset; row.Flags = _flags; row.Name = _name; row.Implementation = _implementation; return row; } public MemberRefRow CreateMemberRefRow (MetadataToken _class, uint _name, uint _signature) { MemberRefRow row = new MemberRefRow (); row.Class = _class; row.Name = _name; row.Signature = _signature; return row; } public MethodRow CreateMethodRow (RVA _rVA, MethodImplAttributes _implFlags, MethodAttributes _flags, uint _name, uint _signature, uint _paramList) { MethodRow row = new MethodRow (); row.RVA = _rVA; row.ImplFlags = _implFlags; row.Flags = _flags; row.Name = _name; row.Signature = _signature; row.ParamList = _paramList; return row; } public MethodImplRow CreateMethodImplRow (uint _class, MetadataToken _methodBody, MetadataToken _methodDeclaration) { MethodImplRow row = new MethodImplRow (); row.Class = _class; row.MethodBody = _methodBody; row.MethodDeclaration = _methodDeclaration; return row; } public MethodPtrRow CreateMethodPtrRow (uint _method) { MethodPtrRow row = new MethodPtrRow (); row.Method = _method; return row; } public MethodSemanticsRow CreateMethodSemanticsRow (MethodSemanticsAttributes _semantics, uint _method, MetadataToken _association) { MethodSemanticsRow row = new MethodSemanticsRow (); row.Semantics = _semantics; row.Method = _method; row.Association = _association; return row; } public MethodSpecRow CreateMethodSpecRow (MetadataToken _method, uint _instantiation) { MethodSpecRow row = new MethodSpecRow (); row.Method = _method; row.Instantiation = _instantiation; return row; } public ModuleRow CreateModuleRow (ushort _generation, uint _name, uint _mvid, uint _encId, uint _encBaseId) { ModuleRow row = new ModuleRow (); row.Generation = _generation; row.Name = _name; row.Mvid = _mvid; row.EncId = _encId; row.EncBaseId = _encBaseId; return row; } public ModuleRefRow CreateModuleRefRow (uint _name) { ModuleRefRow row = new ModuleRefRow (); row.Name = _name; return row; } public NestedClassRow CreateNestedClassRow (uint _nestedClass, uint _enclosingClass) { NestedClassRow row = new NestedClassRow (); row.NestedClass = _nestedClass; row.EnclosingClass = _enclosingClass; return row; } public ParamRow CreateParamRow (ParameterAttributes _flags, ushort _sequence, uint _name) { ParamRow row = new ParamRow (); row.Flags = _flags; row.Sequence = _sequence; row.Name = _name; return row; } public ParamPtrRow CreateParamPtrRow (uint _param) { ParamPtrRow row = new ParamPtrRow (); row.Param = _param; return row; } public PropertyRow CreatePropertyRow (PropertyAttributes _flags, uint _name, uint _type) { PropertyRow row = new PropertyRow (); row.Flags = _flags; row.Name = _name; row.Type = _type; return row; } public PropertyMapRow CreatePropertyMapRow (uint _parent, uint _propertyList) { PropertyMapRow row = new PropertyMapRow (); row.Parent = _parent; row.PropertyList = _propertyList; return row; } public PropertyPtrRow CreatePropertyPtrRow (uint _property) { PropertyPtrRow row = new PropertyPtrRow (); row.Property = _property; return row; } public StandAloneSigRow CreateStandAloneSigRow (uint _signature) { StandAloneSigRow row = new StandAloneSigRow (); row.Signature = _signature; return row; } public TypeDefRow CreateTypeDefRow (TypeAttributes _flags, uint _name, uint _namespace, MetadataToken _extends, uint _fieldList, uint _methodList) { TypeDefRow row = new TypeDefRow (); row.Flags = _flags; row.Name = _name; row.Namespace = _namespace; row.Extends = _extends; row.FieldList = _fieldList; row.MethodList = _methodList; return row; } public TypeRefRow CreateTypeRefRow (MetadataToken _resolutionScope, uint _name, uint _namespace) { TypeRefRow row = new TypeRefRow (); row.ResolutionScope = _resolutionScope; row.Name = _name; row.Namespace = _namespace; return row; } public TypeSpecRow CreateTypeSpecRow (uint _signature) { TypeSpecRow row = new TypeSpecRow (); row.Signature = _signature; return row; } public override void VisitRowCollection (RowCollection coll) { m_blobHeapIdxSz = m_root.Streams.BlobHeap != null ? m_root.Streams.BlobHeap.IndexSize : 2; m_stringsHeapIdxSz = m_root.Streams.StringsHeap != null ? m_root.Streams.StringsHeap.IndexSize : 2; m_guidHeapIdxSz = m_root.Streams.GuidHeap != null ? m_root.Streams.GuidHeap.IndexSize : 2; } public override void VisitAssemblyRow (AssemblyRow row) { m_binaryWriter.Write ((uint) row.HashAlgId); m_binaryWriter.Write (row.MajorVersion); m_binaryWriter.Write (row.MinorVersion); m_binaryWriter.Write (row.BuildNumber); m_binaryWriter.Write (row.RevisionNumber); m_binaryWriter.Write ((uint) row.Flags); WriteBlobPointer (row.PublicKey); WriteStringPointer (row.Name); WriteStringPointer (row.Culture); } public override void VisitAssemblyOSRow (AssemblyOSRow row) { m_binaryWriter.Write (row.OSPlatformID); m_binaryWriter.Write (row.OSMajorVersion); m_binaryWriter.Write (row.OSMinorVersion); } public override void VisitAssemblyProcessorRow (AssemblyProcessorRow row) { m_binaryWriter.Write (row.Processor); } public override void VisitAssemblyRefRow (AssemblyRefRow row) { m_binaryWriter.Write (row.MajorVersion); m_binaryWriter.Write (row.MinorVersion); m_binaryWriter.Write (row.BuildNumber); m_binaryWriter.Write (row.RevisionNumber); m_binaryWriter.Write ((uint) row.Flags); WriteBlobPointer (row.PublicKeyOrToken); WriteStringPointer (row.Name); WriteStringPointer (row.Culture); WriteBlobPointer (row.HashValue); } public override void VisitAssemblyRefOSRow (AssemblyRefOSRow row) { m_binaryWriter.Write (row.OSPlatformID); m_binaryWriter.Write (row.OSMajorVersion); m_binaryWriter.Write (row.OSMinorVersion); WriteTablePointer (row.AssemblyRef, AssemblyRefTable.RId); } public override void VisitAssemblyRefProcessorRow (AssemblyRefProcessorRow row) { m_binaryWriter.Write (row.Processor); WriteTablePointer (row.AssemblyRef, AssemblyRefTable.RId); } public override void VisitClassLayoutRow (ClassLayoutRow row) { m_binaryWriter.Write (row.PackingSize); m_binaryWriter.Write (row.ClassSize); WriteTablePointer (row.Parent, TypeDefTable.RId); } public override void VisitConstantRow (ConstantRow row) { m_binaryWriter.Write ((ushort) row.Type); WriteMetadataToken (row.Parent, CodedIndex.HasConstant); WriteBlobPointer (row.Value); } public override void VisitCustomAttributeRow (CustomAttributeRow row) { WriteMetadataToken (row.Parent, CodedIndex.HasCustomAttribute); WriteMetadataToken (row.Type, CodedIndex.CustomAttributeType); WriteBlobPointer (row.Value); } public override void VisitDeclSecurityRow (DeclSecurityRow row) { m_binaryWriter.Write ((short) row.Action); WriteMetadataToken (row.Parent, CodedIndex.HasDeclSecurity); WriteBlobPointer (row.PermissionSet); } public override void VisitEventRow (EventRow row) { m_binaryWriter.Write ((ushort) row.EventFlags); WriteStringPointer (row.Name); WriteMetadataToken (row.EventType, CodedIndex.TypeDefOrRef); } public override void VisitEventMapRow (EventMapRow row) { WriteTablePointer (row.Parent, TypeDefTable.RId); WriteTablePointer (row.EventList, EventTable.RId); } public override void VisitEventPtrRow (EventPtrRow row) { WriteTablePointer (row.Event, EventTable.RId); } public override void VisitExportedTypeRow (ExportedTypeRow row) { m_binaryWriter.Write ((uint) row.Flags); m_binaryWriter.Write (row.TypeDefId); WriteStringPointer (row.TypeName); WriteStringPointer (row.TypeNamespace); WriteMetadataToken (row.Implementation, CodedIndex.Implementation); } public override void VisitFieldRow (FieldRow row) { m_binaryWriter.Write ((ushort) row.Flags); WriteStringPointer (row.Name); WriteBlobPointer (row.Signature); } public override void VisitFieldLayoutRow (FieldLayoutRow row) { m_binaryWriter.Write (row.Offset); WriteTablePointer (row.Field, FieldTable.RId); } public override void VisitFieldMarshalRow (FieldMarshalRow row) { WriteMetadataToken (row.Parent, CodedIndex.HasFieldMarshal); WriteBlobPointer (row.NativeType); } public override void VisitFieldPtrRow (FieldPtrRow row) { WriteTablePointer (row.Field, FieldTable.RId); } public override void VisitFieldRVARow (FieldRVARow row) { m_binaryWriter.Write (row.RVA.Value); WriteTablePointer (row.Field, FieldTable.RId); } public override void VisitFileRow (FileRow row) { m_binaryWriter.Write ((uint) row.Flags); WriteStringPointer (row.Name); WriteBlobPointer (row.HashValue); } public override void VisitGenericParamRow (GenericParamRow row) { m_binaryWriter.Write (row.Number); m_binaryWriter.Write ((ushort) row.Flags); WriteMetadataToken (row.Owner, CodedIndex.TypeOrMethodDef); WriteStringPointer (row.Name); } public override void VisitGenericParamConstraintRow (GenericParamConstraintRow row) { WriteTablePointer (row.Owner, GenericParamTable.RId); WriteMetadataToken (row.Constraint, CodedIndex.TypeDefOrRef); } public override void VisitImplMapRow (ImplMapRow row) { m_binaryWriter.Write ((ushort) row.MappingFlags); WriteMetadataToken (row.MemberForwarded, CodedIndex.MemberForwarded); WriteStringPointer (row.ImportName); WriteTablePointer (row.ImportScope, ModuleRefTable.RId); } public override void VisitInterfaceImplRow (InterfaceImplRow row) { WriteTablePointer (row.Class, TypeDefTable.RId); WriteMetadataToken (row.Interface, CodedIndex.TypeDefOrRef); } public override void VisitManifestResourceRow (ManifestResourceRow row) { m_binaryWriter.Write (row.Offset); m_binaryWriter.Write ((uint) row.Flags); WriteStringPointer (row.Name); WriteMetadataToken (row.Implementation, CodedIndex.Implementation); } public override void VisitMemberRefRow (MemberRefRow row) { WriteMetadataToken (row.Class, CodedIndex.MemberRefParent); WriteStringPointer (row.Name); WriteBlobPointer (row.Signature); } public override void VisitMethodRow (MethodRow row) { m_binaryWriter.Write (row.RVA.Value); m_binaryWriter.Write ((ushort) row.ImplFlags); m_binaryWriter.Write ((ushort) row.Flags); WriteStringPointer (row.Name); WriteBlobPointer (row.Signature); WriteTablePointer (row.ParamList, ParamTable.RId); } public override void VisitMethodImplRow (MethodImplRow row) { WriteTablePointer (row.Class, TypeDefTable.RId); WriteMetadataToken (row.MethodBody, CodedIndex.MethodDefOrRef); WriteMetadataToken (row.MethodDeclaration, CodedIndex.MethodDefOrRef); } public override void VisitMethodPtrRow (MethodPtrRow row) { WriteTablePointer (row.Method, MethodTable.RId); } public override void VisitMethodSemanticsRow (MethodSemanticsRow row) { m_binaryWriter.Write ((ushort) row.Semantics); WriteTablePointer (row.Method, MethodTable.RId); WriteMetadataToken (row.Association, CodedIndex.HasSemantics); } public override void VisitMethodSpecRow (MethodSpecRow row) { WriteMetadataToken (row.Method, CodedIndex.MethodDefOrRef); WriteBlobPointer (row.Instantiation); } public override void VisitModuleRow (ModuleRow row) { m_binaryWriter.Write (row.Generation); WriteStringPointer (row.Name); WriteGuidPointer (row.Mvid); WriteGuidPointer (row.EncId); WriteGuidPointer (row.EncBaseId); } public override void VisitModuleRefRow (ModuleRefRow row) { WriteStringPointer (row.Name); } public override void VisitNestedClassRow (NestedClassRow row) { WriteTablePointer (row.NestedClass, TypeDefTable.RId); WriteTablePointer (row.EnclosingClass, TypeDefTable.RId); } public override void VisitParamRow (ParamRow row) { m_binaryWriter.Write ((ushort) row.Flags); m_binaryWriter.Write (row.Sequence); WriteStringPointer (row.Name); } public override void VisitParamPtrRow (ParamPtrRow row) { WriteTablePointer (row.Param, ParamTable.RId); } public override void VisitPropertyRow (PropertyRow row) { m_binaryWriter.Write ((ushort) row.Flags); WriteStringPointer (row.Name); WriteBlobPointer (row.Type); } public override void VisitPropertyMapRow (PropertyMapRow row) { WriteTablePointer (row.Parent, TypeDefTable.RId); WriteTablePointer (row.PropertyList, PropertyTable.RId); } public override void VisitPropertyPtrRow (PropertyPtrRow row) { WriteTablePointer (row.Property, PropertyTable.RId); } public override void VisitStandAloneSigRow (StandAloneSigRow row) { WriteBlobPointer (row.Signature); } public override void VisitTypeDefRow (TypeDefRow row) { m_binaryWriter.Write ((uint) row.Flags); WriteStringPointer (row.Name); WriteStringPointer (row.Namespace); WriteMetadataToken (row.Extends, CodedIndex.TypeDefOrRef); WriteTablePointer (row.FieldList, FieldTable.RId); WriteTablePointer (row.MethodList, MethodTable.RId); } public override void VisitTypeRefRow (TypeRefRow row) { WriteMetadataToken (row.ResolutionScope, CodedIndex.ResolutionScope); WriteStringPointer (row.Name); WriteStringPointer (row.Namespace); } public override void VisitTypeSpecRow (TypeSpecRow row) { WriteBlobPointer (row.Signature); } } }
#region copyright // Copyright (c) 2012, TIGWI // All rights reserved. // Distributed under BSD 2-Clause license #endregion namespace Tigwi.UI.Models.Storage { using System; using System.Collections.Generic; using System.Linq; using Tigwi.Storage.Library; /// <summary> /// The user model adapter. /// </summary> public class StorageUserModel : StorageEntityModel, IUserModel { #region Constants and Fields private readonly StorageEntityCollection<StorageAccountModel, IAccountModel> accounts; private IDictionary<Guid, string> apiKeys; private string avatar; private string email; private StorageAccountModel mainAccount; private string login; #endregion #region Constructors and Destructors public StorageUserModel(IStorage storage, StorageContext storageContext, Guid id) : base(storage, storageContext, id) { this.accounts = new StorageEntityCollection<StorageAccountModel, IAccountModel>(storageContext) { FetchIdCollection = () => storage.User.GetAccounts(id), GetId = account => account.Id, GetModel = storageContext.InternalAccounts.InternalFind, ReverseAdd = account => account.InternalUsers.CacheAdd(this), ReverseRemove = account => account.InternalUsers.CacheRemove(this), SaveAdd = account => storage.Account.Add(account.Id, id), SaveRemove = account => storage.Account.Remove(account.Id, id), }; } #endregion #region Public Properties public IDictionary<Guid, string> ApiKeys { get { if (!this.ApiKeysPopulated) { this.PopulateApiKeys(); } return this.apiKeys; } } public ICollection<IAccountModel> Accounts { get { return this.accounts; } } public string Avatar { get { if (!this.AvatarUpdated) { this.Populate(); } return this.avatar; } set { this.avatar = value; this.AvatarUpdated = true; } } public string Email { get { if (!this.EmailUpdated) { this.Populate(); } return this.email; } set { this.email = value; this.EmailUpdated = true; } } public IAccountModel MainAccount { get { if (!this.MainAccountUpdated) { this.Populate(); } return this.mainAccount; } set { // TODO: consistency check this.mainAccount = value is StorageAccountModel ? value as StorageAccountModel : this.StorageContext.InternalAccounts.InternalFind(value.Id); this.MainAccountUpdated = true; } } public string Login { get { this.Populate(); return this.login; } } public string Password { set { this.Storage.User.SetPassword(this.Id, Auth.PasswordAuth.HashPassword(value)); } } internal StorageEntityCollection<StorageAccountModel, IAccountModel> InternalAccounts { get { return this.accounts; } } #endregion #region Properties protected bool AvatarUpdated { get; set; } protected bool EmailUpdated { get; set; } protected bool MainAccountUpdated { get; set; } protected bool IdFetched { get; set; } protected bool ApiKeysPopulated { get; set; } protected override bool InfosUpdated { get { return this.AvatarUpdated || this.EmailUpdated || this.MainAccountUpdated; } set { this.AvatarUpdated = value; this.EmailUpdated = value; this.MainAccountUpdated = value; } } #endregion #region Methods public Guid GenerateApiKey(string applicationName) { if (!this.ApiKeysPopulated) { this.PopulateApiKeys(); } Guid newKey = this.Storage.User.GenerateApiKey(this.Id, applicationName); this.apiKeys.Add(newKey, applicationName); return newKey; } public void DeactivateApiKey(Guid apiKey) { // TODO : Better error checking if (!this.ApiKeysPopulated) { this.PopulateApiKeys(); } if (!this.apiKeys.ContainsKey(apiKey)) return; this.Storage.User.DeactivateApiKey(this.Id, apiKey); this.apiKeys.Remove(apiKey); } internal void PopulateApiKeys() { this.apiKeys = this.Storage.User.ListApiKeys(this.Id); this.ApiKeysPopulated = true; } internal override bool Save() { bool success = true; if (this.Deleted) { try { this.Storage.User.Delete(this.Id); } catch (StorageLibException) { success = false; } } else { if (this.InfosUpdated) { try { this.Storage.User.SetInfo(this.Id, this.Email, this.mainAccount.Id); this.InfosUpdated = false; } catch (StorageLibException) { success = false; } } if (this.accounts != null) { success &= this.accounts.Save(); } } return success; } internal override void Repopulate() { var userInfo = this.Storage.User.GetInfo(this.Id); this.login = userInfo.Login; if (!this.EmailUpdated) { this.email = userInfo.Email; } if (!this.AvatarUpdated) { this.avatar = userInfo.Avatar; } if (!this.MainAccountUpdated) { this.mainAccount = this.StorageContext.InternalAccounts.InternalFind(userInfo.MainAccountId); } this.Populated = true; } #endregion } }
/* * (c) 2008 MOSA - The Managed Operating System Alliance * * Licensed under the terms of the New BSD License. * * Authors: * Simon Wollwage (rootnode) <kintaro@think-in-co.de> */ using poly_subpixel_scale_e = Pictor.Basics.PolySubpixelScale; namespace Pictor { //--------------------------------------------------------EPolyMaxCoord internal enum EPolyMaxCoord { poly_max_coord = (1 << 30) - 1 //----poly_max_coord }; public interface IVectorClipper { int UpScale(double v); int DownScale(int v); void ClipBox(int x1, int y1, int x2, int y2); void ResetClipping(); void MoveTo(int x1, int y1); void LineTo(AntiAliasedRasterizerCells ras, int x2, int y2); }; //------------------------------------------------------rasterizer_sl_clip internal class VectorClipper_DoClip : IVectorClipper { private int MulDiv(double a, double b, double c) { return Basics.Round(a * b / c); } private int xi(int v) { return v; } private int yi(int v) { return v; } public int UpScale(double v) { return Basics.Round(v * (int)poly_subpixel_scale_e.Scale); } public int DownScale(int v) { return v; } //-------------------------------------------------------------------- public VectorClipper_DoClip() { m_clip_box = new RectI(0, 0, 0, 0); m_x1 = (0); m_y1 = (0); m_f1 = (0); m_clipping = (false); } //-------------------------------------------------------------------- public void ResetClipping() { m_clipping = false; } //-------------------------------------------------------------------- public void ClipBox(int x1, int y1, int x2, int y2) { m_clip_box = new RectI(x1, y1, x2, y2); m_clip_box.Normalize(); m_clipping = true; } //-------------------------------------------------------------------- public void MoveTo(int x1, int y1) { m_x1 = x1; m_y1 = y1; if (m_clipping) m_f1 = ClipLiangBarsky.GetClippingFlags(x1, y1, m_clip_box); } //------------------------------------------------------------------------ private void line_clip_y(AntiAliasedRasterizerCells ras, int x1, int y1, int x2, int y2, uint f1, uint f2) { f1 &= 10; f2 &= 10; if ((f1 | f2) == 0) { // Fully visible ras.Line(x1, y1, x2, y2); } else { if (f1 == f2) { // Invisible by Y return; } int tx1 = x1; int ty1 = y1; int tx2 = x2; int ty2 = y2; if ((f1 & 8) != 0) // y1 < Clip.y1 { tx1 = x1 + MulDiv(m_clip_box.y1 - y1, x2 - x1, y2 - y1); ty1 = m_clip_box.y1; } if ((f1 & 2) != 0) // y1 > Clip.y2 { tx1 = x1 + MulDiv(m_clip_box.y2 - y1, x2 - x1, y2 - y1); ty1 = m_clip_box.y2; } if ((f2 & 8) != 0) // y2 < Clip.y1 { tx2 = x1 + MulDiv(m_clip_box.y1 - y1, x2 - x1, y2 - y1); ty2 = m_clip_box.y1; } if ((f2 & 2) != 0) // y2 > Clip.y2 { tx2 = x1 + MulDiv(m_clip_box.y2 - y1, x2 - x1, y2 - y1); ty2 = m_clip_box.y2; } ras.Line(tx1, ty1, tx2, ty2); } } //-------------------------------------------------------------------- public void LineTo(AntiAliasedRasterizerCells ras, int x2, int y2) { if (m_clipping) { uint f2 = ClipLiangBarsky.GetClippingFlags(x2, y2, m_clip_box); if ((m_f1 & 10) == (f2 & 10) && (m_f1 & 10) != 0) { // Invisible by Y m_x1 = x2; m_y1 = y2; m_f1 = f2; return; } int x1 = m_x1; int y1 = m_y1; uint f1 = m_f1; int y3, y4; uint f3, f4; switch (((f1 & 5) << 1) | (f2 & 5)) { case 0: // Visible by X line_clip_y(ras, x1, y1, x2, y2, f1, f2); break; case 1: // x2 > Clip.x2 y3 = y1 + MulDiv(m_clip_box.x2 - x1, y2 - y1, x2 - x1); f3 = ClipLiangBarsky.ClippingFlagsY(y3, m_clip_box); line_clip_y(ras, x1, y1, m_clip_box.x2, y3, f1, f3); line_clip_y(ras, m_clip_box.x2, y3, m_clip_box.x2, y2, f3, f2); break; case 2: // x1 > Clip.x2 y3 = y1 + MulDiv(m_clip_box.x2 - x1, y2 - y1, x2 - x1); f3 = ClipLiangBarsky.ClippingFlagsY(y3, m_clip_box); line_clip_y(ras, m_clip_box.x2, y1, m_clip_box.x2, y3, f1, f3); line_clip_y(ras, m_clip_box.x2, y3, x2, y2, f3, f2); break; case 3: // x1 > Clip.x2 && x2 > Clip.x2 line_clip_y(ras, m_clip_box.x2, y1, m_clip_box.x2, y2, f1, f2); break; case 4: // x2 < Clip.x1 y3 = y1 + MulDiv(m_clip_box.x1 - x1, y2 - y1, x2 - x1); f3 = ClipLiangBarsky.ClippingFlagsY(y3, m_clip_box); line_clip_y(ras, x1, y1, m_clip_box.x1, y3, f1, f3); line_clip_y(ras, m_clip_box.x1, y3, m_clip_box.x1, y2, f3, f2); break; case 6: // x1 > Clip.x2 && x2 < Clip.x1 y3 = y1 + MulDiv(m_clip_box.x2 - x1, y2 - y1, x2 - x1); y4 = y1 + MulDiv(m_clip_box.x1 - x1, y2 - y1, x2 - x1); f3 = ClipLiangBarsky.ClippingFlagsY(y3, m_clip_box); f4 = ClipLiangBarsky.ClippingFlagsY(y4, m_clip_box); line_clip_y(ras, m_clip_box.x2, y1, m_clip_box.x2, y3, f1, f3); line_clip_y(ras, m_clip_box.x2, y3, m_clip_box.x1, y4, f3, f4); line_clip_y(ras, m_clip_box.x1, y4, m_clip_box.x1, y2, f4, f2); break; case 8: // x1 < Clip.x1 y3 = y1 + MulDiv(m_clip_box.x1 - x1, y2 - y1, x2 - x1); f3 = ClipLiangBarsky.ClippingFlagsY(y3, m_clip_box); line_clip_y(ras, m_clip_box.x1, y1, m_clip_box.x1, y3, f1, f3); line_clip_y(ras, m_clip_box.x1, y3, x2, y2, f3, f2); break; case 9: // x1 < Clip.x1 && x2 > Clip.x2 y3 = y1 + MulDiv(m_clip_box.x1 - x1, y2 - y1, x2 - x1); y4 = y1 + MulDiv(m_clip_box.x2 - x1, y2 - y1, x2 - x1); f3 = ClipLiangBarsky.ClippingFlagsY(y3, m_clip_box); f4 = ClipLiangBarsky.ClippingFlagsY(y4, m_clip_box); line_clip_y(ras, m_clip_box.x1, y1, m_clip_box.x1, y3, f1, f3); line_clip_y(ras, m_clip_box.x1, y3, m_clip_box.x2, y4, f3, f4); line_clip_y(ras, m_clip_box.x2, y4, m_clip_box.x2, y2, f4, f2); break; case 12: // x1 < Clip.x1 && x2 < Clip.x1 line_clip_y(ras, m_clip_box.x1, y1, m_clip_box.x1, y2, f1, f2); break; } m_f1 = f2; } else { ras.Line(m_x1, m_y1, x2, y2); } m_x1 = x2; m_y1 = y2; } private RectI m_clip_box; private int m_x1; private int m_y1; private uint m_f1; private bool m_clipping; }; //---------------------------------------------------rasterizer_sl_no_clip internal class VectorClipper_NoClip : IVectorClipper { public VectorClipper_NoClip() { } public int UpScale(double v) { return Basics.Round(v * (int)poly_subpixel_scale_e.Scale); } public int DownScale(int v) { return v; } public void ResetClipping() { } public void ClipBox(int x1, int y1, int x2, int y2) { } public void MoveTo(int x1, int y1) { m_x1 = x1; m_y1 = y1; } public void LineTo(AntiAliasedRasterizerCells ras, int x2, int y2) { ras.Line(m_x1, m_y1, x2, y2); m_x1 = x2; m_y1 = y2; } private int m_x1; private int m_y1; }; }
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Claims; using System.Security.Principal; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Tracing; using Microsoft.Azure.Mobile.Server; using Microsoft.Azure.Mobile.Server.Authentication; using Microsoft.Azure.Mobile.Server.Config; using Microsoft.Azure.Mobile.Server.Notifications; using Microsoft.Azure.NotificationHubs; using Microsoft.Azure.NotificationHubs.Messaging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ZumoE2EServerApp.Controllers { [MobileAppController] public class PushApiController : ApiController { private ITraceWriter traceWriter; private PushClient pushClient; protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); this.traceWriter = this.Configuration.Services.GetTraceWriter(); this.pushClient = new PushClient(this.Configuration); } [Route("api/push")] public async Task<HttpResponseMessage> Post() { var data = await this.Request.Content.ReadAsAsync<JObject>(); var method = (string)data["method"]; if (method == null) { return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest); } if (method == "send") { var serialize = new JsonSerializer(); var token = (string)data["token"]; if (data["payload"] == null || token == null) { return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest); } // Payload could be a string or a dictionary var payloadString = data["payload"].ToString(); var type = (string)data["type"]; var tag = (string)data["tag"]; if (type == "template") { TemplatePushMessage message = new TemplatePushMessage(); var payload = JObject.Parse(payloadString); var keys = payload.Properties(); foreach (JProperty key in keys) { this.traceWriter.Info("Key: " + key.Name); message.Add(key.Name, (string)key.Value); } var result = await this.pushClient.SendAsync(message, "World"); } else if (type == "gcm") { GooglePushMessage message = new GooglePushMessage(); message.JsonPayload = payloadString; var result = await this.pushClient.SendAsync(message); } else if (type == "apns") { ApplePushMessage message = new ApplePushMessage(); this.traceWriter.Info(payloadString.ToString()); message.JsonPayload = payloadString.ToString(); var result = await this.pushClient.SendAsync(message); } else if (type == "wns") { var wnsType = (string)data["wnsType"]; WindowsPushMessage message = new WindowsPushMessage(); message.XmlPayload = payloadString; message.Headers.Add("X-WNS-Type", type + '/' + wnsType); if (tag != null) { await this.pushClient.SendAsync(message, tag); } else { await this.pushClient.SendAsync(message); } } } else { return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest); } return new HttpResponseMessage(System.Net.HttpStatusCode.OK); } [Route("api/verifyRegisterInstallationResult")] public async Task<bool> GetVerifyRegisterInstallationResult(string channelUri, string templates = null, string secondaryTiles = null) { var nhClient = this.GetNhClient(); HttpResponseMessage msg = new HttpResponseMessage(); msg.StatusCode = HttpStatusCode.InternalServerError; IEnumerable<string> installationIds; if (this.Request.Headers.TryGetValues("X-ZUMO-INSTALLATION-ID", out installationIds)) { return await Retry(async () => { var installationId = installationIds.FirstOrDefault(); Installation nhInstallation = await nhClient.GetInstallationAsync(installationId); string nhTemplates = null; string nhSecondaryTiles = null; if (nhInstallation.Templates != null) { nhTemplates = JsonConvert.SerializeObject(nhInstallation.Templates); nhTemplates = Regex.Replace(nhTemplates, @"\s+", String.Empty); templates = Regex.Replace(templates, @"\s+", String.Empty); } if (nhInstallation.SecondaryTiles != null) { nhSecondaryTiles = JsonConvert.SerializeObject(nhInstallation.SecondaryTiles); nhSecondaryTiles = Regex.Replace(nhSecondaryTiles, @"\s+", String.Empty); secondaryTiles = Regex.Replace(secondaryTiles, @"\s+", String.Empty); } if (nhInstallation.PushChannel.ToLower() != channelUri.ToLower()) { msg.Content = new StringContent(string.Format("ChannelUri did not match. Expected {0} Found {1}", channelUri, nhInstallation.PushChannel)); throw new HttpResponseException(msg); } if (templates != nhTemplates) { msg.Content = new StringContent(string.Format("Templates did not match. Expected {0} Found {1}", templates, nhTemplates)); throw new HttpResponseException(msg); } if (secondaryTiles != nhSecondaryTiles) { msg.Content = new StringContent(string.Format("SecondaryTiles did not match. Expected {0} Found {1}", secondaryTiles, nhSecondaryTiles)); throw new HttpResponseException(msg); } bool tagsVerified = await VerifyTags(channelUri, installationId, nhClient); if (!tagsVerified) { msg.Content = new StringContent("Did not find installationId tag"); throw new HttpResponseException(msg); } return true; }); } msg.Content = new StringContent("Did not find X-ZUMO-INSTALLATION-ID header in the incoming request"); throw new HttpResponseException(msg); } [Route("api/verifyUnregisterInstallationResult")] public async Task<bool> GetVerifyUnregisterInstallationResult() { IEnumerable<string> installationIds; string responseErrorMessage = null; if (this.Request.Headers.TryGetValues("X-ZUMO-INSTALLATION-ID", out installationIds)) { return await Retry(async () => { var installationId = installationIds.FirstOrDefault(); try { Installation nhInstallation = await this.GetNhClient().GetInstallationAsync(installationId); } catch (MessagingEntityNotFoundException) { return true; } responseErrorMessage = string.Format("Found deleted Installation with id {0}", installationId); return false; }); } HttpResponseMessage msg = new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(responseErrorMessage) }; throw new HttpResponseException(msg); } [Route("api/deleteRegistrationsForChannel")] public async Task DeleteRegistrationsForChannel(string channelUri) { await Retry(async () => { await this.GetNhClient().DeleteRegistrationsByChannelAsync(channelUri); return true; }); } [Route("api/register")] public void Register(string data) { var installation = JsonConvert.DeserializeObject<Installation>(data); new PushClient(this.Configuration).HubClient.CreateOrUpdateInstallation(installation); } private NotificationHubClient GetNhClient() { var settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; return NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName); } private async Task<bool> VerifyTags(string channelUri, string installationId, NotificationHubClient nhClient) { IPrincipal user = this.User; int expectedTagsCount = 1; if (user.Identity != null && user.Identity.IsAuthenticated) { expectedTagsCount = 2; } string continuationToken = null; do { CollectionQueryResult<RegistrationDescription> regsForChannel = await nhClient.GetRegistrationsByChannelAsync(channelUri, continuationToken, 100); continuationToken = regsForChannel.ContinuationToken; foreach (RegistrationDescription reg in regsForChannel) { RegistrationDescription registration = await nhClient.GetRegistrationAsync<RegistrationDescription>(reg.RegistrationId); if (registration.Tags == null || registration.Tags.Count() != expectedTagsCount) { return false; } if (!registration.Tags.Contains("$InstallationId:{" + installationId + "}")) { return false; } ClaimsIdentity identity = user.Identity as ClaimsIdentity; Claim userIdClaim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); string userId = (userIdClaim != null) ? userIdClaim.Value : string.Empty; if (expectedTagsCount > 1 && !registration.Tags.Contains("_UserId:" + userId)) { return false; } } } while (continuationToken != null); return true; } private async Task<bool> Retry(Func<Task<bool>> target) { var sleepTimes = new int[3] { 1000, 3000, 5000 }; for (var i = 0; i < sleepTimes.Length; i++) { System.Threading.Thread.Sleep(sleepTimes[i]); try { // if the call succeeds, return the result return await target(); } catch (Exception) { // if an exception was thrown and we've already retried three times, rethrow if (i == 2) throw; } } return false; } } }
// 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.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// A class that writes both primitive values and non-cyclical object graphs to a stream that may be /// later read back using the ObjectReader class. /// </summary> internal sealed class ObjectWriter : ObjectReaderWriterBase, IDisposable { private readonly BinaryWriter _writer; private readonly ObjectWriterData _dataMap; private readonly RecordingObjectBinder _binder; private readonly CancellationToken _cancellationToken; internal ObjectWriter( Stream stream, ObjectWriterData defaultData = null, RecordingObjectBinder binder = null, CancellationToken cancellationToken = default(CancellationToken)) { // String serialization assumes both reader and writer to be of the same endianness. // It can be adjusted for BigEndian if needed. Debug.Assert(BitConverter.IsLittleEndian); _writer = new BinaryWriter(stream, Encoding.UTF8); _dataMap = new ObjectWriterData(defaultData); _binder = binder ?? new SimpleRecordingObjectBinder(); _cancellationToken = cancellationToken; } public ObjectBinder Binder { get { return _binder; } } public void Dispose() { _dataMap.Dispose(); } /// <summary> /// Writes a Boolean value to the stream. /// </summary> public void WriteBoolean(bool value) { _writer.Write(value); } /// <summary> /// Writes a Byte value to the stream. /// </summary> public void WriteByte(byte value) { _writer.Write(value); } /// <summary> /// Writes a Char value to the stream. /// </summary> public void WriteChar(char ch) { // write as UInt16 because binary writer fails on chars that are unicode surrogates _writer.Write((ushort)ch); } /// <summary> /// Writes a Decimal value to the stream. /// </summary> public void WriteDecimal(decimal value) { _writer.Write(value); } /// <summary> /// Writes a Double value to the stream. /// </summary> public void WriteDouble(double value) { _writer.Write(value); } /// <summary> /// Writes a Single value to the stream. /// </summary> public void WriteSingle(float value) { _writer.Write(value); } /// <summary> /// Writes a Int32 value to the stream. /// </summary> public void WriteInt32(int value) { _writer.Write(value); } /// <summary> /// Writes a Int64 value to the stream. /// </summary> public void WriteInt64(long value) { _writer.Write(value); } /// <summary> /// Writes a SByte value to the stream. /// </summary> public void WriteSByte(sbyte value) { _writer.Write(value); } /// <summary> /// Writes a Int16 value to the stream. /// </summary> public void WriteInt16(short value) { _writer.Write(value); } /// <summary> /// Writes a UInt32 value to the stream. /// </summary> public void WriteUInt32(uint value) { _writer.Write(value); } /// <summary> /// Writes a UInt64 value to the stream. /// </summary> public void WriteUInt64(ulong value) { _writer.Write(value); } /// <summary> /// Writes a UInt16 value to the stream. /// </summary> public void WriteUInt16(ushort value) { _writer.Write(value); } /// <summary> /// Writes a DateTime value to the stream. /// </summary> public void WriteDateTime(DateTime value) { this.WriteInt64(value.ToBinary()); } /// <summary> /// Writes a compressed 30 bit integer to the stream. (not 32 bit) /// </summary> public void WriteCompressedUInt(uint value) { if (value <= (byte.MaxValue >> 2)) { _writer.Write((byte)value); } else if (value <= (ushort.MaxValue >> 2)) { byte byte0 = (byte)(((value >> 8) & 0xFF) | Byte2Marker); byte byte1 = (byte)(value & 0xFF); // high-bytes to low-bytes _writer.Write(byte0); _writer.Write(byte1); } else if (value <= (uint.MaxValue >> 2)) { // high-bytes to low-bytes byte byte0 = (byte)(((value >> 24) & 0xFF) | Byte4Marker); byte byte1 = (byte)((value >> 16) & 0xFF); byte byte2 = (byte)((value >> 8) & 0xFF); byte byte3 = (byte)(value & 0xFF); // hit-bits with 4-byte marker _writer.Write(byte0); _writer.Write(byte1); _writer.Write(byte2); _writer.Write(byte3); } else { #if COMPILERCORE throw new ArgumentException(CodeAnalysisResources.ValueTooLargeToBeRepresented); #else throw new ArgumentException(WorkspacesResources.Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer); #endif } } /// <summary> /// Writes a String value to the stream. /// </summary> public unsafe void WriteString(string value) { if (value == null) { _writer.Write((byte)DataKind.Null); } else { int id; if (_dataMap.TryGetId(value, out id)) { Debug.Assert(id >= 0); if (id <= byte.MaxValue) { _writer.Write((byte)DataKind.StringRef_B); _writer.Write((byte)id); } else if (id <= ushort.MaxValue) { _writer.Write((byte)DataKind.StringRef_S); _writer.Write((ushort)id); } else { _writer.Write((byte)DataKind.StringRef); _writer.Write(id); } } else { _dataMap.Add(value); if (value.IsValidUnicodeString()) { // Usual case - the string can be encoded as UTF8: // We can use the UTF8 encoding of the binary writer. _writer.Write((byte)DataKind.StringUtf8); _writer.Write(value); } else { _writer.Write((byte)DataKind.StringUtf16); // This is rare, just allocate UTF16 bytes for simplicity. byte[] bytes = new byte[(uint)value.Length * sizeof(char)]; fixed (char* valuePtr = value) { Marshal.Copy((IntPtr)valuePtr, bytes, 0, bytes.Length); } WriteCompressedUInt((uint)value.Length); _writer.Write(bytes); } } } } /// <summary> /// Writes any value (primitive or object graph) to the stream. /// </summary> public void WriteValue(object value) { if (value == null) { _writer.Write((byte)DataKind.Null); } else { var type = value.GetType(); if (type.GetTypeInfo().IsEnum) { WriteEnum(value, type); } else if (type == typeof(bool)) { if ((bool)value) { _writer.Write((byte)DataKind.Boolean_T); } else { _writer.Write((byte)DataKind.Boolean_F); } } else if (type == typeof(int)) { int v = (int)value; if (v == 0) { _writer.Write((byte)DataKind.Int32_Z); } else if (v >= 0 && v < byte.MaxValue) { _writer.Write((byte)DataKind.Int32_B); _writer.Write((byte)v); } else if (v >= 0 && v < ushort.MaxValue) { _writer.Write((byte)DataKind.Int32_S); _writer.Write((ushort)v); } else { _writer.Write((byte)DataKind.Int32); _writer.Write(v); } } else if (type == typeof(string)) { this.WriteString((string)value); } else if (type == typeof(short)) { _writer.Write((byte)DataKind.Int16); _writer.Write((short)value); } else if (type == typeof(long)) { _writer.Write((byte)DataKind.Int64); _writer.Write((long)value); } else if (type == typeof(char)) { _writer.Write((byte)DataKind.Char); this.WriteChar((char)value); } else if (type == typeof(sbyte)) { _writer.Write((byte)DataKind.Int8); _writer.Write((sbyte)value); } else if (type == typeof(byte)) { _writer.Write((byte)DataKind.UInt8); _writer.Write((byte)value); } else if (type == typeof(ushort)) { _writer.Write((byte)DataKind.UInt16); _writer.Write((ushort)value); } else if (type == typeof(uint)) { _writer.Write((byte)DataKind.UInt32); _writer.Write((uint)value); } else if (type == typeof(ulong)) { _writer.Write((byte)DataKind.UInt64); _writer.Write((ulong)value); } else if (type == typeof(decimal)) { _writer.Write((byte)DataKind.Decimal); _writer.Write((decimal)value); } else if (type == typeof(float)) { _writer.Write((byte)DataKind.Float4); _writer.Write((float)value); } else if (type == typeof(double)) { _writer.Write((byte)DataKind.Float8); _writer.Write((double)value); } else if (type == typeof(DateTime)) { _writer.Write((byte)DataKind.DateTime); this.WriteDateTime((DateTime)value); } else if (type.IsArray) { this.WriteArray((Array)value); } else if (value is Type) { this.WriteType((Type)value); } else { this.WriteObject(value); } } } private void WriteEnum(object value, Type enumType) { _writer.Write((byte)DataKind.Enum); this.WriteType(enumType); var type = Enum.GetUnderlyingType(enumType); if (type == typeof(int)) { _writer.Write((int)value); } else if (type == typeof(short)) { _writer.Write((short)value); } else if (type == typeof(byte)) { _writer.Write((byte)value); } else if (type == typeof(long)) { _writer.Write((long)value); } else if (type == typeof(sbyte)) { _writer.Write((sbyte)value); } else if (type == typeof(ushort)) { _writer.Write((ushort)value); } else if (type == typeof(uint)) { _writer.Write((uint)value); } else if (type == typeof(ulong)) { _writer.Write((ulong)value); } else { throw ExceptionUtilities.UnexpectedValue(type); } } private void WriteArray(Array instance) { if (instance.Rank > 1) { #if COMPILERCORE throw new InvalidOperationException(CodeAnalysisResources.ArraysWithMoreThanOneDimensionCannotBeSerialized); #else throw new InvalidOperationException(WorkspacesResources.Arrays_with_more_than_one_dimension_cannot_be_serialized); #endif } int length = instance.GetLength(0); switch (length) { case 0: _writer.Write((byte)DataKind.Array_0); break; case 1: _writer.Write((byte)DataKind.Array_1); break; case 2: _writer.Write((byte)DataKind.Array_2); break; case 3: _writer.Write((byte)DataKind.Array_3); break; default: _writer.Write((byte)DataKind.Array); this.WriteCompressedUInt((uint)length); break; } var elementType = instance.GetType().GetElementType(); this.WriteType(elementType); // optimizations for supported array type by binary writer if (elementType == typeof(byte)) { _writer.Write((byte[])instance); return; } if (elementType == typeof(char)) { _writer.Write((char[])instance); return; } for (int i = 0; i < length; i++) { this.WriteValue(instance.GetValue(i)); } } private void WriteType(Type type) { // optimization. primitive types if (type == typeof(byte)) { _writer.Write((byte)DataKind.UInt8); return; } if (type == typeof(char)) { _writer.Write((byte)DataKind.Char); return; } int id; if (_dataMap.TryGetId(type, out id)) { Debug.Assert(id >= 0); if (id <= byte.MaxValue) { _writer.Write((byte)DataKind.TypeRef_B); _writer.Write((byte)id); } else if (id <= ushort.MaxValue) { _writer.Write((byte)DataKind.TypeRef_S); _writer.Write((ushort)id); } else { _writer.Write((byte)DataKind.TypeRef); _writer.Write(id); } } else { _dataMap.Add(type); _binder?.Record(type); _writer.Write((byte)DataKind.Type); string assemblyName = type.GetTypeInfo().Assembly.FullName; string typeName = type.FullName; // assembly name this.WriteString(assemblyName); // type name this.WriteString(typeName); } } private void WriteObject(object instance) { _cancellationToken.ThrowIfCancellationRequested(); // write object ref if we already know this instance int id; if (_dataMap.TryGetId(instance, out id)) { Debug.Assert(id >= 0); if (id <= byte.MaxValue) { _writer.Write((byte)DataKind.ObjectRef_B); _writer.Write((byte)id); } else if (id <= ushort.MaxValue) { _writer.Write((byte)DataKind.ObjectRef_S); _writer.Write((ushort)id); } else { _writer.Write((byte)DataKind.ObjectRef); _writer.Write(id); } } else { // otherwise add this instance to the map _dataMap.Add(instance); var iwriteable = instance as IObjectWritable; if (iwriteable != null) { this.WriteWritableObject(iwriteable); return; } throw NotWritableException(instance.GetType().FullName); } } private void WriteWritableObject(IObjectWritable instance) { _writer.Write((byte)DataKind.Object_W); Type type = instance.GetType(); this.WriteType(type); _binder?.Record(instance); instance.WriteTo(this); } private static Exception NotWritableException(string typeName) { #if COMPILERCORE throw new InvalidOperationException(string.Format(CodeAnalysisResources.NotWritableException, typeName)); #else throw new InvalidOperationException(string.Format(WorkspacesResources.The_type_0_cannot_be_written_it_does_not_implement_IObjectWritable, typeName)); #endif } } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects.GuiControls { public unsafe class GuiDynamicCtrlArrayControl : GuiControl { public GuiDynamicCtrlArrayControl() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.GuiDynamicCtrlArrayControlCreateInstance()); } public GuiDynamicCtrlArrayControl(uint pId) : base(pId) { } public GuiDynamicCtrlArrayControl(string pName) : base(pName) { } public GuiDynamicCtrlArrayControl(IntPtr pObjPtr) : base(pObjPtr) { } public GuiDynamicCtrlArrayControl(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public GuiDynamicCtrlArrayControl(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiDynamicCtrlArrayControlGetColCount(IntPtr ctrl); private static _GuiDynamicCtrlArrayControlGetColCount _GuiDynamicCtrlArrayControlGetColCountFunc; internal static int GuiDynamicCtrlArrayControlGetColCount(IntPtr ctrl) { if (_GuiDynamicCtrlArrayControlGetColCountFunc == null) { _GuiDynamicCtrlArrayControlGetColCountFunc = (_GuiDynamicCtrlArrayControlGetColCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlGetColCount"), typeof(_GuiDynamicCtrlArrayControlGetColCount)); } return _GuiDynamicCtrlArrayControlGetColCountFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiDynamicCtrlArrayControlSetColCount(IntPtr ctrl, int cols); private static _GuiDynamicCtrlArrayControlSetColCount _GuiDynamicCtrlArrayControlSetColCountFunc; internal static void GuiDynamicCtrlArrayControlSetColCount(IntPtr ctrl, int cols) { if (_GuiDynamicCtrlArrayControlSetColCountFunc == null) { _GuiDynamicCtrlArrayControlSetColCountFunc = (_GuiDynamicCtrlArrayControlSetColCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlSetColCount"), typeof(_GuiDynamicCtrlArrayControlSetColCount)); } _GuiDynamicCtrlArrayControlSetColCountFunc(ctrl, cols); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiDynamicCtrlArrayControlGetColSize(IntPtr ctrl); private static _GuiDynamicCtrlArrayControlGetColSize _GuiDynamicCtrlArrayControlGetColSizeFunc; internal static int GuiDynamicCtrlArrayControlGetColSize(IntPtr ctrl) { if (_GuiDynamicCtrlArrayControlGetColSizeFunc == null) { _GuiDynamicCtrlArrayControlGetColSizeFunc = (_GuiDynamicCtrlArrayControlGetColSize)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlGetColSize"), typeof(_GuiDynamicCtrlArrayControlGetColSize)); } return _GuiDynamicCtrlArrayControlGetColSizeFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiDynamicCtrlArrayControlSetColSize(IntPtr ctrl, int colSize); private static _GuiDynamicCtrlArrayControlSetColSize _GuiDynamicCtrlArrayControlSetColSizeFunc; internal static void GuiDynamicCtrlArrayControlSetColSize(IntPtr ctrl, int colSize) { if (_GuiDynamicCtrlArrayControlSetColSizeFunc == null) { _GuiDynamicCtrlArrayControlSetColSizeFunc = (_GuiDynamicCtrlArrayControlSetColSize)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlSetColSize"), typeof(_GuiDynamicCtrlArrayControlSetColSize)); } _GuiDynamicCtrlArrayControlSetColSizeFunc(ctrl, colSize); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiDynamicCtrlArrayControlGetRowSize(IntPtr ctrl); private static _GuiDynamicCtrlArrayControlGetRowSize _GuiDynamicCtrlArrayControlGetRowSizeFunc; internal static int GuiDynamicCtrlArrayControlGetRowSize(IntPtr ctrl) { if (_GuiDynamicCtrlArrayControlGetRowSizeFunc == null) { _GuiDynamicCtrlArrayControlGetRowSizeFunc = (_GuiDynamicCtrlArrayControlGetRowSize)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlGetRowSize"), typeof(_GuiDynamicCtrlArrayControlGetRowSize)); } return _GuiDynamicCtrlArrayControlGetRowSizeFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiDynamicCtrlArrayControlSetRowSize(IntPtr ctrl, int size); private static _GuiDynamicCtrlArrayControlSetRowSize _GuiDynamicCtrlArrayControlSetRowSizeFunc; internal static void GuiDynamicCtrlArrayControlSetRowSize(IntPtr ctrl, int size) { if (_GuiDynamicCtrlArrayControlSetRowSizeFunc == null) { _GuiDynamicCtrlArrayControlSetRowSizeFunc = (_GuiDynamicCtrlArrayControlSetRowSize)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlSetRowSize"), typeof(_GuiDynamicCtrlArrayControlSetRowSize)); } _GuiDynamicCtrlArrayControlSetRowSizeFunc(ctrl, size); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiDynamicCtrlArrayControlGetRowSpacing(IntPtr ctrl); private static _GuiDynamicCtrlArrayControlGetRowSpacing _GuiDynamicCtrlArrayControlGetRowSpacingFunc; internal static int GuiDynamicCtrlArrayControlGetRowSpacing(IntPtr ctrl) { if (_GuiDynamicCtrlArrayControlGetRowSpacingFunc == null) { _GuiDynamicCtrlArrayControlGetRowSpacingFunc = (_GuiDynamicCtrlArrayControlGetRowSpacing)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlGetRowSpacing"), typeof(_GuiDynamicCtrlArrayControlGetRowSpacing)); } return _GuiDynamicCtrlArrayControlGetRowSpacingFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiDynamicCtrlArrayControlSetRowSpacing(IntPtr ctrl, int Spacing); private static _GuiDynamicCtrlArrayControlSetRowSpacing _GuiDynamicCtrlArrayControlSetRowSpacingFunc; internal static void GuiDynamicCtrlArrayControlSetRowSpacing(IntPtr ctrl, int Spacing) { if (_GuiDynamicCtrlArrayControlSetRowSpacingFunc == null) { _GuiDynamicCtrlArrayControlSetRowSpacingFunc = (_GuiDynamicCtrlArrayControlSetRowSpacing)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlSetRowSpacing"), typeof(_GuiDynamicCtrlArrayControlSetRowSpacing)); } _GuiDynamicCtrlArrayControlSetRowSpacingFunc(ctrl, Spacing); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiDynamicCtrlArrayControlGetColSpacing(IntPtr ctrl); private static _GuiDynamicCtrlArrayControlGetColSpacing _GuiDynamicCtrlArrayControlGetColSpacingFunc; internal static int GuiDynamicCtrlArrayControlGetColSpacing(IntPtr ctrl) { if (_GuiDynamicCtrlArrayControlGetColSpacingFunc == null) { _GuiDynamicCtrlArrayControlGetColSpacingFunc = (_GuiDynamicCtrlArrayControlGetColSpacing)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlGetColSpacing"), typeof(_GuiDynamicCtrlArrayControlGetColSpacing)); } return _GuiDynamicCtrlArrayControlGetColSpacingFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiDynamicCtrlArrayControlSetColSpacing(IntPtr ctrl, int Spacing); private static _GuiDynamicCtrlArrayControlSetColSpacing _GuiDynamicCtrlArrayControlSetColSpacingFunc; internal static void GuiDynamicCtrlArrayControlSetColSpacing(IntPtr ctrl, int Spacing) { if (_GuiDynamicCtrlArrayControlSetColSpacingFunc == null) { _GuiDynamicCtrlArrayControlSetColSpacingFunc = (_GuiDynamicCtrlArrayControlSetColSpacing)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlSetColSpacing"), typeof(_GuiDynamicCtrlArrayControlSetColSpacing)); } _GuiDynamicCtrlArrayControlSetColSpacingFunc(ctrl, Spacing); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiDynamicCtrlArrayControlCreateInstance(); private static _GuiDynamicCtrlArrayControlCreateInstance _GuiDynamicCtrlArrayControlCreateInstanceFunc; internal static IntPtr GuiDynamicCtrlArrayControlCreateInstance() { if (_GuiDynamicCtrlArrayControlCreateInstanceFunc == null) { _GuiDynamicCtrlArrayControlCreateInstanceFunc = (_GuiDynamicCtrlArrayControlCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlCreateInstance"), typeof(_GuiDynamicCtrlArrayControlCreateInstance)); } return _GuiDynamicCtrlArrayControlCreateInstanceFunc(); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiDynamicCtrlArrayControlRefresh(IntPtr ctrl); private static _GuiDynamicCtrlArrayControlRefresh _GuiDynamicCtrlArrayControlRefreshFunc; internal static void GuiDynamicCtrlArrayControlRefresh(IntPtr ctrl) { if (_GuiDynamicCtrlArrayControlRefreshFunc == null) { _GuiDynamicCtrlArrayControlRefreshFunc = (_GuiDynamicCtrlArrayControlRefresh)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiDynamicCtrlArrayControlRefresh"), typeof(_GuiDynamicCtrlArrayControlRefresh)); } _GuiDynamicCtrlArrayControlRefreshFunc(ctrl); } } #endregion #region Properties public int ColCount { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiDynamicCtrlArrayControlGetColCount(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiDynamicCtrlArrayControlSetColCount(ObjectPtr->ObjPtr, value); } } public int ColSize { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiDynamicCtrlArrayControlGetColSize(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiDynamicCtrlArrayControlSetColSize(ObjectPtr->ObjPtr, value); } } public int RowSize { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiDynamicCtrlArrayControlGetRowSize(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiDynamicCtrlArrayControlSetRowSize(ObjectPtr->ObjPtr, value); } } public int RowSpacing { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiDynamicCtrlArrayControlGetRowSpacing(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiDynamicCtrlArrayControlSetRowSpacing(ObjectPtr->ObjPtr, value); } } public int ColSpacing { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiDynamicCtrlArrayControlGetColSpacing(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiDynamicCtrlArrayControlSetColSpacing(ObjectPtr->ObjPtr, value); } } #endregion #region Methods public void Refresh() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiDynamicCtrlArrayControlRefresh(ObjectPtr->ObjPtr); } #endregion } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // // Adaptation for high precision colors has been sponsored by // Liberty Technology Systems, Inc., visit http://lib-sys.com // // Liberty Technology Systems, Inc. is the provider of // PostScript and PDF technology for software developers. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using System; namespace MatterHackers.Agg { // Supported byte orders for RGB and RGBA pixel formats //======================================================================= internal struct order_rgb { private enum rgb_e { R = 0, G = 1, B = 2, rgb_tag }; }; //----order_rgb internal struct order_bgr { private enum bgr_e { B = 0, G = 1, R = 2, rgb_tag }; }; //----order_bgr internal struct order_rgba { private enum rgba_e { R = 0, G = 1, B = 2, A = 3, rgba_tag }; }; //----order_rgba internal struct order_argb { private enum argb_e { A = 0, R = 1, G = 2, B = 3, rgba_tag }; }; //----order_argb internal struct order_abgr { private enum abgr_e { A = 0, B = 1, G = 2, R = 3, rgba_tag }; }; //----order_abgr internal struct order_bgra { private enum bgra_e { B = 0, G = 1, R = 2, A = 3, rgba_tag }; }; //----order_bgra public struct RGBA_Floats : IColorType { private const int base_shift = 8; private const int base_scale = (int)(1 << base_shift); private const int base_mask = base_scale - 1; public float red; public float green; public float blue; public float alpha; public int Red0To255 { get { return (int)agg_basics.uround(red * (float)base_mask); } set { red = (float)value / (float)base_mask; } } public int Green0To255 { get { return (int)agg_basics.uround(green * (float)base_mask); } set { green = (float)value / (float)base_mask; } } public int Blue0To255 { get { return (int)agg_basics.uround(blue * (float)base_mask); } set { blue = (float)value / (float)base_mask; } } public int Alpha0To255 { get { return (int)agg_basics.uround(alpha * (float)base_mask); } set { alpha = (float)value / (float)base_mask; } } public float Red0To1 { get { return red; } set { red = value; } } public float Green0To1 { get { return green; } set { green = value; } } public float Blue0To1 { get { return blue; } set { blue = value; } } public float Alpha0To1 { get { return alpha; } set { alpha = value; } } #region Defined Colors public static readonly RGBA_Floats White = new RGBA_Floats(1, 1, 1, 1); public static readonly RGBA_Floats Black = new RGBA_Floats(0, 0, 0, 1); public static readonly RGBA_Floats Red = new RGBA_Floats(1, 0, 0, 1); public static readonly RGBA_Floats Green = new RGBA_Floats(0, 1, 0, 1); public static readonly RGBA_Floats Blue = new RGBA_Floats(0, 0, 1, 1); public static readonly RGBA_Floats Cyan = new RGBA_Floats(0, 1, 1, 1); public static readonly RGBA_Floats Magenta = new RGBA_Floats(1, 0, 1, 1); public static readonly RGBA_Floats Yellow = new RGBA_Floats(1, 1, 0, 1); #endregion Defined Colors #region Constructors public RGBA_Floats(double r_, double g_, double b_) : this(r_, g_, b_, 1.0) { } public RGBA_Floats(double r_, double g_, double b_, double a_) { red = (float)r_; green = (float)g_; blue = (float)b_; alpha = (float)a_; } public RGBA_Floats(float r_, float g_, float b_) : this(r_, g_, b_, 1.0f) { } public RGBA_Floats(float r_, float g_, float b_, float a_) { red = r_; green = g_; blue = b_; alpha = a_; } public RGBA_Floats(RGBA_Floats c) : this(c, c.alpha) { } public RGBA_Floats(RGBA_Floats c, float a_) { red = c.red; green = c.green; blue = c.blue; alpha = a_; } public RGBA_Floats(float wavelen) : this(wavelen, 1.0f) { } public RGBA_Floats(float wavelen, float gamma) { this = from_wavelength(wavelen, gamma); } public RGBA_Floats(RGBA_Bytes color) { red = color.Red0To1; green = color.Green0To1; blue = color.Blue0To1; alpha = color.Alpha0To1; } #endregion Constructors #region HSL // Given H,S,L,A in range of 0-1 // Returns a Color (RGB struct) in range of 0-255 public static RGBA_Floats FromHSL(double hue0To1, double saturation0To1, double lightness0To1, double alpha = 1) { double v; double r, g, b; if (alpha > 1.0) { alpha = 1.0; } r = lightness0To1; // default to gray g = lightness0To1; b = lightness0To1; v = lightness0To1 + saturation0To1 - lightness0To1 * saturation0To1; if (lightness0To1 <= 0.5) { v = lightness0To1 * (1.0 + saturation0To1); } if (v > 0) { double m; double sv; int sextant; double fract, vsf, mid1, mid2; m = lightness0To1 + lightness0To1 - v; sv = (v - m) / v; hue0To1 *= 6.0; sextant = (int)hue0To1; fract = hue0To1 - sextant; vsf = v * sv * fract; mid1 = m + vsf; mid2 = v - vsf; switch (sextant) { case 0: r = v; g = mid1; b = m; break; case 1: r = mid2; g = v; b = m; break; case 2: r = m; g = v; b = mid1; break; case 3: r = m; g = mid2; b = v; break; case 4: r = mid1; g = m; b = v; break; case 5: r = v; g = m; b = mid2; break; case 6: goto case 0; } } return new RGBA_Floats(r, g, b, alpha); } public void GetHSL(out double hue0To1, out double saturation0To1, out double lightness0To1) { double maxRGB = Math.Max(red, Math.Max(green, blue)); double minRGB = Math.Min(red, Math.Min(green, blue)); double deltaMaxToMin = maxRGB - minRGB; double r2, g2, b2; hue0To1 = 0; // default to black saturation0To1 = 0; lightness0To1 = 0; lightness0To1 = (minRGB + maxRGB) / 2.0; if (lightness0To1 <= 0.0) { return; } saturation0To1 = deltaMaxToMin; if (saturation0To1 > 0.0) { saturation0To1 /= (lightness0To1 <= 0.5) ? (maxRGB + minRGB) : (2.0 - maxRGB - minRGB); } else { return; } r2 = (maxRGB - red) / deltaMaxToMin; g2 = (maxRGB - green) / deltaMaxToMin; b2 = (maxRGB - blue) / deltaMaxToMin; if (red == maxRGB) { if (green == minRGB) { hue0To1 = 5.0 + b2; } else { hue0To1 = 1.0 - g2; } } else if (green == maxRGB) { if (blue == minRGB) { hue0To1 = 1.0 + r2; } else { hue0To1 = 3.0 - b2; } } else { if (red == minRGB) { hue0To1 = 3.0 + g2; } else { hue0To1 = 5.0 - r2; } } hue0To1 /= 6.0; } public static RGBA_Floats AdjustSaturation(RGBA_Floats original, double saturationMultiplier) { double hue0To1; double saturation0To1; double lightness0To1; original.GetHSL(out hue0To1, out saturation0To1, out lightness0To1); saturation0To1 *= saturationMultiplier; return FromHSL(hue0To1, saturation0To1, lightness0To1); } public static RGBA_Floats AdjustLightness(RGBA_Floats original, double lightnessMultiplier) { double hue0To1; double saturation0To1; double lightness0To1; original.GetHSL(out hue0To1, out saturation0To1, out lightness0To1); lightness0To1 *= lightnessMultiplier; return FromHSL(hue0To1, saturation0To1, lightness0To1); } #endregion HSL public static bool operator ==(RGBA_Floats a, RGBA_Floats b) { if (a.red == b.red && a.green == b.green && a.blue == b.blue && a.alpha == b.alpha) { return true; } return false; } public static bool operator !=(RGBA_Floats a, RGBA_Floats b) { if (a.red != b.red || a.green != b.green || a.blue != b.blue || a.alpha != b.alpha) { return true; } return false; } public override bool Equals(object obj) { if (obj.GetType() == typeof(RGBA_Floats)) { return this == (RGBA_Floats)obj; } return false; } public override int GetHashCode() { return new { blue, green, red, alpha }.GetHashCode(); } public RGBA_Bytes GetAsRGBA_Bytes() { return new RGBA_Bytes(Red0To255, Green0To255, Blue0To255, Alpha0To255); } public RGBA_Floats GetAsRGBA_Floats() { return this; } static public RGBA_Floats operator +(RGBA_Floats A, RGBA_Floats B) { RGBA_Floats temp = new RGBA_Floats(); temp.red = A.red + B.red; temp.green = A.green + B.green; temp.blue = A.blue + B.blue; temp.alpha = A.alpha + B.alpha; return temp; } static public RGBA_Floats operator -(RGBA_Floats A, RGBA_Floats B) { RGBA_Floats temp = new RGBA_Floats(); temp.red = A.red - B.red; temp.green = A.green - B.green; temp.blue = A.blue - B.blue; temp.alpha = A.alpha - B.alpha; return temp; } static public RGBA_Floats operator *(RGBA_Floats A, RGBA_Floats B) { RGBA_Floats temp = new RGBA_Floats(); temp.red = A.red * B.red; temp.green = A.green * B.green; temp.blue = A.blue * B.blue; temp.alpha = A.alpha * B.alpha; return temp; } static public RGBA_Floats operator /(RGBA_Floats A, RGBA_Floats B) { RGBA_Floats temp = new RGBA_Floats(); temp.red = A.red / B.red; temp.green = A.green / B.green; temp.blue = A.blue / B.blue; temp.alpha = A.alpha / B.alpha; return temp; } static public RGBA_Floats operator /(RGBA_Floats A, float B) { RGBA_Floats temp = new RGBA_Floats(); temp.red = A.red / B; temp.green = A.green / B; temp.blue = A.blue / B; temp.alpha = A.alpha / B; return temp; } static public RGBA_Floats operator /(RGBA_Floats A, double doubleB) { float B = (float)doubleB; RGBA_Floats temp = new RGBA_Floats(); temp.red = A.red / B; temp.green = A.green / B; temp.blue = A.blue / B; temp.alpha = A.alpha / B; return temp; } static public RGBA_Floats operator *(RGBA_Floats A, float B) { RGBA_Floats temp = new RGBA_Floats(); temp.red = A.red * B; temp.green = A.green * B; temp.blue = A.blue * B; temp.alpha = A.alpha * B; return temp; } static public RGBA_Floats operator *(RGBA_Floats A, double doubleB) { float B = (float)doubleB; RGBA_Floats temp = new RGBA_Floats(); temp.red = A.red * B; temp.green = A.green * B; temp.blue = A.blue * B; temp.alpha = A.alpha * B; return temp; } public void clear() { red = green = blue = alpha = 0; } public RGBA_Floats transparent() { alpha = 0.0f; return this; } public RGBA_Floats opacity(float a_) { if (a_ < 0.0) a_ = 0.0f; if (a_ > 1.0) a_ = 1.0f; alpha = a_; return this; } public float opacity() { return alpha; } public RGBA_Floats premultiply() { red *= alpha; green *= alpha; blue *= alpha; return this; } public RGBA_Floats premultiply(float a_) { if (alpha <= 0.0 || a_ <= 0.0) { red = green = blue = alpha = 0.0f; return this; } a_ /= alpha; red *= a_; green *= a_; blue *= a_; alpha = a_; return this; } public static RGBA_Floats ComponentMax(RGBA_Floats a, RGBA_Floats b) { RGBA_Floats result = a; if (result.red < b.red) result.red = b.red; if (result.green < b.green) result.green = b.green; if (result.blue < b.blue) result.blue = b.blue; if (result.alpha < b.alpha) result.alpha = b.alpha; return result; } public RGBA_Floats demultiply() { if (alpha == 0) { red = green = blue = 0; return this; } float a_ = 1.0f / alpha; red *= a_; green *= a_; blue *= a_; return this; } public RGBA_Bytes gradient(RGBA_Bytes c_8, double k) { RGBA_Floats c = c_8.GetAsRGBA_Floats(); RGBA_Floats ret; ret.red = (float)(red + (c.red - red) * k); ret.green = (float)(green + (c.green - green) * k); ret.blue = (float)(blue + (c.blue - blue) * k); ret.alpha = (float)(alpha + (c.alpha - alpha) * k); return ret.GetAsRGBA_Bytes(); } public static IColorType no_color() { return (IColorType)new RGBA_Floats(0, 0, 0, 0); } public static RGBA_Floats from_wavelength(float wl) { return from_wavelength(wl, 1.0f); } public static RGBA_Floats from_wavelength(float wl, float gamma) { RGBA_Floats t = new RGBA_Floats(0.0f, 0.0f, 0.0f); if (wl >= 380.0 && wl <= 440.0) { t.red = (float)(-1.0 * (wl - 440.0) / (440.0 - 380.0)); t.blue = 1.0f; } else if (wl >= 440.0 && wl <= 490.0) { t.green = (float)((wl - 440.0) / (490.0 - 440.0)); t.blue = 1.0f; } else if (wl >= 490.0 && wl <= 510.0) { t.green = 1.0f; t.blue = (float)(-1.0 * (wl - 510.0) / (510.0 - 490.0)); } else if (wl >= 510.0 && wl <= 580.0) { t.red = (float)((wl - 510.0) / (580.0 - 510.0)); t.green = 1.0f; } else if (wl >= 580.0 && wl <= 645.0) { t.red = 1.0f; t.green = (float)(-1.0 * (wl - 645.0) / (645.0 - 580.0)); } else if (wl >= 645.0 && wl <= 780.0) { t.red = 1.0f; } float s = 1.0f; if (wl > 700.0) s = (float)(0.3 + 0.7 * (780.0 - wl) / (780.0 - 700.0)); else if (wl < 420.0) s = (float)(0.3 + 0.7 * (wl - 380.0) / (420.0 - 380.0)); t.red = (float)Math.Pow(t.red * s, gamma); t.green = (float)Math.Pow(t.green * s, gamma); t.blue = (float)Math.Pow(t.blue * s, gamma); return t; } public static RGBA_Floats rgba_pre(double r, double g, double b) { return rgba_pre((float)r, (float)g, (float)b, 1.0f); } public static RGBA_Floats rgba_pre(float r, float g, float b) { return rgba_pre(r, g, b, 1.0f); } public static RGBA_Floats rgba_pre(float r, float g, float b, float a) { return new RGBA_Floats(r, g, b, a).premultiply(); } public static RGBA_Floats rgba_pre(double r, double g, double b, double a) { return new RGBA_Floats((float)r, (float)g, (float)b, (float)a).premultiply(); } public static RGBA_Floats rgba_pre(RGBA_Floats c) { return new RGBA_Floats(c).premultiply(); } public static RGBA_Floats rgba_pre(RGBA_Floats c, float a) { return new RGBA_Floats(c, a).premultiply(); } public static RGBA_Floats GetTweenColor(RGBA_Floats Color1, RGBA_Floats Color2, double RatioOf2) { if (RatioOf2 <= 0) { return new RGBA_Floats(Color1); } if (RatioOf2 >= 1.0) { return new RGBA_Floats(Color2); } // figure out how much of each color we should be. double RatioOf1 = 1.0 - RatioOf2; return new RGBA_Floats( Color1.red * RatioOf1 + Color2.red * RatioOf2, Color1.green * RatioOf1 + Color2.green * RatioOf2, Color1.blue * RatioOf1 + Color2.blue * RatioOf2); } public RGBA_Floats Blend(RGBA_Floats other, double weight) { RGBA_Floats result = new RGBA_Floats(this); result = this * (1 - weight) + other * weight; return result; } public double SumOfDistances(RGBA_Floats other) { double dist = Math.Abs(red - other.red) + Math.Abs(green - other.green) + Math.Abs(blue - other.blue); return dist; } private void Clamp0To1(ref float value) { if (value < 0) { value = 0; } else if (value > 1) { value = 1; } } public void Clamp0To1() { Clamp0To1(ref red); Clamp0To1(ref green); Clamp0To1(ref blue); Clamp0To1(ref alpha); } } public struct RGBA_Bytes : IColorType { public const int cover_shift = 8; public const int cover_size = 1 << cover_shift; //----cover_size public const int cover_mask = cover_size - 1; //----cover_mask //public const int cover_none = 0, //----cover_none //public const int cover_full = cover_mask //----cover_full public const int base_shift = 8; public const int base_scale = (int)(1 << base_shift); public const int base_mask = base_scale - 1; public byte blue; public byte green; public byte red; public byte alpha; public static readonly RGBA_Bytes Transparent = new RGBA_Bytes(255, 255, 255, 0); public static readonly RGBA_Bytes White = new RGBA_Bytes(255, 255, 255, 255); public static readonly RGBA_Bytes LightGray = new RGBA_Bytes(225, 225, 225, 255); public static readonly RGBA_Bytes Gray = new RGBA_Bytes(125, 125, 125, 235); public static readonly RGBA_Bytes DarkGray = new RGBA_Bytes(85, 85, 85, 255); public static readonly RGBA_Bytes Black = new RGBA_Bytes(0, 0, 0, 255); public static readonly RGBA_Bytes Red = new RGBA_Bytes(255, 0, 0, 255); public static readonly RGBA_Bytes Orange = new RGBA_Bytes(255, 127, 0, 255); public static readonly RGBA_Bytes Pink = new RGBA_Bytes(255, 192, 203, 255); public static readonly RGBA_Bytes Green = new RGBA_Bytes(0, 255, 0, 255); public static readonly RGBA_Bytes Blue = new RGBA_Bytes(0, 0, 255, 255); public static readonly RGBA_Bytes Indigo = new RGBA_Bytes(75, 0, 130, 255); public static readonly RGBA_Bytes Violet = new RGBA_Bytes(143, 0, 255, 255); public static readonly RGBA_Bytes Cyan = new RGBA_Bytes(0, 255, 255, 255); public static readonly RGBA_Bytes Magenta = new RGBA_Bytes(255, 0, 255, 255); public static readonly RGBA_Bytes Yellow = new RGBA_Bytes(255, 255, 0, 255); public static readonly RGBA_Bytes YellowGreen = new RGBA_Bytes(154, 205, 50, 255); public int Red0To255 { get { return (int)red; } set { red = (byte)value; } } public int Green0To255 { get { return (int)green; } set { green = (byte)value; } } public int Blue0To255 { get { return (int)blue; } set { blue = (byte)value; } } public int Alpha0To255 { get { return (int)alpha; } set { alpha = (byte)value; } } public float Red0To1 { get { return red / 255.0f; } set { red = (byte)Math.Max(0, Math.Min((int)(value * 255), 255)); } } public float Green0To1 { get { return green / 255.0f; } set { green = (byte)Math.Max(0, Math.Min((int)(value * 255), 255)); } } public float Blue0To1 { get { return blue / 255.0f; } set { blue = (byte)Math.Max(0, Math.Min((int)(value * 255), 255)); } } public float Alpha0To1 { get { return alpha / 255.0f; } set { alpha = (byte)Math.Max(0, Math.Min((int)(value * 255), 255)); } } public RGBA_Bytes(int r_, int g_, int b_) : this(r_, g_, b_, base_mask) { } public RGBA_Bytes(int r_, int g_, int b_, int a_) { red = (byte)Math.Min(Math.Max(r_, 0), 255); green = (byte)Math.Min(Math.Max(g_, 0), 255); blue = (byte)Math.Min(Math.Max(b_, 0), 255); alpha = (byte)Math.Min(Math.Max(a_, 0), 255); } public RGBA_Bytes(double r_, double g_, double b_, double a_) { red = ((byte)agg_basics.uround(r_ * (double)base_mask)); green = ((byte)agg_basics.uround(g_ * (double)base_mask)); blue = ((byte)agg_basics.uround(b_ * (double)base_mask)); alpha = ((byte)agg_basics.uround(a_ * (double)base_mask)); } public RGBA_Bytes(double r_, double g_, double b_) { red = ((byte)agg_basics.uround(r_ * (double)base_mask)); green = ((byte)agg_basics.uround(g_ * (double)base_mask)); blue = ((byte)agg_basics.uround(b_ * (double)base_mask)); alpha = (byte)base_mask; } public RGBA_Bytes(RGBA_Floats c, double a_) { red = ((byte)agg_basics.uround(c.red * (double)base_mask)); green = ((byte)agg_basics.uround(c.green * (double)base_mask)); blue = ((byte)agg_basics.uround(c.blue * (double)base_mask)); alpha = ((byte)agg_basics.uround(a_ * (double)base_mask)); } public RGBA_Bytes(RGBA_Bytes c) : this(c, c.alpha) { } public RGBA_Bytes(RGBA_Bytes c, int a_) { red = (byte)c.red; green = (byte)c.green; blue = (byte)c.blue; alpha = (byte)a_; } public RGBA_Bytes(uint fourByteColor) { red = (byte)((fourByteColor >> 16) & 0xFF); green = (byte)((fourByteColor >> 8) & 0xFF); blue = (byte)((fourByteColor >> 0) & 0xFF); alpha = (byte)((fourByteColor >> 24) & 0xFF); } public RGBA_Bytes(RGBA_Floats c) { red = ((byte)agg_basics.uround(c.red * (double)base_mask)); green = ((byte)agg_basics.uround(c.green * (double)base_mask)); blue = ((byte)agg_basics.uround(c.blue * (double)base_mask)); alpha = ((byte)agg_basics.uround(c.alpha * (double)base_mask)); } public static bool operator ==(RGBA_Bytes a, RGBA_Bytes b) { if (a.red == b.red && a.green == b.green && a.blue == b.blue && a.alpha == b.alpha) { return true; } return false; } public static bool operator !=(RGBA_Bytes a, RGBA_Bytes b) { if (a.red != b.red || a.green != b.green || a.blue != b.blue || a.alpha != b.alpha) { return true; } return false; } public override bool Equals(object obj) { if (obj.GetType() == typeof(RGBA_Bytes)) { return this == (RGBA_Bytes)obj; } return false; } public override int GetHashCode() { return new { blue, green, red, alpha }.GetHashCode(); } public RGBA_Floats GetAsRGBA_Floats() { return new RGBA_Floats((float)red / (float)base_mask, (float)green / (float)base_mask, (float)blue / (float)base_mask, (float)alpha / (float)base_mask); } public RGBA_Bytes GetAsRGBA_Bytes() { return this; } public string GetAsHTMLString() { string html = string.Format("#{0:X2}{1:X2}{2:X2}", red, green, blue); return html; } private void clear() { red = green = blue = alpha = 0; } public RGBA_Bytes gradient(RGBA_Bytes c, double k) { RGBA_Bytes ret = new RGBA_Bytes(); int ik = agg_basics.uround(k * base_scale); ret.Red0To255 = (byte)((int)(Red0To255) + ((((int)(c.Red0To255) - Red0To255) * ik) >> base_shift)); ret.Green0To255 = (byte)((int)(Green0To255) + ((((int)(c.Green0To255) - Green0To255) * ik) >> base_shift)); ret.Blue0To255 = (byte)((int)(Blue0To255) + ((((int)(c.Blue0To255) - Blue0To255) * ik) >> base_shift)); ret.Alpha0To255 = (byte)((int)(Alpha0To255) + ((((int)(c.Alpha0To255) - Alpha0To255) * ik) >> base_shift)); return ret; } static public RGBA_Bytes operator +(RGBA_Bytes A, RGBA_Bytes B) { RGBA_Bytes temp = new RGBA_Bytes(); temp.red = (byte)((A.red + B.red) > 255 ? 255 : (A.red + B.red)); temp.green = (byte)((A.green + B.green) > 255 ? 255 : (A.green + B.green)); temp.blue = (byte)((A.blue + B.blue) > 255 ? 255 : (A.blue + B.blue)); temp.alpha = (byte)((A.alpha + B.alpha) > 255 ? 255 : (A.alpha + B.alpha)); return temp; } static public RGBA_Bytes operator -(RGBA_Bytes A, RGBA_Bytes B) { RGBA_Bytes temp = new RGBA_Bytes(); temp.red = (byte)((A.red - B.red) < 0 ? 0 : (A.red - B.red)); temp.green = (byte)((A.green - B.green) < 0 ? 0 : (A.green - B.green)); temp.blue = (byte)((A.blue - B.blue) < 0 ? 0 : (A.blue - B.blue)); temp.alpha = 255;// (byte)((A.m_A - B.m_A) < 0 ? 0 : (A.m_A - B.m_A)); return temp; } static public RGBA_Bytes operator *(RGBA_Bytes A, double doubleB) { float B = (float)doubleB; RGBA_Floats temp = new RGBA_Floats(); temp.red = A.red / 255.0f * B; temp.green = A.green / 255.0f * B; temp.blue = A.blue / 255.0f * B; temp.alpha = A.alpha / 255.0f * B; return new RGBA_Bytes(temp); } public void add(RGBA_Bytes c, int cover) { int cr, cg, cb, ca; if (cover == cover_mask) { if (c.Alpha0To255 == base_mask) { this = c; } else { cr = Red0To255 + c.Red0To255; Red0To255 = (cr > (int)(base_mask)) ? (int)(base_mask) : cr; cg = Green0To255 + c.Green0To255; Green0To255 = (cg > (int)(base_mask)) ? (int)(base_mask) : cg; cb = Blue0To255 + c.Blue0To255; Blue0To255 = (cb > (int)(base_mask)) ? (int)(base_mask) : cb; ca = Alpha0To255 + c.Alpha0To255; Alpha0To255 = (ca > (int)(base_mask)) ? (int)(base_mask) : ca; } } else { cr = Red0To255 + ((c.Red0To255 * cover + cover_mask / 2) >> cover_shift); cg = Green0To255 + ((c.Green0To255 * cover + cover_mask / 2) >> cover_shift); cb = Blue0To255 + ((c.Blue0To255 * cover + cover_mask / 2) >> cover_shift); ca = Alpha0To255 + ((c.Alpha0To255 * cover + cover_mask / 2) >> cover_shift); Red0To255 = (cr > (int)(base_mask)) ? (int)(base_mask) : cr; Green0To255 = (cg > (int)(base_mask)) ? (int)(base_mask) : cg; Blue0To255 = (cb > (int)(base_mask)) ? (int)(base_mask) : cb; Alpha0To255 = (ca > (int)(base_mask)) ? (int)(base_mask) : ca; } } public void apply_gamma_dir(GammaLookUpTable gamma) { Red0To255 = gamma.dir((byte)Red0To255); Green0To255 = gamma.dir((byte)Green0To255); Blue0To255 = gamma.dir((byte)Blue0To255); } public static IColorType no_color() { return new RGBA_Bytes(0, 0, 0, 0); } //-------------------------------------------------------------rgb8_packed static public RGBA_Bytes rgb8_packed(int v) { return new RGBA_Bytes((v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF); } public RGBA_Bytes Blend(RGBA_Bytes other, double weight) { RGBA_Bytes result = new RGBA_Bytes(this); result = this * (1 - weight) + other * weight; return result; } } }
namespace EIDSS.Reports.Document.Human.CaseInvestigation { partial class ContactListReport { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ContactListReport)); this.Detail = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand(); this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand(); this.contactListDataSet1 = new EIDSS.Reports.Document.Human.CaseInvestigation.ContactListDataSet(); this.sp_rep_HUM_CaseForm_ContactsTableAdapter = new EIDSS.Reports.Document.Human.CaseInvestigation.ContactListDataSetTableAdapters.sp_rep_HUM_CaseForm_ContactsTableAdapter(); this.xrCrossBandBox1 = new DevExpress.XtraReports.UI.XRCrossBandBox(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrLabel3 = new DevExpress.XtraReports.UI.XRLabel(); this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand(); this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.contactListDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // Detail // this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable2}); resources.ApplyResources(this.Detail, "Detail"); this.Detail.Name = "Detail"; this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UseTextAlignment = false; // // xrTable2 // this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable2, "xrTable2"); this.xrTable2.Name = "xrTable2"; this.xrTable2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow2}); this.xrTable2.StylePriority.UseBorders = false; this.xrTable2.StylePriority.UsePadding = false; this.xrTable2.StylePriority.UseTextAlignment = false; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell6, this.xrTableCell7, this.xrTableCell8, this.xrTableCell9, this.xrTableCell10, this.xrTableCell12}); this.xrTableRow2.Name = "xrTableRow2"; resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); // // xrTableCell6 // this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumCaseFormContacts.ContactName")}); this.xrTableCell6.Name = "xrTableCell6"; resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); // // xrTableCell7 // this.xrTableCell7.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumCaseFormContacts.Relation_Type")}); this.xrTableCell7.Name = "xrTableCell7"; this.xrTableCell7.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); // // xrTableCell8 // this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumCaseFormContacts.ContactDate", "{0:dd/MM/yyyy}")}); this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); // // xrTableCell9 // this.xrTableCell9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumCaseFormContacts.PlaceOfContact")}); this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); // // xrTableCell10 // this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumCaseFormContacts.ContactInformation")}); this.xrTableCell10.Name = "xrTableCell10"; resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); // // xrTableCell12 // this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumCaseFormContacts.Comments")}); this.xrTableCell12.Name = "xrTableCell12"; resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.Name = "PageHeader"; this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.PageHeader.StylePriority.UseFont = false; // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.Name = "PageFooter"; this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // contactListDataSet1 // this.contactListDataSet1.DataSetName = "ContactListDataSet"; this.contactListDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // sp_rep_HUM_CaseForm_ContactsTableAdapter // this.sp_rep_HUM_CaseForm_ContactsTableAdapter.ClearBeforeFill = true; // // xrCrossBandBox1 // this.xrCrossBandBox1.BorderWidth = 1; this.xrCrossBandBox1.EndBand = this.ReportFooter; resources.ApplyResources(this.xrCrossBandBox1, "xrCrossBandBox1"); this.xrCrossBandBox1.Name = "xrCrossBandBox1"; this.xrCrossBandBox1.StartBand = this.ReportHeader; this.xrCrossBandBox1.WidthF = 774F; // // ReportFooter // resources.ApplyResources(this.ReportFooter, "ReportFooter"); this.ReportFooter.Name = "ReportFooter"; this.ReportFooter.StylePriority.UseFont = false; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1, this.xrLabel3}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Name = "ReportHeader"; this.ReportHeader.StylePriority.UseFont = false; this.ReportHeader.StylePriority.UseTextAlignment = false; // // xrTable1 // this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1}); this.xrTable1.StylePriority.UseBorders = false; this.xrTable1.StylePriority.UseFont = false; this.xrTable1.StylePriority.UsePadding = false; this.xrTable1.StylePriority.UseTextAlignment = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell4, this.xrTableCell1, this.xrTableCell5, this.xrTableCell2, this.xrTableCell3, this.xrTableCell11}); this.xrTableRow1.Name = "xrTableRow1"; resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); // // xrTableCell4 // this.xrTableCell4.Name = "xrTableCell4"; resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); // // xrTableCell1 // this.xrTableCell1.Name = "xrTableCell1"; resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); // // xrTableCell5 // this.xrTableCell5.Name = "xrTableCell5"; resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); // // xrTableCell2 // this.xrTableCell2.Name = "xrTableCell2"; resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); // // xrTableCell3 // this.xrTableCell3.Name = "xrTableCell3"; resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); // // xrTableCell11 // this.xrTableCell11.Name = "xrTableCell11"; resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); // // xrLabel3 // this.xrLabel3.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.xrLabel3, "xrLabel3"); this.xrLabel3.Name = "xrLabel3"; this.xrLabel3.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel3.StylePriority.UseBorders = false; this.xrLabel3.StylePriority.UseFont = false; this.xrLabel3.StylePriority.UseTextAlignment = false; // // topMarginBand1 // resources.ApplyResources(this.topMarginBand1, "topMarginBand1"); this.topMarginBand1.Name = "topMarginBand1"; // // bottomMarginBand1 // resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1"); this.bottomMarginBand1.Name = "bottomMarginBand1"; // // ContactListReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.ReportFooter, this.topMarginBand1, this.bottomMarginBand1}); this.CrossBandControls.AddRange(new DevExpress.XtraReports.UI.XRCrossBandControl[] { this.xrCrossBandBox1}); this.DataAdapter = this.sp_rep_HUM_CaseForm_ContactsTableAdapter; this.DataMember = "spRepHumCaseFormContacts"; this.DataSource = this.contactListDataSet1; this.ExportOptions.Xls.SheetName = resources.GetString("ContactListReport.ExportOptions.Xls.SheetName"); this.ExportOptions.Xlsx.SheetName = resources.GetString("ContactListReport.ExportOptions.Xlsx.SheetName"); resources.ApplyResources(this, "$this"); this.Version = "13.1"; ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.contactListDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailBand Detail; private DevExpress.XtraReports.UI.PageHeaderBand PageHeader; private DevExpress.XtraReports.UI.PageFooterBand PageFooter; private ContactListDataSet contactListDataSet1; private ContactListDataSetTableAdapters.sp_rep_HUM_CaseForm_ContactsTableAdapter sp_rep_HUM_CaseForm_ContactsTableAdapter; private DevExpress.XtraReports.UI.XRCrossBandBox xrCrossBandBox1; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader; private DevExpress.XtraReports.UI.XRLabel xrLabel3; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTable xrTable2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.TopMarginBand topMarginBand1; private DevExpress.XtraReports.UI.BottomMarginBand bottomMarginBand1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/proto/grpc/testing/echo_messages.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Grpc.Testing { /// <summary>Holder for reflection information generated from src/proto/grpc/testing/echo_messages.proto</summary> public static partial class EchoMessagesReflection { #region Descriptor /// <summary>File descriptor for src/proto/grpc/testing/echo_messages.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static EchoMessagesReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CipzcmMvcHJvdG8vZ3JwYy90ZXN0aW5nL2VjaG9fbWVzc2FnZXMucHJvdG8S", "DGdycGMudGVzdGluZyIyCglEZWJ1Z0luZm8SFQoNc3RhY2tfZW50cmllcxgB", "IAMoCRIOCgZkZXRhaWwYAiABKAkiUAoLRXJyb3JTdGF0dXMSDAoEY29kZRgB", "IAEoBRIVCg1lcnJvcl9tZXNzYWdlGAIgASgJEhwKFGJpbmFyeV9lcnJvcl9k", "ZXRhaWxzGAMgASgJIskDCg1SZXF1ZXN0UGFyYW1zEhUKDWVjaG9fZGVhZGxp", "bmUYASABKAgSHgoWY2xpZW50X2NhbmNlbF9hZnRlcl91cxgCIAEoBRIeChZz", "ZXJ2ZXJfY2FuY2VsX2FmdGVyX3VzGAMgASgFEhUKDWVjaG9fbWV0YWRhdGEY", "BCABKAgSGgoSY2hlY2tfYXV0aF9jb250ZXh0GAUgASgIEh8KF3Jlc3BvbnNl", "X21lc3NhZ2VfbGVuZ3RoGAYgASgFEhEKCWVjaG9fcGVlchgHIAEoCBIgChhl", "eHBlY3RlZF9jbGllbnRfaWRlbnRpdHkYCCABKAkSHAoUc2tpcF9jYW5jZWxs", "ZWRfY2hlY2sYCSABKAgSKAogZXhwZWN0ZWRfdHJhbnNwb3J0X3NlY3VyaXR5", "X3R5cGUYCiABKAkSKwoKZGVidWdfaW5mbxgLIAEoCzIXLmdycGMudGVzdGlu", "Zy5EZWJ1Z0luZm8SEgoKc2VydmVyX2RpZRgMIAEoCBIcChRiaW5hcnlfZXJy", "b3JfZGV0YWlscxgNIAEoCRIxCg5leHBlY3RlZF9lcnJvchgOIAEoCzIZLmdy", "cGMudGVzdGluZy5FcnJvclN0YXR1cyJKCgtFY2hvUmVxdWVzdBIPCgdtZXNz", "YWdlGAEgASgJEioKBXBhcmFtGAIgASgLMhsuZ3JwYy50ZXN0aW5nLlJlcXVl", "c3RQYXJhbXMiRgoOUmVzcG9uc2VQYXJhbXMSGAoQcmVxdWVzdF9kZWFkbGlu", "ZRgBIAEoAxIMCgRob3N0GAIgASgJEgwKBHBlZXIYAyABKAkiTAoMRWNob1Jl", "c3BvbnNlEg8KB21lc3NhZ2UYASABKAkSKwoFcGFyYW0YAiABKAsyHC5ncnBj", "LnRlc3RpbmcuUmVzcG9uc2VQYXJhbXNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.DebugInfo), global::Grpc.Testing.DebugInfo.Parser, new[]{ "StackEntries", "Detail" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.ErrorStatus), global::Grpc.Testing.ErrorStatus.Parser, new[]{ "Code", "ErrorMessage", "BinaryErrorDetails" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.RequestParams), global::Grpc.Testing.RequestParams.Parser, new[]{ "EchoDeadline", "ClientCancelAfterUs", "ServerCancelAfterUs", "EchoMetadata", "CheckAuthContext", "ResponseMessageLength", "EchoPeer", "ExpectedClientIdentity", "SkipCancelledCheck", "ExpectedTransportSecurityType", "DebugInfo", "ServerDie", "BinaryErrorDetails", "ExpectedError" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.EchoRequest), global::Grpc.Testing.EchoRequest.Parser, new[]{ "Message", "Param" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.ResponseParams), global::Grpc.Testing.ResponseParams.Parser, new[]{ "RequestDeadline", "Host", "Peer" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.EchoResponse), global::Grpc.Testing.EchoResponse.Parser, new[]{ "Message", "Param" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Message to be echoed back serialized in trailer. /// </summary> public sealed partial class DebugInfo : pb::IMessage<DebugInfo> { private static readonly pb::MessageParser<DebugInfo> _parser = new pb::MessageParser<DebugInfo>(() => new DebugInfo()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<DebugInfo> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.EchoMessagesReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DebugInfo() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DebugInfo(DebugInfo other) : this() { stackEntries_ = other.stackEntries_.Clone(); detail_ = other.detail_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DebugInfo Clone() { return new DebugInfo(this); } /// <summary>Field number for the "stack_entries" field.</summary> public const int StackEntriesFieldNumber = 1; private static readonly pb::FieldCodec<string> _repeated_stackEntries_codec = pb::FieldCodec.ForString(10); private readonly pbc::RepeatedField<string> stackEntries_ = new pbc::RepeatedField<string>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> StackEntries { get { return stackEntries_; } } /// <summary>Field number for the "detail" field.</summary> public const int DetailFieldNumber = 2; private string detail_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Detail { get { return detail_; } set { detail_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as DebugInfo); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(DebugInfo other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!stackEntries_.Equals(other.stackEntries_)) return false; if (Detail != other.Detail) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= stackEntries_.GetHashCode(); if (Detail.Length != 0) hash ^= Detail.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { stackEntries_.WriteTo(output, _repeated_stackEntries_codec); if (Detail.Length != 0) { output.WriteRawTag(18); output.WriteString(Detail); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += stackEntries_.CalculateSize(_repeated_stackEntries_codec); if (Detail.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Detail); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(DebugInfo other) { if (other == null) { return; } stackEntries_.Add(other.stackEntries_); if (other.Detail.Length != 0) { Detail = other.Detail; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { stackEntries_.AddEntriesFrom(input, _repeated_stackEntries_codec); break; } case 18: { Detail = input.ReadString(); break; } } } } } /// <summary> /// Error status client expects to see. /// </summary> public sealed partial class ErrorStatus : pb::IMessage<ErrorStatus> { private static readonly pb::MessageParser<ErrorStatus> _parser = new pb::MessageParser<ErrorStatus>(() => new ErrorStatus()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ErrorStatus> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.EchoMessagesReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ErrorStatus() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ErrorStatus(ErrorStatus other) : this() { code_ = other.code_; errorMessage_ = other.errorMessage_; binaryErrorDetails_ = other.binaryErrorDetails_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ErrorStatus Clone() { return new ErrorStatus(this); } /// <summary>Field number for the "code" field.</summary> public const int CodeFieldNumber = 1; private int code_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Code { get { return code_; } set { code_ = value; } } /// <summary>Field number for the "error_message" field.</summary> public const int ErrorMessageFieldNumber = 2; private string errorMessage_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ErrorMessage { get { return errorMessage_; } set { errorMessage_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "binary_error_details" field.</summary> public const int BinaryErrorDetailsFieldNumber = 3; private string binaryErrorDetails_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BinaryErrorDetails { get { return binaryErrorDetails_; } set { binaryErrorDetails_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ErrorStatus); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ErrorStatus other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Code != other.Code) return false; if (ErrorMessage != other.ErrorMessage) return false; if (BinaryErrorDetails != other.BinaryErrorDetails) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Code != 0) hash ^= Code.GetHashCode(); if (ErrorMessage.Length != 0) hash ^= ErrorMessage.GetHashCode(); if (BinaryErrorDetails.Length != 0) hash ^= BinaryErrorDetails.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Code != 0) { output.WriteRawTag(8); output.WriteInt32(Code); } if (ErrorMessage.Length != 0) { output.WriteRawTag(18); output.WriteString(ErrorMessage); } if (BinaryErrorDetails.Length != 0) { output.WriteRawTag(26); output.WriteString(BinaryErrorDetails); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Code != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Code); } if (ErrorMessage.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ErrorMessage); } if (BinaryErrorDetails.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BinaryErrorDetails); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ErrorStatus other) { if (other == null) { return; } if (other.Code != 0) { Code = other.Code; } if (other.ErrorMessage.Length != 0) { ErrorMessage = other.ErrorMessage; } if (other.BinaryErrorDetails.Length != 0) { BinaryErrorDetails = other.BinaryErrorDetails; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Code = input.ReadInt32(); break; } case 18: { ErrorMessage = input.ReadString(); break; } case 26: { BinaryErrorDetails = input.ReadString(); break; } } } } } public sealed partial class RequestParams : pb::IMessage<RequestParams> { private static readonly pb::MessageParser<RequestParams> _parser = new pb::MessageParser<RequestParams>(() => new RequestParams()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RequestParams> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.EchoMessagesReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestParams() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestParams(RequestParams other) : this() { echoDeadline_ = other.echoDeadline_; clientCancelAfterUs_ = other.clientCancelAfterUs_; serverCancelAfterUs_ = other.serverCancelAfterUs_; echoMetadata_ = other.echoMetadata_; checkAuthContext_ = other.checkAuthContext_; responseMessageLength_ = other.responseMessageLength_; echoPeer_ = other.echoPeer_; expectedClientIdentity_ = other.expectedClientIdentity_; skipCancelledCheck_ = other.skipCancelledCheck_; expectedTransportSecurityType_ = other.expectedTransportSecurityType_; DebugInfo = other.debugInfo_ != null ? other.DebugInfo.Clone() : null; serverDie_ = other.serverDie_; binaryErrorDetails_ = other.binaryErrorDetails_; ExpectedError = other.expectedError_ != null ? other.ExpectedError.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestParams Clone() { return new RequestParams(this); } /// <summary>Field number for the "echo_deadline" field.</summary> public const int EchoDeadlineFieldNumber = 1; private bool echoDeadline_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool EchoDeadline { get { return echoDeadline_; } set { echoDeadline_ = value; } } /// <summary>Field number for the "client_cancel_after_us" field.</summary> public const int ClientCancelAfterUsFieldNumber = 2; private int clientCancelAfterUs_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int ClientCancelAfterUs { get { return clientCancelAfterUs_; } set { clientCancelAfterUs_ = value; } } /// <summary>Field number for the "server_cancel_after_us" field.</summary> public const int ServerCancelAfterUsFieldNumber = 3; private int serverCancelAfterUs_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int ServerCancelAfterUs { get { return serverCancelAfterUs_; } set { serverCancelAfterUs_ = value; } } /// <summary>Field number for the "echo_metadata" field.</summary> public const int EchoMetadataFieldNumber = 4; private bool echoMetadata_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool EchoMetadata { get { return echoMetadata_; } set { echoMetadata_ = value; } } /// <summary>Field number for the "check_auth_context" field.</summary> public const int CheckAuthContextFieldNumber = 5; private bool checkAuthContext_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool CheckAuthContext { get { return checkAuthContext_; } set { checkAuthContext_ = value; } } /// <summary>Field number for the "response_message_length" field.</summary> public const int ResponseMessageLengthFieldNumber = 6; private int responseMessageLength_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int ResponseMessageLength { get { return responseMessageLength_; } set { responseMessageLength_ = value; } } /// <summary>Field number for the "echo_peer" field.</summary> public const int EchoPeerFieldNumber = 7; private bool echoPeer_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool EchoPeer { get { return echoPeer_; } set { echoPeer_ = value; } } /// <summary>Field number for the "expected_client_identity" field.</summary> public const int ExpectedClientIdentityFieldNumber = 8; private string expectedClientIdentity_ = ""; /// <summary> /// will force check_auth_context. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ExpectedClientIdentity { get { return expectedClientIdentity_; } set { expectedClientIdentity_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "skip_cancelled_check" field.</summary> public const int SkipCancelledCheckFieldNumber = 9; private bool skipCancelledCheck_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool SkipCancelledCheck { get { return skipCancelledCheck_; } set { skipCancelledCheck_ = value; } } /// <summary>Field number for the "expected_transport_security_type" field.</summary> public const int ExpectedTransportSecurityTypeFieldNumber = 10; private string expectedTransportSecurityType_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ExpectedTransportSecurityType { get { return expectedTransportSecurityType_; } set { expectedTransportSecurityType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "debug_info" field.</summary> public const int DebugInfoFieldNumber = 11; private global::Grpc.Testing.DebugInfo debugInfo_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Grpc.Testing.DebugInfo DebugInfo { get { return debugInfo_; } set { debugInfo_ = value; } } /// <summary>Field number for the "server_die" field.</summary> public const int ServerDieFieldNumber = 12; private bool serverDie_; /// <summary> /// Server should not see a request with this set. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool ServerDie { get { return serverDie_; } set { serverDie_ = value; } } /// <summary>Field number for the "binary_error_details" field.</summary> public const int BinaryErrorDetailsFieldNumber = 13; private string binaryErrorDetails_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BinaryErrorDetails { get { return binaryErrorDetails_; } set { binaryErrorDetails_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "expected_error" field.</summary> public const int ExpectedErrorFieldNumber = 14; private global::Grpc.Testing.ErrorStatus expectedError_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Grpc.Testing.ErrorStatus ExpectedError { get { return expectedError_; } set { expectedError_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RequestParams); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RequestParams other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (EchoDeadline != other.EchoDeadline) return false; if (ClientCancelAfterUs != other.ClientCancelAfterUs) return false; if (ServerCancelAfterUs != other.ServerCancelAfterUs) return false; if (EchoMetadata != other.EchoMetadata) return false; if (CheckAuthContext != other.CheckAuthContext) return false; if (ResponseMessageLength != other.ResponseMessageLength) return false; if (EchoPeer != other.EchoPeer) return false; if (ExpectedClientIdentity != other.ExpectedClientIdentity) return false; if (SkipCancelledCheck != other.SkipCancelledCheck) return false; if (ExpectedTransportSecurityType != other.ExpectedTransportSecurityType) return false; if (!object.Equals(DebugInfo, other.DebugInfo)) return false; if (ServerDie != other.ServerDie) return false; if (BinaryErrorDetails != other.BinaryErrorDetails) return false; if (!object.Equals(ExpectedError, other.ExpectedError)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (EchoDeadline != false) hash ^= EchoDeadline.GetHashCode(); if (ClientCancelAfterUs != 0) hash ^= ClientCancelAfterUs.GetHashCode(); if (ServerCancelAfterUs != 0) hash ^= ServerCancelAfterUs.GetHashCode(); if (EchoMetadata != false) hash ^= EchoMetadata.GetHashCode(); if (CheckAuthContext != false) hash ^= CheckAuthContext.GetHashCode(); if (ResponseMessageLength != 0) hash ^= ResponseMessageLength.GetHashCode(); if (EchoPeer != false) hash ^= EchoPeer.GetHashCode(); if (ExpectedClientIdentity.Length != 0) hash ^= ExpectedClientIdentity.GetHashCode(); if (SkipCancelledCheck != false) hash ^= SkipCancelledCheck.GetHashCode(); if (ExpectedTransportSecurityType.Length != 0) hash ^= ExpectedTransportSecurityType.GetHashCode(); if (debugInfo_ != null) hash ^= DebugInfo.GetHashCode(); if (ServerDie != false) hash ^= ServerDie.GetHashCode(); if (BinaryErrorDetails.Length != 0) hash ^= BinaryErrorDetails.GetHashCode(); if (expectedError_ != null) hash ^= ExpectedError.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (EchoDeadline != false) { output.WriteRawTag(8); output.WriteBool(EchoDeadline); } if (ClientCancelAfterUs != 0) { output.WriteRawTag(16); output.WriteInt32(ClientCancelAfterUs); } if (ServerCancelAfterUs != 0) { output.WriteRawTag(24); output.WriteInt32(ServerCancelAfterUs); } if (EchoMetadata != false) { output.WriteRawTag(32); output.WriteBool(EchoMetadata); } if (CheckAuthContext != false) { output.WriteRawTag(40); output.WriteBool(CheckAuthContext); } if (ResponseMessageLength != 0) { output.WriteRawTag(48); output.WriteInt32(ResponseMessageLength); } if (EchoPeer != false) { output.WriteRawTag(56); output.WriteBool(EchoPeer); } if (ExpectedClientIdentity.Length != 0) { output.WriteRawTag(66); output.WriteString(ExpectedClientIdentity); } if (SkipCancelledCheck != false) { output.WriteRawTag(72); output.WriteBool(SkipCancelledCheck); } if (ExpectedTransportSecurityType.Length != 0) { output.WriteRawTag(82); output.WriteString(ExpectedTransportSecurityType); } if (debugInfo_ != null) { output.WriteRawTag(90); output.WriteMessage(DebugInfo); } if (ServerDie != false) { output.WriteRawTag(96); output.WriteBool(ServerDie); } if (BinaryErrorDetails.Length != 0) { output.WriteRawTag(106); output.WriteString(BinaryErrorDetails); } if (expectedError_ != null) { output.WriteRawTag(114); output.WriteMessage(ExpectedError); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (EchoDeadline != false) { size += 1 + 1; } if (ClientCancelAfterUs != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(ClientCancelAfterUs); } if (ServerCancelAfterUs != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(ServerCancelAfterUs); } if (EchoMetadata != false) { size += 1 + 1; } if (CheckAuthContext != false) { size += 1 + 1; } if (ResponseMessageLength != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(ResponseMessageLength); } if (EchoPeer != false) { size += 1 + 1; } if (ExpectedClientIdentity.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ExpectedClientIdentity); } if (SkipCancelledCheck != false) { size += 1 + 1; } if (ExpectedTransportSecurityType.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ExpectedTransportSecurityType); } if (debugInfo_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(DebugInfo); } if (ServerDie != false) { size += 1 + 1; } if (BinaryErrorDetails.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BinaryErrorDetails); } if (expectedError_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ExpectedError); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RequestParams other) { if (other == null) { return; } if (other.EchoDeadline != false) { EchoDeadline = other.EchoDeadline; } if (other.ClientCancelAfterUs != 0) { ClientCancelAfterUs = other.ClientCancelAfterUs; } if (other.ServerCancelAfterUs != 0) { ServerCancelAfterUs = other.ServerCancelAfterUs; } if (other.EchoMetadata != false) { EchoMetadata = other.EchoMetadata; } if (other.CheckAuthContext != false) { CheckAuthContext = other.CheckAuthContext; } if (other.ResponseMessageLength != 0) { ResponseMessageLength = other.ResponseMessageLength; } if (other.EchoPeer != false) { EchoPeer = other.EchoPeer; } if (other.ExpectedClientIdentity.Length != 0) { ExpectedClientIdentity = other.ExpectedClientIdentity; } if (other.SkipCancelledCheck != false) { SkipCancelledCheck = other.SkipCancelledCheck; } if (other.ExpectedTransportSecurityType.Length != 0) { ExpectedTransportSecurityType = other.ExpectedTransportSecurityType; } if (other.debugInfo_ != null) { if (debugInfo_ == null) { debugInfo_ = new global::Grpc.Testing.DebugInfo(); } DebugInfo.MergeFrom(other.DebugInfo); } if (other.ServerDie != false) { ServerDie = other.ServerDie; } if (other.BinaryErrorDetails.Length != 0) { BinaryErrorDetails = other.BinaryErrorDetails; } if (other.expectedError_ != null) { if (expectedError_ == null) { expectedError_ = new global::Grpc.Testing.ErrorStatus(); } ExpectedError.MergeFrom(other.ExpectedError); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { EchoDeadline = input.ReadBool(); break; } case 16: { ClientCancelAfterUs = input.ReadInt32(); break; } case 24: { ServerCancelAfterUs = input.ReadInt32(); break; } case 32: { EchoMetadata = input.ReadBool(); break; } case 40: { CheckAuthContext = input.ReadBool(); break; } case 48: { ResponseMessageLength = input.ReadInt32(); break; } case 56: { EchoPeer = input.ReadBool(); break; } case 66: { ExpectedClientIdentity = input.ReadString(); break; } case 72: { SkipCancelledCheck = input.ReadBool(); break; } case 82: { ExpectedTransportSecurityType = input.ReadString(); break; } case 90: { if (debugInfo_ == null) { debugInfo_ = new global::Grpc.Testing.DebugInfo(); } input.ReadMessage(debugInfo_); break; } case 96: { ServerDie = input.ReadBool(); break; } case 106: { BinaryErrorDetails = input.ReadString(); break; } case 114: { if (expectedError_ == null) { expectedError_ = new global::Grpc.Testing.ErrorStatus(); } input.ReadMessage(expectedError_); break; } } } } } public sealed partial class EchoRequest : pb::IMessage<EchoRequest> { private static readonly pb::MessageParser<EchoRequest> _parser = new pb::MessageParser<EchoRequest>(() => new EchoRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<EchoRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.EchoMessagesReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EchoRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EchoRequest(EchoRequest other) : this() { message_ = other.message_; Param = other.param_ != null ? other.Param.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EchoRequest Clone() { return new EchoRequest(this); } /// <summary>Field number for the "message" field.</summary> public const int MessageFieldNumber = 1; private string message_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Message { get { return message_; } set { message_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "param" field.</summary> public const int ParamFieldNumber = 2; private global::Grpc.Testing.RequestParams param_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Grpc.Testing.RequestParams Param { get { return param_; } set { param_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as EchoRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(EchoRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Message != other.Message) return false; if (!object.Equals(Param, other.Param)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Message.Length != 0) hash ^= Message.GetHashCode(); if (param_ != null) hash ^= Param.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Message.Length != 0) { output.WriteRawTag(10); output.WriteString(Message); } if (param_ != null) { output.WriteRawTag(18); output.WriteMessage(Param); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Message.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Message); } if (param_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Param); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(EchoRequest other) { if (other == null) { return; } if (other.Message.Length != 0) { Message = other.Message; } if (other.param_ != null) { if (param_ == null) { param_ = new global::Grpc.Testing.RequestParams(); } Param.MergeFrom(other.Param); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Message = input.ReadString(); break; } case 18: { if (param_ == null) { param_ = new global::Grpc.Testing.RequestParams(); } input.ReadMessage(param_); break; } } } } } public sealed partial class ResponseParams : pb::IMessage<ResponseParams> { private static readonly pb::MessageParser<ResponseParams> _parser = new pb::MessageParser<ResponseParams>(() => new ResponseParams()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ResponseParams> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.EchoMessagesReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ResponseParams() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ResponseParams(ResponseParams other) : this() { requestDeadline_ = other.requestDeadline_; host_ = other.host_; peer_ = other.peer_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ResponseParams Clone() { return new ResponseParams(this); } /// <summary>Field number for the "request_deadline" field.</summary> public const int RequestDeadlineFieldNumber = 1; private long requestDeadline_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long RequestDeadline { get { return requestDeadline_; } set { requestDeadline_ = value; } } /// <summary>Field number for the "host" field.</summary> public const int HostFieldNumber = 2; private string host_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Host { get { return host_; } set { host_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "peer" field.</summary> public const int PeerFieldNumber = 3; private string peer_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Peer { get { return peer_; } set { peer_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ResponseParams); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ResponseParams other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (RequestDeadline != other.RequestDeadline) return false; if (Host != other.Host) return false; if (Peer != other.Peer) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (RequestDeadline != 0L) hash ^= RequestDeadline.GetHashCode(); if (Host.Length != 0) hash ^= Host.GetHashCode(); if (Peer.Length != 0) hash ^= Peer.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (RequestDeadline != 0L) { output.WriteRawTag(8); output.WriteInt64(RequestDeadline); } if (Host.Length != 0) { output.WriteRawTag(18); output.WriteString(Host); } if (Peer.Length != 0) { output.WriteRawTag(26); output.WriteString(Peer); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (RequestDeadline != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(RequestDeadline); } if (Host.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Host); } if (Peer.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Peer); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ResponseParams other) { if (other == null) { return; } if (other.RequestDeadline != 0L) { RequestDeadline = other.RequestDeadline; } if (other.Host.Length != 0) { Host = other.Host; } if (other.Peer.Length != 0) { Peer = other.Peer; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { RequestDeadline = input.ReadInt64(); break; } case 18: { Host = input.ReadString(); break; } case 26: { Peer = input.ReadString(); break; } } } } } public sealed partial class EchoResponse : pb::IMessage<EchoResponse> { private static readonly pb::MessageParser<EchoResponse> _parser = new pb::MessageParser<EchoResponse>(() => new EchoResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<EchoResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.EchoMessagesReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EchoResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EchoResponse(EchoResponse other) : this() { message_ = other.message_; Param = other.param_ != null ? other.Param.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EchoResponse Clone() { return new EchoResponse(this); } /// <summary>Field number for the "message" field.</summary> public const int MessageFieldNumber = 1; private string message_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Message { get { return message_; } set { message_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "param" field.</summary> public const int ParamFieldNumber = 2; private global::Grpc.Testing.ResponseParams param_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Grpc.Testing.ResponseParams Param { get { return param_; } set { param_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as EchoResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(EchoResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Message != other.Message) return false; if (!object.Equals(Param, other.Param)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Message.Length != 0) hash ^= Message.GetHashCode(); if (param_ != null) hash ^= Param.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Message.Length != 0) { output.WriteRawTag(10); output.WriteString(Message); } if (param_ != null) { output.WriteRawTag(18); output.WriteMessage(Param); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Message.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Message); } if (param_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Param); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(EchoResponse other) { if (other == null) { return; } if (other.Message.Length != 0) { Message = other.Message; } if (other.param_ != null) { if (param_ == null) { param_ = new global::Grpc.Testing.ResponseParams(); } Param.MergeFrom(other.Param); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Message = input.ReadString(); break; } case 18: { if (param_ == null) { param_ = new global::Grpc.Testing.ResponseParams(); } input.ReadMessage(param_); break; } } } } } #endregion } #endregion Designer generated code
// This file is part of the C5 Generic Collection Library for C# and CLI // See https://github.com/sestoft/C5/blob/master/LICENSE for licensing details. using NUnit.Framework; using System; using SCG = System.Collections.Generic; namespace C5.Tests { internal class SC : SCG.IComparer<string> { public int Compare(string a, string b) { return a.CompareTo(b); } public void appl(String s) { System.Console.WriteLine("--{0}", s); } } internal class TenEqualityComparer : SCG.IEqualityComparer<int>, SCG.IComparer<int> { private TenEqualityComparer() { } public static TenEqualityComparer Default => new TenEqualityComparer(); public int GetHashCode(int item) { return (item / 10).GetHashCode(); } public bool Equals(int item1, int item2) { return item1 / 10 == item2 / 10; } public int Compare(int a, int b) { return (a / 10).CompareTo(b / 10); } } internal class IC : SCG.IComparer<int>, IComparable<int>, SCG.IComparer<IC>, IComparable<IC> { public int Compare(int a, int b) { return a > b ? 1 : a < b ? -1 : 0; } public int Compare(IC a, IC b) { return a.I > b.I ? 1 : a.I < b.I ? -1 : 0; } public int I { get; set; } public IC() { } public IC(int i) { I = i; } public int CompareTo(int that) { return I > that ? 1 : I < that ? -1 : 0; } public bool Equals(int that) { return I == that; } public int CompareTo(IC that) { return I > that.I ? 1 : I < that.I ? -1 : 0; } public bool Equals(IC that) { return I == that.I; } public static bool Eq(SCG.IEnumerable<int> me, params int[] that) { int i = 0, maxind = that.Length - 1; foreach (int item in me) { if (i > maxind || item != that[i++]) { return false; } } return i == maxind + 1; } public static bool SetEq(ICollectionValue<int> me, params int[] that) { int[] me2 = me.ToArray(); Array.Sort(me2); int i = 0, maxind = that.Length - 1; foreach (int item in me2) { if (i > maxind || item != that[i++]) { return false; } } return i == maxind + 1; } public static bool SetEq(ICollectionValue<SCG.KeyValuePair<int, int>> me, params int[] that) { var first = new ArrayList<SCG.KeyValuePair<int, int>>(); first.AddAll(me); var other = new ArrayList<SCG.KeyValuePair<int, int>>(); for (int i = 0; i < that.Length; i += 2) { other.Add(new SCG.KeyValuePair<int, int>(that[i], that[i + 1])); } return other.UnsequencedEquals(first); } } internal class RevIC : SCG.IComparer<int> { public int Compare(int a, int b) { return a > b ? -1 : a < b ? 1 : 0; } } public class FunEnumerable : SCG.IEnumerable<int> { private readonly int size; private readonly Func<int, int> f; public FunEnumerable(int size, Func<int, int> f) { this.size = size; this.f = f; } public SCG.IEnumerator<int> GetEnumerator() { for (int i = 0; i < size; i++) { yield return f(i); } } #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); } #endregion } public class BadEnumerableException : Exception { } public class BadEnumerable<T> : CollectionValueBase<T>, ICollectionValue<T> { private readonly T[] contents; private readonly Exception exception; public BadEnumerable(Exception exception, params T[] contents) { this.contents = (T[])contents.Clone(); this.exception = exception; } public override SCG.IEnumerator<T> GetEnumerator() { for (int i = 0; i < contents.Length; i++) { yield return contents[i]; } throw exception; } public override bool IsEmpty => false; public override int Count => contents.Length + 1; public override Speed CountSpeed => Speed.Constant; public override T Choose() { throw exception; } } public class CollectionEventList<T> { private readonly ArrayList<CollectionEvent<T>> happened; private EventType listenTo; private readonly SCG.IEqualityComparer<T> itemequalityComparer; public CollectionEventList(SCG.IEqualityComparer<T> itemequalityComparer) { happened = new ArrayList<CollectionEvent<T>>(); this.itemequalityComparer = itemequalityComparer; } public void Listen(ICollectionValue<T> list, EventType listenTo) { this.listenTo = listenTo; if ((listenTo & EventType.Changed) != 0) { list.CollectionChanged += new CollectionChangedHandler<T>(changed); } if ((listenTo & EventType.Cleared) != 0) { list.CollectionCleared += new CollectionClearedHandler<T>(cleared); } if ((listenTo & EventType.Removed) != 0) { list.ItemsRemoved += new ItemsRemovedHandler<T>(removed); } if ((listenTo & EventType.Added) != 0) { list.ItemsAdded += new ItemsAddedHandler<T>(added); } if ((listenTo & EventType.Inserted) != 0) { list.ItemInserted += new ItemInsertedHandler<T>(inserted); } if ((listenTo & EventType.RemovedAt) != 0) { list.ItemRemovedAt += new ItemRemovedAtHandler<T>(removedAt); } } public void Add(CollectionEvent<T> e) { happened.Add(e); } /// <summary> /// Check that we have seen exactly the events in expected that match listenTo. /// </summary> /// <param name="expected"></param> public void Check(SCG.IEnumerable<CollectionEvent<T>> expected) { int i = 0; foreach (CollectionEvent<T> expectedEvent in expected) { if ((expectedEvent.Act & listenTo) == 0) { continue; } if (i >= happened.Count) { Assert.Fail(string.Format("Event number {0} did not happen:\n expected {1}", i, expectedEvent)); } if (!expectedEvent.Equals(happened[i], itemequalityComparer)) { Assert.Fail(string.Format("Event number {0}:\n expected {1}\n but saw {2}", i, expectedEvent, happened[i])); } i++; } if (i < happened.Count) { Assert.Fail(string.Format("Event number {0} seen but no event expected:\n {1}", i, happened[i])); } happened.Clear(); } public void Clear() { happened.Clear(); } public void Print(System.IO.TextWriter writer) { happened.Apply(delegate (CollectionEvent<T> e) { writer.WriteLine(e); }); } private void changed(object sender) { happened.Add(new CollectionEvent<T>(EventType.Changed, new EventArgs(), sender)); } private void cleared(object sender, ClearedEventArgs eventArgs) { happened.Add(new CollectionEvent<T>(EventType.Cleared, eventArgs, sender)); } private void added(object sender, ItemCountEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventType.Added, eventArgs, sender)); } private void removed(object sender, ItemCountEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventType.Removed, eventArgs, sender)); } private void inserted(object sender, ItemAtEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventType.Inserted, eventArgs, sender)); } private void removedAt(object sender, ItemAtEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventType.RemovedAt, eventArgs, sender)); } } public sealed class CollectionEvent<T> { public EventType Act { get; } public EventArgs Args { get; } public object Sender { get; } public CollectionEvent(EventType act, EventArgs args, object sender) { Act = act; Args = args; Sender = sender; } public bool Equals(CollectionEvent<T> otherEvent, SCG.IEqualityComparer<T> itemequalityComparer) { if (otherEvent == null || Act != otherEvent.Act || !object.ReferenceEquals(Sender, otherEvent.Sender)) { return false; } switch (Act) { case EventType.None: break; case EventType.Changed: return true; case EventType.Cleared: if (Args is ClearedRangeEventArgs) { ClearedRangeEventArgs a = Args as ClearedRangeEventArgs; if (!(otherEvent.Args is ClearedRangeEventArgs o)) { return false; } return a.Full == o.Full && a.Start == o.Start && a.Count == o.Count; } else { if (otherEvent.Args is ClearedRangeEventArgs) { return false; } ClearedEventArgs a = Args as ClearedEventArgs, o = otherEvent.Args as ClearedEventArgs; return a.Full == o.Full && a.Count == o.Count; } case EventType.Added: { ItemCountEventArgs<T> a = Args as ItemCountEventArgs<T>, o = otherEvent.Args as ItemCountEventArgs<T>; return itemequalityComparer.Equals(a.Item, o.Item) && a.Count == o.Count; } case EventType.Removed: { ItemCountEventArgs<T> a = Args as ItemCountEventArgs<T>, o = otherEvent.Args as ItemCountEventArgs<T>; return itemequalityComparer.Equals(a.Item, o.Item) && a.Count == o.Count; } case EventType.Inserted: { ItemAtEventArgs<T> a = Args as ItemAtEventArgs<T>, o = otherEvent.Args as ItemAtEventArgs<T>; return a.Index == o.Index && itemequalityComparer.Equals(a.Item, o.Item); } case EventType.RemovedAt: { ItemAtEventArgs<T> a = Args as ItemAtEventArgs<T>, o = otherEvent.Args as ItemAtEventArgs<T>; return a.Index == o.Index && itemequalityComparer.Equals(a.Item, o.Item); } } throw new ApplicationException("Illegal Action: " + Act); } public override string ToString() { return string.Format("Action: {0}, Args : {1}, Source : {2}", Act, Args, Sender); } } public class CHC { public static int UnsequencedHashCode(params int[] a) { int h = 0; foreach (int i in a) { h += (int)(((uint)i * 1529784657 + 1) ^ ((uint)i * 2912831877) ^ ((uint)i * 1118771817 + 2)); } return h; } public static int SequencedHashCode(params int[] a) { int h = 0; foreach (int i in a) { h = h * 31 + i; } return h; } } //This class is a modified sample from VS2005 beta1 documentation public class RadixFormatProvider : IFormatProvider { private readonly RadixFormatter _radixformatter; public RadixFormatProvider(int radix) { if (radix < 2 || radix > 36) { throw new ArgumentException(string.Format( "The radix \"{0}\" is not in the range 2..36.", radix)); } _radixformatter = new RadixFormatter(radix); } public object GetFormat(Type argType) { if (argType == typeof(ICustomFormatter)) { return _radixformatter; } else { return null; } } } //This class is a modified sample from VS2005 beta1 documentation public class RadixFormatter : ICustomFormatter { private readonly int radix; public RadixFormatter(int radix) { if (radix < 2 || radix > 36) { throw new ArgumentException(string.Format( "The radix \"{0}\" is not in the range 2..36.", radix)); } this.radix = radix; } // The value to be formatted is returned as a signed string // of digits from the rDigits array. private static readonly char[] rDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; public string Format(string format, object arg, IFormatProvider formatProvider) { /*switch (Type.GetTypeCode(argToBeFormatted.GetType())) { case TypeCode.Boolean: break; case TypeCode.Byte: break; case TypeCode.Char: break; case TypeCode.DBNull: break; case TypeCode.DateTime: break; case TypeCode.Decimal: break; case TypeCode.Double: break; case TypeCode.Empty: break; case TypeCode.Int16: break; case TypeCode.Int32: break; case TypeCode.Int64: break; case TypeCode.Object: break; case TypeCode.SByte: break; case TypeCode.Single: break; case TypeCode.String: break; case TypeCode.UInt16: break; case TypeCode.UInt32: break; case TypeCode.UInt64: break; }*/ int intToBeFormatted; try { intToBeFormatted = (int)arg; } catch (Exception) { if (arg is IFormattable) { return ((IFormattable)arg). ToString(format, formatProvider); } else if (IsKeyValuePair(arg)) { var (key, value) = GetKeyValuePair(arg); var formattedKey = Format(format, key, formatProvider); var formattedValue = Format(format, value, formatProvider); return $"[{formattedKey}, {formattedValue}]"; } else { return arg.ToString(); } } return formatInt(intToBeFormatted); } private string formatInt(int intToBeFormatted) { // The formatting is handled here. if (intToBeFormatted == 0) { return "0"; } int intPositive; char[] outDigits = new char[31]; // Verify that the argument can be converted to a int integer. // Extract the magnitude for conversion. intPositive = Math.Abs(intToBeFormatted); int digitIndex; // Convert the magnitude to a digit string. for (digitIndex = 0; digitIndex <= 32; digitIndex++) { if (intPositive == 0) { break; } outDigits[outDigits.Length - digitIndex - 1] = rDigits[intPositive % radix]; intPositive /= radix; } // Add a minus sign if the argument is negative. if (intToBeFormatted < 0) { outDigits[outDigits.Length - digitIndex++ - 1] = '-'; } return new string(outDigits, outDigits.Length - digitIndex, digitIndex); } // SCG.KeyValuePair is not showable, so we hack it now. private bool IsKeyValuePair(object arg) { if (arg != null) { var type = arg.GetType(); if (type.IsGenericType) { var baseType = type.GetGenericTypeDefinition(); return baseType == typeof(SCG.KeyValuePair<,>); } } return false; } private (object key, object value) GetKeyValuePair(object arg) { var type = arg.GetType(); var key = type.GetProperty("Key").GetValue(arg, null); var value = type.GetProperty("Value").GetValue(arg, null); return (key, value); } } }
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Text; using System.Reflection; using System.Runtime.Serialization; //This file contains all the typed enums that the client rest api spec exposes. //This file is automatically generated from https://github.com/elastic/elasticsearch/tree/v6.0.0-alpha1/rest-api-spec //Generated from commit v6.0.0-alpha1 namespace Elasticsearch.Net { public enum Refresh { [EnumMember(Value = "true")] True, [EnumMember(Value = "false")] False, [EnumMember(Value = "wait_for")] WaitFor } public enum Bytes { [EnumMember(Value = "b")] B, [EnumMember(Value = "k")] K, [EnumMember(Value = "kb")] Kb, [EnumMember(Value = "m")] M, [EnumMember(Value = "mb")] Mb, [EnumMember(Value = "g")] G, [EnumMember(Value = "gb")] Gb, [EnumMember(Value = "t")] T, [EnumMember(Value = "tb")] Tb, [EnumMember(Value = "p")] P, [EnumMember(Value = "pb")] Pb } public enum Health { [EnumMember(Value = "green")] Green, [EnumMember(Value = "yellow")] Yellow, [EnumMember(Value = "red")] Red } public enum Size { [EnumMember(Value = "")] Raw, [EnumMember(Value = "k")] K, [EnumMember(Value = "m")] M, [EnumMember(Value = "g")] G, [EnumMember(Value = "t")] T, [EnumMember(Value = "p")] P } public enum Level { [EnumMember(Value = "cluster")] Cluster, [EnumMember(Value = "indices")] Indices, [EnumMember(Value = "shards")] Shards } public enum WaitForEvents { [EnumMember(Value = "immediate")] Immediate, [EnumMember(Value = "urgent")] Urgent, [EnumMember(Value = "high")] High, [EnumMember(Value = "normal")] Normal, [EnumMember(Value = "low")] Low, [EnumMember(Value = "languid")] Languid } public enum WaitForStatus { [EnumMember(Value = "green")] Green, [EnumMember(Value = "yellow")] Yellow, [EnumMember(Value = "red")] Red } public enum ExpandWildcards { [EnumMember(Value = "open")] Open, [EnumMember(Value = "closed")] Closed, [EnumMember(Value = "none")] None, [EnumMember(Value = "all")] All } public enum DefaultOperator { [EnumMember(Value = "AND")] And, [EnumMember(Value = "OR")] Or } public enum VersionType { [EnumMember(Value = "internal")] Internal, [EnumMember(Value = "external")] External, [EnumMember(Value = "external_gte")] ExternalGte, [EnumMember(Value = "force")] Force } public enum Conflicts { [EnumMember(Value = "abort")] Abort, [EnumMember(Value = "proceed")] Proceed } public enum SearchType { [EnumMember(Value = "query_then_fetch")] QueryThenFetch, [EnumMember(Value = "dfs_query_then_fetch")] DfsQueryThenFetch } public enum OpType { [EnumMember(Value = "index")] Index, [EnumMember(Value = "create")] Create } public enum Format { [EnumMember(Value = "detailed")] Detailed, [EnumMember(Value = "text")] Text } public enum ThreadType { [EnumMember(Value = "cpu")] Cpu, [EnumMember(Value = "wait")] Wait, [EnumMember(Value = "block")] Block } public enum SuggestMode { [EnumMember(Value = "missing")] Missing, [EnumMember(Value = "popular")] Popular, [EnumMember(Value = "always")] Always } public enum GroupBy { [EnumMember(Value = "nodes")] Nodes, [EnumMember(Value = "parents")] Parents } [Flags]public enum ClusterStateMetric { [EnumMember(Value = "blocks")] Blocks = 1 << 0, [EnumMember(Value = "metadata")] Metadata = 1 << 1, [EnumMember(Value = "nodes")] Nodes = 1 << 2, [EnumMember(Value = "routing_table")] RoutingTable = 1 << 3, [EnumMember(Value = "routing_nodes")] RoutingNodes = 1 << 4, [EnumMember(Value = "master_node")] MasterNode = 1 << 5, [EnumMember(Value = "version")] Version = 1 << 6, [EnumMember(Value = "_all")] All = 1 << 7 } [Flags]public enum Feature { [EnumMember(Value = "_settings")] Settings = 1 << 0, [EnumMember(Value = "_mappings")] Mappings = 1 << 1, [EnumMember(Value = "_aliases")] Aliases = 1 << 2 } [Flags]public enum IndicesStatsMetric { [EnumMember(Value = "completion")] Completion = 1 << 0, [EnumMember(Value = "docs")] Docs = 1 << 1, [EnumMember(Value = "fielddata")] Fielddata = 1 << 2, [EnumMember(Value = "query_cache")] QueryCache = 1 << 3, [EnumMember(Value = "flush")] Flush = 1 << 4, [EnumMember(Value = "get")] Get = 1 << 5, [EnumMember(Value = "indexing")] Indexing = 1 << 6, [EnumMember(Value = "merge")] Merge = 1 << 7, [EnumMember(Value = "request_cache")] RequestCache = 1 << 8, [EnumMember(Value = "refresh")] Refresh = 1 << 9, [EnumMember(Value = "search")] Search = 1 << 10, [EnumMember(Value = "segments")] Segments = 1 << 11, [EnumMember(Value = "store")] Store = 1 << 12, [EnumMember(Value = "warmer")] Warmer = 1 << 13, [EnumMember(Value = "suggest")] Suggest = 1 << 14, [EnumMember(Value = "_all")] All = 1 << 15 } [Flags]public enum NodesInfoMetric { [EnumMember(Value = "settings")] Settings = 1 << 0, [EnumMember(Value = "os")] Os = 1 << 1, [EnumMember(Value = "process")] Process = 1 << 2, [EnumMember(Value = "jvm")] Jvm = 1 << 3, [EnumMember(Value = "thread_pool")] ThreadPool = 1 << 4, [EnumMember(Value = "transport")] Transport = 1 << 5, [EnumMember(Value = "http")] Http = 1 << 6, [EnumMember(Value = "plugins")] Plugins = 1 << 7, [EnumMember(Value = "ingest")] Ingest = 1 << 8 } [Flags]public enum NodesStatsMetric { [EnumMember(Value = "breaker")] Breaker = 1 << 0, [EnumMember(Value = "fs")] Fs = 1 << 1, [EnumMember(Value = "http")] Http = 1 << 2, [EnumMember(Value = "indices")] Indices = 1 << 3, [EnumMember(Value = "jvm")] Jvm = 1 << 4, [EnumMember(Value = "os")] Os = 1 << 5, [EnumMember(Value = "process")] Process = 1 << 6, [EnumMember(Value = "thread_pool")] ThreadPool = 1 << 7, [EnumMember(Value = "transport")] Transport = 1 << 8, [EnumMember(Value = "discovery")] Discovery = 1 << 9, [EnumMember(Value = "_all")] All = 1 << 10 } [Flags]public enum NodesStatsIndexMetric { [EnumMember(Value = "completion")] Completion = 1 << 0, [EnumMember(Value = "docs")] Docs = 1 << 1, [EnumMember(Value = "fielddata")] Fielddata = 1 << 2, [EnumMember(Value = "query_cache")] QueryCache = 1 << 3, [EnumMember(Value = "flush")] Flush = 1 << 4, [EnumMember(Value = "get")] Get = 1 << 5, [EnumMember(Value = "indexing")] Indexing = 1 << 6, [EnumMember(Value = "merge")] Merge = 1 << 7, [EnumMember(Value = "request_cache")] RequestCache = 1 << 8, [EnumMember(Value = "refresh")] Refresh = 1 << 9, [EnumMember(Value = "search")] Search = 1 << 10, [EnumMember(Value = "segments")] Segments = 1 << 11, [EnumMember(Value = "store")] Store = 1 << 12, [EnumMember(Value = "warmer")] Warmer = 1 << 13, [EnumMember(Value = "suggest")] Suggest = 1 << 14, [EnumMember(Value = "_all")] All = 1 << 15 } [Flags]public enum WatcherStatsMetric { [EnumMember(Value = "queued_watches")] QueuedWatches = 1 << 0, [EnumMember(Value = "pending_watches")] PendingWatches = 1 << 1, [EnumMember(Value = "_all")] All = 1 << 2 } public static class KnownEnums { private class EnumDictionary : Dictionary<Enum, string> { public EnumDictionary(int capacity) : base(capacity) {} public Func<Enum, string> Resolver { get; set; } } public static string GetStringValue(this Refresh enumValue) { switch (enumValue) { case Refresh.True: return "true"; case Refresh.False: return "false"; case Refresh.WaitFor: return "wait_for"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'Refresh'"); } public static string GetStringValue(this Bytes enumValue) { switch (enumValue) { case Bytes.B: return "b"; case Bytes.K: return "k"; case Bytes.Kb: return "kb"; case Bytes.M: return "m"; case Bytes.Mb: return "mb"; case Bytes.G: return "g"; case Bytes.Gb: return "gb"; case Bytes.T: return "t"; case Bytes.Tb: return "tb"; case Bytes.P: return "p"; case Bytes.Pb: return "pb"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'Bytes'"); } public static string GetStringValue(this Health enumValue) { switch (enumValue) { case Health.Green: return "green"; case Health.Yellow: return "yellow"; case Health.Red: return "red"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'Health'"); } public static string GetStringValue(this Size enumValue) { switch (enumValue) { case Size.Raw: return ""; case Size.K: return "k"; case Size.M: return "m"; case Size.G: return "g"; case Size.T: return "t"; case Size.P: return "p"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'Size'"); } public static string GetStringValue(this Level enumValue) { switch (enumValue) { case Level.Cluster: return "cluster"; case Level.Indices: return "indices"; case Level.Shards: return "shards"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'Level'"); } public static string GetStringValue(this WaitForEvents enumValue) { switch (enumValue) { case WaitForEvents.Immediate: return "immediate"; case WaitForEvents.Urgent: return "urgent"; case WaitForEvents.High: return "high"; case WaitForEvents.Normal: return "normal"; case WaitForEvents.Low: return "low"; case WaitForEvents.Languid: return "languid"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'WaitForEvents'"); } public static string GetStringValue(this WaitForStatus enumValue) { switch (enumValue) { case WaitForStatus.Green: return "green"; case WaitForStatus.Yellow: return "yellow"; case WaitForStatus.Red: return "red"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'WaitForStatus'"); } public static string GetStringValue(this ExpandWildcards enumValue) { switch (enumValue) { case ExpandWildcards.Open: return "open"; case ExpandWildcards.Closed: return "closed"; case ExpandWildcards.None: return "none"; case ExpandWildcards.All: return "all"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'ExpandWildcards'"); } public static string GetStringValue(this DefaultOperator enumValue) { switch (enumValue) { case DefaultOperator.And: return "AND"; case DefaultOperator.Or: return "OR"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'DefaultOperator'"); } public static string GetStringValue(this VersionType enumValue) { switch (enumValue) { case VersionType.Internal: return "internal"; case VersionType.External: return "external"; case VersionType.ExternalGte: return "external_gte"; case VersionType.Force: return "force"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'VersionType'"); } public static string GetStringValue(this Conflicts enumValue) { switch (enumValue) { case Conflicts.Abort: return "abort"; case Conflicts.Proceed: return "proceed"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'Conflicts'"); } public static string GetStringValue(this SearchType enumValue) { switch (enumValue) { case SearchType.QueryThenFetch: return "query_then_fetch"; case SearchType.DfsQueryThenFetch: return "dfs_query_then_fetch"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'SearchType'"); } public static string GetStringValue(this OpType enumValue) { switch (enumValue) { case OpType.Index: return "index"; case OpType.Create: return "create"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'OpType'"); } public static string GetStringValue(this Format enumValue) { switch (enumValue) { case Format.Detailed: return "detailed"; case Format.Text: return "text"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'Format'"); } public static string GetStringValue(this ThreadType enumValue) { switch (enumValue) { case ThreadType.Cpu: return "cpu"; case ThreadType.Wait: return "wait"; case ThreadType.Block: return "block"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'ThreadType'"); } public static string GetStringValue(this SuggestMode enumValue) { switch (enumValue) { case SuggestMode.Missing: return "missing"; case SuggestMode.Popular: return "popular"; case SuggestMode.Always: return "always"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'SuggestMode'"); } public static string GetStringValue(this GroupBy enumValue) { switch (enumValue) { case GroupBy.Nodes: return "nodes"; case GroupBy.Parents: return "parents"; } throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum 'GroupBy'"); } public static string GetStringValue(this ClusterStateMetric enumValue) { if ((enumValue & ClusterStateMetric.All) != 0) return "_all"; var list = new List<string>(); if ((enumValue & ClusterStateMetric.Blocks) != 0) list.Add("blocks"); if ((enumValue & ClusterStateMetric.Metadata) != 0) list.Add("metadata"); if ((enumValue & ClusterStateMetric.Nodes) != 0) list.Add("nodes"); if ((enumValue & ClusterStateMetric.RoutingTable) != 0) list.Add("routing_table"); if ((enumValue & ClusterStateMetric.RoutingNodes) != 0) list.Add("routing_nodes"); if ((enumValue & ClusterStateMetric.MasterNode) != 0) list.Add("master_node"); if ((enumValue & ClusterStateMetric.Version) != 0) list.Add("version"); return string.Join(",", list); } public static string GetStringValue(this Feature enumValue) { var list = new List<string>(); if ((enumValue & Feature.Settings) != 0) list.Add("_settings"); if ((enumValue & Feature.Mappings) != 0) list.Add("_mappings"); if ((enumValue & Feature.Aliases) != 0) list.Add("_aliases"); return string.Join(",", list); } public static string GetStringValue(this IndicesStatsMetric enumValue) { if ((enumValue & IndicesStatsMetric.All) != 0) return "_all"; var list = new List<string>(); if ((enumValue & IndicesStatsMetric.Completion) != 0) list.Add("completion"); if ((enumValue & IndicesStatsMetric.Docs) != 0) list.Add("docs"); if ((enumValue & IndicesStatsMetric.Fielddata) != 0) list.Add("fielddata"); if ((enumValue & IndicesStatsMetric.QueryCache) != 0) list.Add("query_cache"); if ((enumValue & IndicesStatsMetric.Flush) != 0) list.Add("flush"); if ((enumValue & IndicesStatsMetric.Get) != 0) list.Add("get"); if ((enumValue & IndicesStatsMetric.Indexing) != 0) list.Add("indexing"); if ((enumValue & IndicesStatsMetric.Merge) != 0) list.Add("merge"); if ((enumValue & IndicesStatsMetric.RequestCache) != 0) list.Add("request_cache"); if ((enumValue & IndicesStatsMetric.Refresh) != 0) list.Add("refresh"); if ((enumValue & IndicesStatsMetric.Search) != 0) list.Add("search"); if ((enumValue & IndicesStatsMetric.Segments) != 0) list.Add("segments"); if ((enumValue & IndicesStatsMetric.Store) != 0) list.Add("store"); if ((enumValue & IndicesStatsMetric.Warmer) != 0) list.Add("warmer"); if ((enumValue & IndicesStatsMetric.Suggest) != 0) list.Add("suggest"); return string.Join(",", list); } public static string GetStringValue(this NodesInfoMetric enumValue) { var list = new List<string>(); if ((enumValue & NodesInfoMetric.Settings) != 0) list.Add("settings"); if ((enumValue & NodesInfoMetric.Os) != 0) list.Add("os"); if ((enumValue & NodesInfoMetric.Process) != 0) list.Add("process"); if ((enumValue & NodesInfoMetric.Jvm) != 0) list.Add("jvm"); if ((enumValue & NodesInfoMetric.ThreadPool) != 0) list.Add("thread_pool"); if ((enumValue & NodesInfoMetric.Transport) != 0) list.Add("transport"); if ((enumValue & NodesInfoMetric.Http) != 0) list.Add("http"); if ((enumValue & NodesInfoMetric.Plugins) != 0) list.Add("plugins"); if ((enumValue & NodesInfoMetric.Ingest) != 0) list.Add("ingest"); return string.Join(",", list); } public static string GetStringValue(this NodesStatsMetric enumValue) { if ((enumValue & NodesStatsMetric.All) != 0) return "_all"; var list = new List<string>(); if ((enumValue & NodesStatsMetric.Breaker) != 0) list.Add("breaker"); if ((enumValue & NodesStatsMetric.Fs) != 0) list.Add("fs"); if ((enumValue & NodesStatsMetric.Http) != 0) list.Add("http"); if ((enumValue & NodesStatsMetric.Indices) != 0) list.Add("indices"); if ((enumValue & NodesStatsMetric.Jvm) != 0) list.Add("jvm"); if ((enumValue & NodesStatsMetric.Os) != 0) list.Add("os"); if ((enumValue & NodesStatsMetric.Process) != 0) list.Add("process"); if ((enumValue & NodesStatsMetric.ThreadPool) != 0) list.Add("thread_pool"); if ((enumValue & NodesStatsMetric.Transport) != 0) list.Add("transport"); if ((enumValue & NodesStatsMetric.Discovery) != 0) list.Add("discovery"); return string.Join(",", list); } public static string GetStringValue(this NodesStatsIndexMetric enumValue) { if ((enumValue & NodesStatsIndexMetric.All) != 0) return "_all"; var list = new List<string>(); if ((enumValue & NodesStatsIndexMetric.Completion) != 0) list.Add("completion"); if ((enumValue & NodesStatsIndexMetric.Docs) != 0) list.Add("docs"); if ((enumValue & NodesStatsIndexMetric.Fielddata) != 0) list.Add("fielddata"); if ((enumValue & NodesStatsIndexMetric.QueryCache) != 0) list.Add("query_cache"); if ((enumValue & NodesStatsIndexMetric.Flush) != 0) list.Add("flush"); if ((enumValue & NodesStatsIndexMetric.Get) != 0) list.Add("get"); if ((enumValue & NodesStatsIndexMetric.Indexing) != 0) list.Add("indexing"); if ((enumValue & NodesStatsIndexMetric.Merge) != 0) list.Add("merge"); if ((enumValue & NodesStatsIndexMetric.RequestCache) != 0) list.Add("request_cache"); if ((enumValue & NodesStatsIndexMetric.Refresh) != 0) list.Add("refresh"); if ((enumValue & NodesStatsIndexMetric.Search) != 0) list.Add("search"); if ((enumValue & NodesStatsIndexMetric.Segments) != 0) list.Add("segments"); if ((enumValue & NodesStatsIndexMetric.Store) != 0) list.Add("store"); if ((enumValue & NodesStatsIndexMetric.Warmer) != 0) list.Add("warmer"); if ((enumValue & NodesStatsIndexMetric.Suggest) != 0) list.Add("suggest"); return string.Join(",", list); } public static string GetStringValue(this WatcherStatsMetric enumValue) { if ((enumValue & WatcherStatsMetric.All) != 0) return "_all"; var list = new List<string>(); if ((enumValue & WatcherStatsMetric.QueuedWatches) != 0) list.Add("queued_watches"); if ((enumValue & WatcherStatsMetric.PendingWatches) != 0) list.Add("pending_watches"); return string.Join(",", list); } private static readonly ConcurrentDictionary<Type, Func<Enum, string>> EnumStringResolvers = new ConcurrentDictionary<Type, Func<Enum, string>>(); static KnownEnums() { EnumStringResolvers.TryAdd(typeof(Refresh), (e) => GetStringValue((Refresh)e)); EnumStringResolvers.TryAdd(typeof(Bytes), (e) => GetStringValue((Bytes)e)); EnumStringResolvers.TryAdd(typeof(Health), (e) => GetStringValue((Health)e)); EnumStringResolvers.TryAdd(typeof(Size), (e) => GetStringValue((Size)e)); EnumStringResolvers.TryAdd(typeof(Level), (e) => GetStringValue((Level)e)); EnumStringResolvers.TryAdd(typeof(WaitForEvents), (e) => GetStringValue((WaitForEvents)e)); EnumStringResolvers.TryAdd(typeof(WaitForStatus), (e) => GetStringValue((WaitForStatus)e)); EnumStringResolvers.TryAdd(typeof(ExpandWildcards), (e) => GetStringValue((ExpandWildcards)e)); EnumStringResolvers.TryAdd(typeof(DefaultOperator), (e) => GetStringValue((DefaultOperator)e)); EnumStringResolvers.TryAdd(typeof(VersionType), (e) => GetStringValue((VersionType)e)); EnumStringResolvers.TryAdd(typeof(Conflicts), (e) => GetStringValue((Conflicts)e)); EnumStringResolvers.TryAdd(typeof(SearchType), (e) => GetStringValue((SearchType)e)); EnumStringResolvers.TryAdd(typeof(OpType), (e) => GetStringValue((OpType)e)); EnumStringResolvers.TryAdd(typeof(Format), (e) => GetStringValue((Format)e)); EnumStringResolvers.TryAdd(typeof(ThreadType), (e) => GetStringValue((ThreadType)e)); EnumStringResolvers.TryAdd(typeof(SuggestMode), (e) => GetStringValue((SuggestMode)e)); EnumStringResolvers.TryAdd(typeof(GroupBy), (e) => GetStringValue((GroupBy)e)); EnumStringResolvers.TryAdd(typeof(ClusterStateMetric), (e) => GetStringValue((ClusterStateMetric)e)); EnumStringResolvers.TryAdd(typeof(Feature), (e) => GetStringValue((Feature)e)); EnumStringResolvers.TryAdd(typeof(IndicesStatsMetric), (e) => GetStringValue((IndicesStatsMetric)e)); EnumStringResolvers.TryAdd(typeof(NodesInfoMetric), (e) => GetStringValue((NodesInfoMetric)e)); EnumStringResolvers.TryAdd(typeof(NodesStatsMetric), (e) => GetStringValue((NodesStatsMetric)e)); EnumStringResolvers.TryAdd(typeof(NodesStatsIndexMetric), (e) => GetStringValue((NodesStatsIndexMetric)e)); EnumStringResolvers.TryAdd(typeof(WatcherStatsMetric), (e) => GetStringValue((WatcherStatsMetric)e)); } public static string GetStringValue(this Enum e) { var type = e.GetType(); var resolver = EnumStringResolvers.GetOrAdd(type, GetEnumStringResolver); return resolver(e); } private static Func<Enum, string> GetEnumStringResolver(Type type) { var values = Enum.GetValues(type); var dictionary = new EnumDictionary(values.Length); for (int index = 0; index < values.Length; index++) { var value = values.GetValue(index); #if DOTNETCORE var info = type.GetTypeInfo().GetDeclaredField(value.ToString()); #else var info = type.GetField(value.ToString()); #endif var da = (EnumMemberAttribute[])info.GetCustomAttributes(typeof(EnumMemberAttribute), false); var stringValue = da.Length > 0 ? da[0].Value : Enum.GetName(type, value); dictionary.Add((Enum)value, stringValue); } #if DOTNETCORE var isFlag = type.GetTypeInfo().GetCustomAttributes(typeof(FlagsAttribute), false).Any(); #else var isFlag = type.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0; #endif return (e) => { if (isFlag) { var list = new List<string>(); foreach(var kv in dictionary) { if (e.HasFlag(kv.Key)) list.Add(kv.Value); } return string.Join(",", list); } else { return dictionary[e]; } }; } } }
// Copyright (C) 2014 dot42 // // Original filename: Junit.Runner.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Junit.Runner { /// <summary> /// <para>An interface to define how a test suite should be loaded. </para> /// </summary> /// <java-name> /// junit/runner/TestSuiteLoader /// </java-name> [Dot42.DexImport("junit/runner/TestSuiteLoader", AccessFlags = 1537)] public partial interface ITestSuiteLoader /* scope: __dot42__ */ { /// <java-name> /// load /// </java-name> [Dot42.DexImport("load", "(Ljava/lang/String;)Ljava/lang/Class;", AccessFlags = 1025)] global::System.Type Load(string suiteClassName) /* MethodBuilder.Create */ ; /// <java-name> /// reload /// </java-name> [Dot42.DexImport("reload", "(Ljava/lang/Class;)Ljava/lang/Class;", AccessFlags = 1025)] global::System.Type Reload(global::System.Type aClass) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Base class for all test runners. This class was born live on stage in Sardinia during XP2000. </para> /// </summary> /// <java-name> /// junit/runner/BaseTestRunner /// </java-name> [Dot42.DexImport("junit/runner/BaseTestRunner", AccessFlags = 1057)] public abstract partial class BaseTestRunner : global::Junit.Framework.ITestListener /* scope: __dot42__ */ { /// <java-name> /// SUITE_METHODNAME /// </java-name> [Dot42.DexImport("SUITE_METHODNAME", "Ljava/lang/String;", AccessFlags = 25)] public const string SUITE_METHODNAME = "suite"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public BaseTestRunner() /* MethodBuilder.Create */ { } /// <summary> /// <para>A test started. </para> /// </summary> /// <java-name> /// startTest /// </java-name> [Dot42.DexImport("startTest", "(Ljunit/framework/Test;)V", AccessFlags = 33)] public virtual void StartTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ { } /// <java-name> /// setPreferences /// </java-name> [Dot42.DexImport("setPreferences", "(Ljava/util/Properties;)V", AccessFlags = 12)] protected internal static void SetPreferences(global::Java.Util.Properties preferences) /* MethodBuilder.Create */ { } /// <java-name> /// getPreferences /// </java-name> [Dot42.DexImport("getPreferences", "()Ljava/util/Properties;", AccessFlags = 12)] protected internal static global::Java.Util.Properties GetPreferences() /* MethodBuilder.Create */ { return default(global::Java.Util.Properties); } /// <java-name> /// savePreferences /// </java-name> [Dot42.DexImport("savePreferences", "()V", AccessFlags = 9)] public static void SavePreferences() /* MethodBuilder.Create */ { } /// <java-name> /// setPreference /// </java-name> [Dot42.DexImport("setPreference", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetPreference(string key, string value) /* MethodBuilder.Create */ { } /// <summary> /// <para>A test ended. </para> /// </summary> /// <java-name> /// endTest /// </java-name> [Dot42.DexImport("endTest", "(Ljunit/framework/Test;)V", AccessFlags = 33)] public virtual void EndTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ { } /// <java-name> /// addError /// </java-name> [Dot42.DexImport("addError", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 33)] public virtual void AddError(global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */ { } /// <java-name> /// addFailure /// </java-name> [Dot42.DexImport("addFailure", "(Ljunit/framework/Test;Ljunit/framework/AssertionFailedError;)V", AccessFlags = 33)] public virtual void AddFailure(global::Junit.Framework.ITest test, global::Junit.Framework.AssertionFailedError t) /* MethodBuilder.Create */ { } /// <java-name> /// testStarted /// </java-name> [Dot42.DexImport("testStarted", "(Ljava/lang/String;)V", AccessFlags = 1025)] public abstract void TestStarted(string testName) /* MethodBuilder.Create */ ; /// <java-name> /// testEnded /// </java-name> [Dot42.DexImport("testEnded", "(Ljava/lang/String;)V", AccessFlags = 1025)] public abstract void TestEnded(string testName) /* MethodBuilder.Create */ ; /// <java-name> /// testFailed /// </java-name> [Dot42.DexImport("testFailed", "(ILjunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1025)] public abstract void TestFailed(int status, global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the Test corresponding to the given suite. This is a template method, subclasses override runFailed(), clearStatus(). </para> /// </summary> /// <java-name> /// getTest /// </java-name> [Dot42.DexImport("getTest", "(Ljava/lang/String;)Ljunit/framework/Test;", AccessFlags = 1)] public virtual global::Junit.Framework.ITest GetTest(string suiteClassName) /* MethodBuilder.Create */ { return default(global::Junit.Framework.ITest); } /// <summary> /// <para>Returns the formatted string of the elapsed time. </para> /// </summary> /// <java-name> /// elapsedTimeAsString /// </java-name> [Dot42.DexImport("elapsedTimeAsString", "(J)Ljava/lang/String;", AccessFlags = 1)] public virtual string ElapsedTimeAsString(long runTime) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Processes the command line arguments and returns the name of the suite class to run or null </para> /// </summary> /// <java-name> /// processArguments /// </java-name> [Dot42.DexImport("processArguments", "([Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 4)] protected internal virtual string ProcessArguments(string[] args) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the loading behaviour of the test runner </para> /// </summary> /// <java-name> /// setLoading /// </java-name> [Dot42.DexImport("setLoading", "(Z)V", AccessFlags = 1)] public virtual void SetLoading(bool enable) /* MethodBuilder.Create */ { } /// <summary> /// <para>Extract the class name from a String in VA/Java style </para> /// </summary> /// <java-name> /// extractClassName /// </java-name> [Dot42.DexImport("extractClassName", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1)] public virtual string ExtractClassName(string className) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Truncates a String to the maximum length. </para> /// </summary> /// <java-name> /// truncate /// </java-name> [Dot42.DexImport("truncate", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string Truncate(string s) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Override to define how to handle a failed loading of a test suite. </para> /// </summary> /// <java-name> /// runFailed /// </java-name> [Dot42.DexImport("runFailed", "(Ljava/lang/String;)V", AccessFlags = 1028)] protected internal abstract void RunFailed(string message) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the loader to be used.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>not present in JUnit4.10 </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// getLoader /// </java-name> [Dot42.DexImport("getLoader", "()Ljunit/runner/TestSuiteLoader;", AccessFlags = 1)] public virtual global::Junit.Runner.ITestSuiteLoader GetLoader() /* MethodBuilder.Create */ { return default(global::Junit.Runner.ITestSuiteLoader); } /// <summary> /// <para>Returns the loaded Class for a suite name. </para> /// </summary> /// <java-name> /// loadSuiteClass /// </java-name> [Dot42.DexImport("loadSuiteClass", "(Ljava/lang/String;)Ljava/lang/Class;", AccessFlags = 4, Signature = "(Ljava/lang/String;)Ljava/lang/Class<*>;")] protected internal virtual global::System.Type LoadSuiteClass(string suiteClassName) /* MethodBuilder.Create */ { return default(global::System.Type); } /// <summary> /// <para>Clears the status message. </para> /// </summary> /// <java-name> /// clearStatus /// </java-name> [Dot42.DexImport("clearStatus", "()V", AccessFlags = 4)] protected internal virtual void ClearStatus() /* MethodBuilder.Create */ { } /// <java-name> /// useReloadingTestSuiteLoader /// </java-name> [Dot42.DexImport("useReloadingTestSuiteLoader", "()Z", AccessFlags = 4)] protected internal virtual bool UseReloadingTestSuiteLoader() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getPreference /// </java-name> [Dot42.DexImport("getPreference", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string GetPreference(string key) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getPreference /// </java-name> [Dot42.DexImport("getPreference", "(Ljava/lang/String;I)I", AccessFlags = 9)] public static int GetPreference(string key, int dflt) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// getFilteredTrace /// </java-name> [Dot42.DexImport("getFilteredTrace", "(Ljava/lang/Throwable;)Ljava/lang/String;", AccessFlags = 9)] public static string GetFilteredTrace(global::System.Exception exception) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>not present in JUnit4.10 </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// inVAJava /// </java-name> [Dot42.DexImport("inVAJava", "()Z", AccessFlags = 9)] public static bool InVAJava() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getFilteredTrace /// </java-name> [Dot42.DexImport("getFilteredTrace", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string GetFilteredTrace(string @string) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// showStackRaw /// </java-name> [Dot42.DexImport("showStackRaw", "()Z", AccessFlags = 12)] protected internal static bool ShowStackRaw() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getPreferences /// </java-name> protected internal static global::Java.Util.Properties Preferences { [Dot42.DexImport("getPreferences", "()Ljava/util/Properties;", AccessFlags = 12)] get{ return GetPreferences(); } [Dot42.DexImport("setPreferences", "(Ljava/util/Properties;)V", AccessFlags = 12)] set{ SetPreferences(value); } } /// <summary> /// <para>Returns the loader to be used.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>not present in JUnit4.10 </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// getLoader /// </java-name> public global::Junit.Runner.ITestSuiteLoader Loader { [Dot42.DexImport("getLoader", "()Ljunit/runner/TestSuiteLoader;", AccessFlags = 1)] get{ return GetLoader(); } } } /// <summary> /// <para>This class defines the current version of JUnit </para> /// </summary> /// <java-name> /// junit/runner/Version /// </java-name> [Dot42.DexImport("junit/runner/Version", AccessFlags = 33)] public partial class Version /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal Version() /* MethodBuilder.Create */ { } /// <java-name> /// id /// </java-name> [Dot42.DexImport("id", "()Ljava/lang/String;", AccessFlags = 9)] public static string Id() /* MethodBuilder.Create */ { return default(string); } } }
using System; using Cosmos.IL2CPU.X86; using CPU = Cosmos.Assembler.x86; using Cosmos.Assembler.x86; using Label = Cosmos.Assembler.Label; namespace Cosmos.IL2CPU.X86.IL { [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Beq)] [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Bge)] [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Bgt)] [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Ble)] [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Blt)] [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Bne_Un)] [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Bge_Un)] [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Bgt_Un)] [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Ble_Un)] [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Blt_Un)] [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Brfalse)] [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Brtrue)] public class Branch : ILOp { public Branch(Cosmos.Assembler.Assembler aAsmblr) : base(aAsmblr) { } public override void Execute(MethodInfo aMethod, ILOpCode aOpCode) { var xIsSingleCompare = true; switch (aOpCode.OpCode) { case ILOpCode.Code.Beq: case ILOpCode.Code.Bge: case ILOpCode.Code.Bgt: case ILOpCode.Code.Bge_Un: case ILOpCode.Code.Bgt_Un: case ILOpCode.Code.Ble: case ILOpCode.Code.Ble_Un: case ILOpCode.Code.Bne_Un: case ILOpCode.Code.Blt: case ILOpCode.Code.Blt_Un: Assembler.Stack.Pop(); xIsSingleCompare = false; break; } var xStackContent = Assembler.Stack.Pop(); if (xStackContent.Size > 8) { throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: StackSize > 8 not supported"); } CPU.ConditionalTestEnum xTestOp; // all conditions are inverted here? switch (aOpCode.OpCode) { case ILOpCode.Code.Beq: xTestOp = CPU.ConditionalTestEnum.Zero; break; case ILOpCode.Code.Bge: xTestOp = CPU.ConditionalTestEnum.GreaterThanOrEqualTo; break; case ILOpCode.Code.Bgt: xTestOp = CPU.ConditionalTestEnum.GreaterThan; break; case ILOpCode.Code.Ble: xTestOp = CPU.ConditionalTestEnum.LessThanOrEqualTo; break; case ILOpCode.Code.Blt: xTestOp = CPU.ConditionalTestEnum.LessThan; break; case ILOpCode.Code.Bne_Un: xTestOp = CPU.ConditionalTestEnum.NotEqual; break; case ILOpCode.Code.Bge_Un: xTestOp = CPU.ConditionalTestEnum.AboveOrEqual; break; case ILOpCode.Code.Bgt_Un: xTestOp = CPU.ConditionalTestEnum.Above; break; case ILOpCode.Code.Ble_Un: xTestOp = CPU.ConditionalTestEnum.BelowOrEqual; break; case ILOpCode.Code.Blt_Un: xTestOp = CPU.ConditionalTestEnum.Below; break; case ILOpCode.Code.Brfalse: xTestOp = CPU.ConditionalTestEnum.Zero; break; case ILOpCode.Code.Brtrue: xTestOp = CPU.ConditionalTestEnum.NotZero; break; default: throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Unknown OpCode for conditional branch."); } if (!xIsSingleCompare) { if (xStackContent.Size <= 4) { //if (xStackContent.IsFloat) //{ // throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Comparison of floats (System.Single) is not yet supported!"); //} //else //{ new CPU.Pop { DestinationReg = CPU.Registers.EAX }; new CPU.Pop { DestinationReg = CPU.Registers.EBX }; new CPU.Compare { DestinationReg = CPU.Registers.EBX, SourceReg = CPU.Registers.EAX }; new CPU.ConditionalJump { Condition = xTestOp, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; //} } else { //if (xStackContent.IsFloat) //{ // throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Comparison of doubles (System.Double) is not yet supported!"); //} //else //{ var xNoJump = GetLabel(aMethod, aOpCode) + "__NoBranch"; // value 2 EBX:EAX new CPU.Pop { DestinationReg = CPU.Registers.EAX }; new CPU.Pop { DestinationReg = CPU.Registers.EBX }; // value 1 EDX:ECX new CPU.Pop { DestinationReg = CPU.Registers.ECX }; new CPU.Pop { DestinationReg = CPU.Registers.EDX }; switch (xTestOp) { case ConditionalTestEnum.Zero: // Equal case ConditionalTestEnum.NotEqual: // NotZero new CPU.Xor { DestinationReg = CPU.Registers.EAX, SourceReg = CPU.Registers.ECX }; new CPU.ConditionalJump { Condition = xTestOp, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; new CPU.Xor { DestinationReg = CPU.Registers.EBX, SourceReg = CPU.Registers.EDX }; new CPU.ConditionalJump { Condition = xTestOp, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; break; case ConditionalTestEnum.GreaterThanOrEqualTo: new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.LessThan, DestinationLabel = xNoJump }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.GreaterThan, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Below, DestinationLabel = xNoJump }; break; case ConditionalTestEnum.GreaterThan: new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.LessThan, DestinationLabel = xNoJump }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.GreaterThan, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.BelowOrEqual, DestinationLabel = xNoJump }; break; case ConditionalTestEnum.LessThanOrEqualTo: new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.LessThan, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.GreaterThan, DestinationLabel = xNoJump }; new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.BelowOrEqual, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; break; case ConditionalTestEnum.LessThan: new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.LessThan, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.GreaterThan, DestinationLabel = xNoJump }; new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Below, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; break; // from here all unsigned case ConditionalTestEnum.AboveOrEqual: new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Above, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Below, DestinationLabel = xNoJump }; break; case ConditionalTestEnum.Above: new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Above, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.BelowOrEqual, DestinationLabel = xNoJump }; break; case ConditionalTestEnum.BelowOrEqual: new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Above, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Below, DestinationLabel = xNoJump }; new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Above, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; break; case ConditionalTestEnum.Below: new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Above, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Below, DestinationLabel = xNoJump }; new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX }; new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.AboveOrEqual, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; break; default: throw new Exception("Unknown OpCode for conditional branch in 64-bit."); } new Label(xNoJump); //} } } else { //if (xStackContent.IsFloat) //{ // throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Simple comparison of floating point numbers is not yet supported!"); //} //else //{ // todo: improve code clarity if (xStackContent.Size > 4) { throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Simple branches are not yet supported on operands > 4 bytes!"); } new CPU.Pop { DestinationReg = CPU.Registers.EAX }; if (xTestOp == ConditionalTestEnum.Zero) { new CPU.Compare { DestinationReg = CPU.Registers.EAX, SourceValue = 0 }; new CPU.ConditionalJump { Condition = ConditionalTestEnum.Equal, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; } else if (xTestOp == ConditionalTestEnum.NotZero) { new CPU.Compare { DestinationReg = CPU.Registers.EAX, SourceValue = 0 }; new CPU.ConditionalJump { Condition = ConditionalTestEnum.NotEqual, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) }; } else { throw new NotSupportedException("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Situation not supported yet! (In the Simple Comparison)"); } } //} } } }
using System; using System.IO; using System.Text; using ChainUtils.BouncyCastle.Math; using ChainUtils.BouncyCastle.Utilities; namespace ChainUtils.BouncyCastle.Asn1 { public class DerObjectIdentifier : Asn1Object { private readonly string identifier; private byte[] body = null; /** * return an Oid from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerObjectIdentifier GetInstance(object obj) { if (obj == null || obj is DerObjectIdentifier) return (DerObjectIdentifier) obj; if (obj is byte[]) return FromOctetString((byte[])obj); throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj"); } /** * return an object Identifier from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerObjectIdentifier GetInstance( Asn1TaggedObject obj, bool explicitly) { return GetInstance(obj.GetObject()); } public DerObjectIdentifier( string identifier) { if (identifier == null) throw new ArgumentNullException("identifier"); if (!IsValidIdentifier(identifier)) throw new FormatException("string " + identifier + " not an OID"); this.identifier = identifier; } internal DerObjectIdentifier(DerObjectIdentifier oid, string branchID) { if (!IsValidBranchID(branchID, 0)) throw new ArgumentException("string " + branchID + " not a valid OID branch", "branchID"); identifier = oid.Id + "." + branchID; } // TODO Change to ID? public string Id { get { return identifier; } } public virtual DerObjectIdentifier Branch(string branchID) { return new DerObjectIdentifier(this, branchID); } /** * Return true if this oid is an extension of the passed in branch, stem. * @param stem the arc or branch that is a possible parent. * @return true if the branch is on the passed in stem, false otherwise. */ public virtual bool On(DerObjectIdentifier stem) { string id = Id, stemId = stem.Id; return id.Length > stemId.Length && id[stemId.Length] == '.' && id.StartsWith(stemId); } internal DerObjectIdentifier(byte[] bytes) { identifier = MakeOidStringFromBytes(bytes); body = Arrays.Clone(bytes); } private void WriteField( Stream outputStream, long fieldValue) { var result = new byte[9]; var pos = 8; result[pos] = (byte)(fieldValue & 0x7f); while (fieldValue >= (1L << 7)) { fieldValue >>= 7; result[--pos] = (byte)((fieldValue & 0x7f) | 0x80); } outputStream.Write(result, pos, 9 - pos); } private void WriteField( Stream outputStream, BigInteger fieldValue) { var byteCount = (fieldValue.BitLength + 6) / 7; if (byteCount == 0) { outputStream.WriteByte(0); } else { var tmpValue = fieldValue; var tmp = new byte[byteCount]; for (var i = byteCount-1; i >= 0; i--) { tmp[i] = (byte) ((tmpValue.IntValue & 0x7f) | 0x80); tmpValue = tmpValue.ShiftRight(7); } tmp[byteCount-1] &= 0x7f; outputStream.Write(tmp, 0, tmp.Length); } } private void DoOutput(MemoryStream bOut) { var tok = new OidTokenizer(identifier); var token = tok.NextToken(); var first = int.Parse(token) * 40; token = tok.NextToken(); if (token.Length <= 18) { WriteField(bOut, first + Int64.Parse(token)); } else { WriteField(bOut, new BigInteger(token).Add(BigInteger.ValueOf(first))); } while (tok.HasMoreTokens) { token = tok.NextToken(); if (token.Length <= 18) { WriteField(bOut, Int64.Parse(token)); } else { WriteField(bOut, new BigInteger(token)); } } } internal byte[] GetBody() { lock (this) { if (body == null) { var bOut = new MemoryStream(); DoOutput(bOut); body = bOut.ToArray(); } } return body; } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.ObjectIdentifier, GetBody()); } protected override int Asn1GetHashCode() { return identifier.GetHashCode(); } protected override bool Asn1Equals( Asn1Object asn1Object) { var other = asn1Object as DerObjectIdentifier; if (other == null) return false; return identifier.Equals(other.identifier); } public override string ToString() { return identifier; } private static bool IsValidBranchID( String branchID, int start) { var periodAllowed = false; var pos = branchID.Length; while (--pos >= start) { var ch = branchID[pos]; // TODO Leading zeroes? if ('0' <= ch && ch <= '9') { periodAllowed = true; continue; } if (ch == '.') { if (!periodAllowed) return false; periodAllowed = false; continue; } return false; } return periodAllowed; } private static bool IsValidIdentifier(string identifier) { if (identifier.Length < 3 || identifier[1] != '.') return false; var first = identifier[0]; if (first < '0' || first > '2') return false; return IsValidBranchID(identifier, 2); } private const long LONG_LIMIT = (long.MaxValue >> 7) - 0x7f; private static string MakeOidStringFromBytes( byte[] bytes) { var objId = new StringBuilder(); long value = 0; BigInteger bigValue = null; var first = true; for (var i = 0; i != bytes.Length; i++) { int b = bytes[i]; if (value <= LONG_LIMIT) { value += (b & 0x7f); if ((b & 0x80) == 0) // end of number reached { if (first) { if (value < 40) { objId.Append('0'); } else if (value < 80) { objId.Append('1'); value -= 40; } else { objId.Append('2'); value -= 80; } first = false; } objId.Append('.'); objId.Append(value); value = 0; } else { value <<= 7; } } else { if (bigValue == null) { bigValue = BigInteger.ValueOf(value); } bigValue = bigValue.Or(BigInteger.ValueOf(b & 0x7f)); if ((b & 0x80) == 0) { if (first) { objId.Append('2'); bigValue = bigValue.Subtract(BigInteger.ValueOf(80)); first = false; } objId.Append('.'); objId.Append(bigValue); bigValue = null; value = 0; } else { bigValue = bigValue.ShiftLeft(7); } } } return objId.ToString(); } private static readonly DerObjectIdentifier[] cache = new DerObjectIdentifier[1024]; internal static DerObjectIdentifier FromOctetString(byte[] enc) { var hashCode = Arrays.GetHashCode(enc); var first = hashCode & 1023; lock (cache) { var entry = cache[first]; if (entry != null && Arrays.AreEqual(enc, entry.GetBody())) { return entry; } return cache[first] = new DerObjectIdentifier(enc); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public class AIMoveInfo{ public List<Tile> tileList=new List<Tile>(); public List<UnitTB> targetList=new List<UnitTB>(); } public enum _AIStance{ Passive, //AI faction will not do anything until it detect hostile Trigger, //AI faction will not do anything until it's being spoted Active //AI faction will actively move around seeking out target } public class AIManager : MonoBehaviour { public static AIManager instance; public _AIStance aIStance; public static _AIStance GetAIStance(){ if(instance==null) return _AIStance.Passive; return instance.aIStance; } //set to true when a unit is asked to move //when unit completes it's move, the unit instance will call function to set this back to false //for _AIRoutine only public bool unitInAction=false; public static void ClearUnitInActionFlag(){ instance.unitInAction=false; } // Use this for initialization void Awake () { instance=this; } //just for testing, IEnumerator SkippedAIRoutine(){ yield return new WaitForSeconds(1f); GameControlTB.OnEndTurn(); } public static void AIRoutine(int factionID){ instance.StartCoroutine(instance._AIRoutine(factionID)); //for testing //Debug.Log("all AI routine"); //instance.StartCoroutine(instance.SkippedAIRoutine(null)); } public static void MoveUnit(UnitTB unit){ //Debug.Log("move "+unit); instance.StartCoroutine(instance._AIRoutineSingleUnit(unit)); //for testing //Debug.Log("single AI routine"); //instance.StartCoroutine(instance.SkippedAIRoutine(null)); } //AI routine to move a single unit IEnumerator _AIRoutineSingleUnit(UnitTB unit){ while(GameControlTB.IsActionInProgress()) yield return null; yield return new WaitForSeconds(1f); unitInAction=true; instance.StartCoroutine(instance._MoveUnit(unit)); //wait a frame for the unit to start moving, set the inAction flag, etc.. yield return null; while(unit.InAction() || GameControlTB.IsActionInProgress() || unitInAction){ yield return null; } GameControlTB.OnEndTurn(); } //AI routine for faction based turn mode, AI will move all available unit for the faction //called by UnitControl in OnNextTurn IEnumerator _AIRoutine(int factionID){ while(GameControlTB.IsActionInProgress()) yield return null; yield return new WaitForSeconds(1f); Faction faction=UnitControl.GetFactionInTurn(factionID); List<UnitTB> allUnit=faction.allUnitList; int counter=0; if(GameControlTB.GetMoveOrder()==_MoveOrder.Free){ int count=allUnit.Count; //create a list (1, 2, 3..... ) to the size of the unit, this is for unit shuffling List<int> IDList=new List<int>(); for(int i=0; i<count; i++) IDList.Add(i); for(int i=0; i<count; i++){ //randomly select a unit to move int rand=UnityEngine.Random.Range(0, IDList.Count); /* //if(counter%2==0) rand=0; //else rand=IDList.Count-1; string label="rand: "+rand+" ("+IDList.Count+")"; for(int nn=0; nn<IDList.Count; nn++){ label+=" "+IDList[nn]; } Debug.Log(label); */ int ID=IDList[rand]; UnitTB unit=allUnit[ID]; //remove the unit from allUnit list so that it wont be selected again IDList.RemoveAt(rand); counter+=1; //move the unit unitInAction=true; StartCoroutine(_MoveUnit(unit)); //wait a frame for the unit to start moving, set the inAction flag, etc.. yield return null; //wait while the unit is in action (making its move) //and while the game event is in progress (counter attack, death effect/animation, etc.) //and while the unit localUnitInactionFlag hasn't been cleared while(unit.InAction() || GameControlTB.IsActionInProgress() || unitInAction){ yield return null; } //for counter-attack enabled, in case the unit is destroyed in after being countered if(unit.IsDestroyed()){ //label=""; for(int n=rand; n<IDList.Count; n++){ if(IDList[n]>=ID){ //label+=" "+IDList[n]; IDList[n]-=1; } } //Debug.Log("unit destroyed "+label); } /* label="rand: "+rand+" ("+IDList.Count+")"; for(int nn=0; nn<IDList.Count; nn++){ label+=" "+IDList[nn]; } Debug.Log(label); */ if(GameControlTB.battleEnded) yield break; } } else if(GameControlTB.GetMoveOrder()==_MoveOrder.FixedRandom || GameControlTB.GetMoveOrder()==_MoveOrder.FixedStatsBased){ for(int i=0; i<allUnit.Count; i++){ UnitTB unit=allUnit[i]; //move the unit unitInAction=true; StartCoroutine(_MoveUnit(unit)); yield return null; //wait while the unit is in action (making its move) //and while the game event is in progress (counter attack, death effect/animation, etc.) while(unit.InAction() || GameControlTB.IsActionInProgress() || unitInAction){ yield return null; } if(GameControlTB.battleEnded) yield break; } } faction.allUnitMoved=true; yield return new WaitForSeconds(0.5f); EndTurn(); } public void EndTurn(){ if(!GameControlTB.battleEnded) GameControlTB.OnEndTurn(); } //LOS and fog of war is not considered //that has already been built into various function called on UnitControl and GridManager public Tile Analyse(UnitTB unit){ //analyse current tile first List<UnitTB> currentHostilesList; if(!GameControlTB.EnableFogOfWar()) currentHostilesList=UnitControl.GetHostileInRangeFromTile(unit.occupiedTile, unit); else currentHostilesList=UnitControl.GetVisibleHostileInRangeFromTile(unit.occupiedTile, unit); unit.occupiedTile.AIHostileList=currentHostilesList; if(GameControlTB.EnableCover()){ if(currentHostilesList.Count!=0){ int count=0; for(int n=0; n<currentHostilesList.Count; n++){ if((int)unit.occupiedTile.GetCoverType(currentHostilesList[n].thisT.position)>0){ count+=1; } } if(count==currentHostilesList.Count) return unit.occupiedTile; } } else{ if(currentHostilesList.Count!=0) return unit.occupiedTile; } //get all possible target List<UnitTB> allHostiles=new List<UnitTB>(); if(GameControlTB.EnableFogOfWar()) allHostiles=UnitControl.GetAllHostileWithinFactionSight(unit.factionID); else allHostiles=UnitControl.GetAllHostile(unit.factionID); //if there's no potential target at all if(allHostiles.Count==0){ if(unit.attackerList.Count>0){ return unit.attackerList[0].unit.occupiedTile; } else{ //if stance is set to passive, stay put if(aIStance==_AIStance.Passive) return unit.occupiedTile; } } //get all walkable List<Tile> walkableTiles=GridManager.GetWalkableTilesWithinRange(unit.occupiedTile, unit.GetMoveRange()); //get tiles with target in range from the walkables List<Tile> offensiveTiles=new List<Tile>(); for(int i=0; i<walkableTiles.Count; i++){ walkableTiles[i].AIHostileList=new List<UnitTB>(); bool visibleOnly=GameControlTB.EnableFogOfWar(); List<UnitTB> hostilesList=UnitControl.GetHostileInRangeFromTile(walkableTiles[i], unit, visibleOnly); walkableTiles[i].AIHostileList=hostilesList; if(hostilesList.Count>0){ offensiveTiles.Add(walkableTiles[i]); } } //cross search any walkables with any tiles with target List<Tile> offensiveWalkableTiles=new List<Tile>(); for(int i=0; i<offensiveTiles.Count; i++){ if(walkableTiles.Contains(offensiveTiles[i])){ offensiveWalkableTiles.Add(offensiveTiles[i]); } } //if the game uses cover if(GameControlTB.EnableCover()){ //calculating general direction of enemy, to know which direction to take cover from //Vector3 hostileAveragePos=Vector3.zero; //for(int i=0; i<allHostiles.Count; i++){ // hostileAveragePos+=allHostiles[i].occupiedTile.pos; //} //hostileAveragePos/=allHostiles.Count; //get offensive tile with cover from all hostile List<Tile> offensiveTilesWithAllCover=new List<Tile>(); List<Tile> offensiveTilesWithPartialCover=new List<Tile>(); for(int i=0; i<offensiveWalkableTiles.Count; i++){ Tile tile=offensiveWalkableTiles[i]; int count=0; for(int n=0; n<tile.AIHostileList.Count; n++){ if((int)tile.GetCoverType(tile.AIHostileList[n].thisT.position)>0){ count+=1; } } if(count==tile.AIHostileList.Count) offensiveTilesWithAllCover.Add(tile); else if(count>0) offensiveTilesWithPartialCover.Add(tile); } if(offensiveTilesWithAllCover.Count>0){ int rand=UnityEngine.Random.Range(0, offensiveTilesWithAllCover.Count); return(offensiveTilesWithAllCover[rand]); } else if(offensiveTilesWithAllCover.Count>0){ int rand=UnityEngine.Random.Range(0, offensiveTilesWithPartialCover.Count); return(offensiveTilesWithPartialCover[rand]); } //get any tile with possible cover from the walkables List<Tile> walkableTilesWithCover=new List<Tile>(); for(int i=0; i<walkableTiles.Count; i++){ if(walkableTiles[i].GotCover()){ walkableTilesWithCover.Add(walkableTiles[i]); } } //cross-search offense and walkable tile with cover //to get tiles which offer cover and the unit can attack from List<Tile> offensiveTilesWithCover=new List<Tile>(); for(int i=0; i<offensiveTiles.Count; i++){ if(walkableTilesWithCover.Contains(offensiveTiles[i])){ offensiveTilesWithCover.Add(offensiveTiles[i]); } } //if there's any tile that offer cover and target at the same time, use the tile if(offensiveTilesWithCover.Count>0){ int rand=UnityEngine.Random.Range(0, offensiveTilesWithCover.Count); return offensiveTilesWithCover[rand]; } //if there's no tile that offer cover and target at the same time //just use any walkable tile with cover instead if(walkableTilesWithCover.Count>0){ int rand=UnityEngine.Random.Range(0, walkableTilesWithCover.Count); return walkableTilesWithCover[rand]; } } //if cover system is not used, or there's no cover in any walkable tiles //if there's walkable that the unit can attack from, uses that if(offensiveWalkableTiles.Count>0){ int rand=UnityEngine.Random.Range(0, offensiveWalkableTiles.Count); return offensiveWalkableTiles[rand]; } //check if the unit has been attacked, if yes, retaliate UnitTB attacker=unit.GetNearestAttacker(); if(attacker!=null) return attacker.occupiedTile; //no hostile unit within range if(aIStance==_AIStance.Active || aIStance==_AIStance.Trigger){ //no hostile detected at all, just move randomly if(allHostiles.Count==0){ if(walkableTiles.Count>0){ int rand=UnityEngine.Random.Range(0, walkableTiles.Count); return walkableTiles[rand]; } } //get the nearest target and move towards it else{ int nearest=999999999; int nearestID=0; for(int i=0; i<allHostiles.Count; i++){ int dist=GridManager.Distance(unit.occupiedTile, allHostiles[i].occupiedTile); if(dist<nearest){ nearest=dist; nearestID=i; } } return allHostiles[nearestID].occupiedTile; } } return null; } //for LOS checking along a path, //return true if the unit will be seen by hostile faction if the unit moves along the path, false if otherwise bool CheckEncounterOnPath(Tile srcTile, Tile targetTile){ List<Tile> path=AStar.SearchWalkableTile(srcTile, targetTile); List<UnitTB> allPlayerUnit=UnitControl.GetAllUnitsOfFaction(0); bool visibleToPlayer=false; for(int i=0; i<path.Count; i++){ Tile tile=path[0]; for(int j=0; j<allPlayerUnit.Count; j++){ if(GridManager.IsInLOS(tile, allPlayerUnit[j].occupiedTile)){ int dist=GridManager.Distance(tile, allPlayerUnit[j].occupiedTile); if(dist<=allPlayerUnit[j].GetSight()){ visibleToPlayer=true; break; } } } } return visibleToPlayer; } //execute move/attack for a single unit IEnumerator _MoveUnit(UnitTB unit){ //make sure no event is taking place while(GameControlTB.IsActionInProgress()) yield return null; if(!unit.IsStunned()){ /* DateTime timeS; DateTime timeE; TimeSpan timeSpan; timeS=System.DateTime.Now; */ Tile destinationTile=null; if(aIStance==_AIStance.Trigger){ if(unit.triggered) destinationTile=Analyse(unit); } else{ destinationTile=Analyse(unit); } //if there's target in current tile, just attack it if(destinationTile==unit.occupiedTile){ if(destinationTile.AIHostileList.Count!=0){ //unit.Attack(destinationTile.AIHostileList[UnityEngine.Random.Range(0, destinationTile.AIHostileList.Count)]); //unit will simply attack instead of move if(!unit.MoveAttack(unit.occupiedTile)) NoActionForUnit(unit); } else{ unitInAction=false; } yield break; } if(destinationTile!=null){ if(GameControlTB.EnableFogOfWar()){ bool visibleToPlayer=CheckEncounterOnPath(unit.occupiedTile, destinationTile); if(visibleToPlayer){ if(!unit.MoveAttack(destinationTile)) NoActionForUnit(unit); } else{ if(destinationTile.AIHostileList.Count==0){ MoveUnitToTileInstant(unit, destinationTile); unit.CompleteAllAction(); } else{ if(!unit.MoveAttack(destinationTile)) NoActionForUnit(unit); } } } else{ if(!unit.MoveAttack(destinationTile)) NoActionForUnit(unit); } } else{ //no action is available for the unit, simply registred it as moved NoActionForUnit(unit); } /* timeE=System.DateTime.Now; timeSpan=timeE-timeS; Debug.Log( "Time:"+timeSpan.TotalMilliseconds); */ } else{ NoActionForUnit(unit); } } void NoActionForUnit(UnitTB unit){ UnitControl.MoveUnit(unit); unit.CompleteAllAction(); unitInAction=false; } void MoveUnitToTileInstant(UnitTB unit, Tile tile){ List<Tile> path=AStar.SearchToOccupiedTile(unit.occupiedTile, tile); //make sure the target tile is not occupied if(path.Count>0){ if(path[path.Count-1].unit!=null) path.RemoveAt(path.Count-1); } //make sure the unit doesnt move beyond the allowed range while(path.Count>Mathf.Max(1, unit.GetMoveRange()+1)){ path.RemoveAt(path.Count-1); } if(path.Count>0){ Tile destinationTile=path[path.Count-1]; unit.occupiedTile.unit=null; unit.occupiedTile=destinationTile; destinationTile.unit=unit; unit.thisT.position=destinationTile.pos; } unitInAction=false; } } //for fog of war mode, return a list of hostile unit which is visible by all unit //public List<UnitTB> allVisibleHostile=new List<UnitTB>(); //~ public void GetVisibleHostileUnit(int factionID){ //allVisibleHostile=UnitControl.GetAllHostileUnitWithinFactionSight(factionID); //~ } //~ public UnitTB GetNearestUnitFromFactionVisible(UnitTB srcUnit){ //~ UnitTB targetUnit=null; //~ float currentNearest=Mathf.Infinity; //~ for(int i=0; i<allVisibleHostile.Count; i++){ //~ float dist=Vector3.Distance(srcUnit.occupiedTile.pos, allVisibleHostile[i].occupiedTile.pos); //~ if(dist<currentNearest){ //~ targetUnit=allVisibleHostile[i]; //~ currentNearest=dist; //~ } //~ } //~ return targetUnit; //~ } //~ public UnitTB GetNearestUnitFromUnitVisible(UnitTB srcUnit, List<UnitTB> visibleList){ //~ UnitTB targetUnit=null; //~ float currentNearest=Mathf.Infinity; //~ for(int i=0; i<visibleList.Count; i++){ //~ float dist=Vector3.Distance(srcUnit.occupiedTile.pos, visibleList[i].occupiedTile.pos); //~ if(dist<currentNearest){ //~ targetUnit=visibleList[i]; //~ currentNearest=dist; //~ } //~ } //~ return targetUnit; //~ }
// // KeyPairPersistenceTest.cs: Unit tests for keypair persistence // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2004-2005 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. // using NUnit.Framework; using System; using System.IO; using System.Security.Cryptography; using Mono.Security.Cryptography; namespace MonoTests.Mono.Security.Cryptography { [TestFixture] public class KeyPairPersistenceTest { [Test] [ExpectedException (typeof (ArgumentNullException))] public void Constructor_Null () { KeyPairPersistence kpp = new KeyPairPersistence (null); } private void Compare (KeyPairPersistence saved, KeyPairPersistence loaded) { // Note: there is an additional Environement.NewLine // at the end of the loaded string - that's why we do // not use AssertEquals (for strings) Assert.IsTrue (loaded.Filename.StartsWith (saved.Filename), "Filename"); Assert.IsTrue (loaded.KeyValue.StartsWith (saved.KeyValue), "KeyValue"); Assert.IsTrue (loaded.Parameters.KeyContainerName.StartsWith (saved.Parameters.KeyContainerName), "Parameters.KeyContainerName"); Assert.AreEqual (saved.Parameters.KeyNumber, loaded.Parameters.KeyNumber, "Parameters.KeyNumber"); Assert.IsTrue (loaded.Parameters.ProviderName.StartsWith (saved.Parameters.ProviderName), "Parameters.ProviderName"); Assert.AreEqual (saved.Parameters.ProviderType, loaded.Parameters.ProviderType, "Parameters.ProviderType"); } [Test] public void CspType () { try { CspParameters cp = new CspParameters (-1); KeyPairPersistence kpp = new KeyPairPersistence (cp, "<keypair/>"); kpp.Save (); Assert.IsTrue (File.Exists (kpp.Filename), "Save-Exists"); // we didn't supply a name so we can't load it back kpp.Remove (); Assert.IsFalse (File.Exists (kpp.Filename), "Remove-!Exists"); } catch (UnauthorizedAccessException) { Assert.Ignore ("Access denied to key containers files."); } } [Test] public void CspTypeProvider () { try { CspParameters cp = new CspParameters (-2, "Provider"); KeyPairPersistence kpp = new KeyPairPersistence (cp, "<keypair/>"); kpp.Save (); Assert.IsTrue (File.Exists (kpp.Filename), "Save-Exists"); // we didn't supply a name so we can't load it back kpp.Remove (); Assert.IsFalse (File.Exists (kpp.Filename), "Remove-!Exists"); } catch (UnauthorizedAccessException) { Assert.Ignore ("Access denied to key containers files."); } } [Test] public void CspTypeProviderContainer () { try { CspParameters cp = new CspParameters (-3, "Provider", "Container"); KeyPairPersistence kpp = new KeyPairPersistence (cp, "<keypair/>"); kpp.Save (); Assert.IsTrue (File.Exists (kpp.Filename), "Save-Exists"); KeyPairPersistence kpp2 = new KeyPairPersistence (cp); Assert.IsTrue (kpp2.Load (), "Load"); Compare (kpp, kpp2); kpp.Remove (); Assert.IsFalse (File.Exists (kpp.Filename), "Remove-!Exists"); } catch (UnauthorizedAccessException) { Assert.Ignore ("Access denied to key containers files."); } } [Test] public void CspTypeProviderContainerKeyNumber () { try { CspParameters cp = new CspParameters (-4, "Provider", "Container"); cp.KeyNumber = 0; KeyPairPersistence kpp = new KeyPairPersistence (cp, "<keypair/>"); kpp.Save (); Assert.IsTrue (File.Exists (kpp.Filename), "Save-Exists"); KeyPairPersistence kpp2 = new KeyPairPersistence (cp); Assert.IsTrue (kpp2.Load (), "Load"); Compare (kpp, kpp2); kpp.Remove (); Assert.IsFalse (File.Exists (kpp.Filename), "Remove-!Exists"); } catch (UnauthorizedAccessException) { Assert.Ignore ("Access denied to key containers files."); } } [Test] public void CspFlagsDefault () { try { CspParameters cp = new CspParameters (-5, "Provider", "Container"); cp.Flags = CspProviderFlags.UseDefaultKeyContainer; KeyPairPersistence kpp = new KeyPairPersistence (cp, "<keypair/>"); kpp.Save (); Assert.IsTrue (File.Exists (kpp.Filename), "Save-Exists"); KeyPairPersistence kpp2 = new KeyPairPersistence (cp); Assert.IsTrue (kpp2.Load (), "Load"); Compare (kpp, kpp2); kpp.Remove (); Assert.IsFalse (File.Exists (kpp.Filename), "Remove-!Exists"); } catch (UnauthorizedAccessException) { Assert.Ignore ("Access denied to key containers files."); } } [Test] public void CspFlagsMachine () { try { CspParameters cp = new CspParameters (-6, "Provider", "Container"); cp.Flags = CspProviderFlags.UseMachineKeyStore; KeyPairPersistence kpp = new KeyPairPersistence (cp, "<keypair/>"); kpp.Save (); Assert.IsTrue (File.Exists (kpp.Filename), "Save-Exists"); KeyPairPersistence kpp2 = new KeyPairPersistence (cp); Assert.IsTrue (kpp2.Load (), "Load"); Compare (kpp, kpp2); kpp.Remove (); Assert.IsFalse (File.Exists (kpp.Filename), "Remove-!Exists"); } catch (CryptographicException ce) { // not everyone can write to the machine store if (!(ce.InnerException is UnauthorizedAccessException)) throw; Assert.Ignore ("Access denied to key containers files."); } catch (UnauthorizedAccessException) { Assert.Ignore ("Access denied to key containers files."); } } [Test] public void CspFlagsDefaultMachine () { try { CspParameters cp = new CspParameters (-7, "Provider", "Container"); cp.Flags = CspProviderFlags.UseDefaultKeyContainer | CspProviderFlags.UseMachineKeyStore; KeyPairPersistence kpp = new KeyPairPersistence (cp, "<keypair/>"); kpp.Save (); Assert.IsTrue (File.Exists (kpp.Filename), "Save-Exists"); KeyPairPersistence kpp2 = new KeyPairPersistence (cp); Assert.IsTrue (kpp2.Load (), "Load"); Compare (kpp, kpp2); kpp.Remove (); Assert.IsFalse (File.Exists (kpp.Filename), "Remove-!Exists"); } catch (CryptographicException ce) { // not everyone can write to the machine store if (!(ce.InnerException is UnauthorizedAccessException)) throw; Assert.Ignore ("Access denied to key containers files."); } catch (UnauthorizedAccessException) { Assert.Ignore ("Access denied to key containers files."); } } [Test] public void CspNoChangesPermitted () { try { CspParameters cp = new CspParameters (-8, "Provider", "Container"); cp.KeyNumber = 0; cp.Flags = CspProviderFlags.UseMachineKeyStore; KeyPairPersistence kpp = new KeyPairPersistence (cp); CspParameters copy = kpp.Parameters; copy.Flags = CspProviderFlags.UseDefaultKeyContainer; copy.KeyContainerName = "NewContainerName"; copy.KeyNumber = 1; copy.ProviderName = "NewProviderName"; copy.ProviderType = -9; Assert.IsTrue (cp.Flags != copy.Flags, "Flags"); Assert.IsTrue (cp.KeyContainerName != copy.KeyContainerName, "KeyContainerName"); Assert.IsTrue (cp.KeyNumber != copy.KeyNumber, "KeyNumber"); Assert.IsTrue (cp.ProviderName != copy.ProviderName, "ProviderName"); Assert.IsTrue (cp.ProviderType != copy.ProviderType, "ProviderType"); } catch (UnauthorizedAccessException) { Assert.Ignore ("Access denied to key containers files."); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Diagnostics; using OpenLiveWriter.CoreServices.Layout; using OpenLiveWriter.CoreServices.Marketization; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; using OpenLiveWriter.PostEditor.ContentSources.Common; using System.Collections.Generic; namespace OpenLiveWriter.PostEditor.ContentSources.Common { /// <summary> /// Summary description for VideoBrowserForm. /// </summary> public class MediaInsertForm : ApplicationDialog, IRtlAware { private IContainer components = null; //top tab control private LightweightControlContainerControl mainTabControl; private TabLightweightControl tabs; private List<MediaTab> _sources; private MediaTab activeSource = null; private Button buttonInsert; private LinkLabel copyrightLinkLabel; private Button btnCancel; public const string EventName = "Inserting Media"; public MediaInsertForm(List<MediaTab> sources, string blogID, int selectedTab, MediaSmartContent content, string title, bool showCopyright) : this(sources, blogID, selectedTab, content, title, showCopyright, false) { } public MediaInsertForm(List<MediaTab> sources, string blogID, int selectedTab, MediaSmartContent content, string title, bool showCopyright, bool isEdit) { // // Required for Windows Form Designer support // InitializeComponent(); _sources = sources; //set strings btnCancel.Text = Res.Get(StringId.CancelButton); if (!isEdit) buttonInsert.Text = Res.Get(StringId.InsertButtonText); else buttonInsert.Text = Res.Get(StringId.OKButtonText); Text = title; if (!showCopyright || !MarketizationOptions.IsFeatureEnabled(MarketizationOptions.Feature.VideoCopyright)) { copyrightLinkLabel.Visible = false; } else { copyrightLinkLabel.Font = Res.GetFont(FontSize.Small, FontStyle.Regular); copyrightLinkLabel.Text = Res.Get(StringId.Plugin_Video_Copyright_Notice); string link = MarketizationOptions.GetFeatureParameter(MarketizationOptions.Feature.VideoCopyright, "Glink"); if (link == null || link == String.Empty) copyrightLinkLabel.LinkArea = new LinkArea(0,0); else copyrightLinkLabel.LinkClicked += copyrightLinkLabel_LinkClicked; } copyrightLinkLabel.LinkColor = SystemColors.HotTrack; // // tabs // tabs = new TabLightweightControl(); tabs.VirtualBounds = new Rectangle(0, 5, 450, 485); tabs.LightweightControlContainerControl = mainTabControl; tabs.DrawSideAndBottomTabPageBorders = false; tabs.ColorizeBorder = false; int i = 0; foreach (MediaTab mediaSource in _sources) { mediaSource.MediaSelected += videoSource_MediaSelected; TabPageControl tab = mediaSource; tab.TabStop = false; Controls.Add(tab); tabs.SetTab(i++, tab); } // initial appearance of editor if ( !DesignMode ) Icon = ApplicationEnvironment.ProductIcon ; tabs.VirtualLocation = new Point(0, 5); tabs.VirtualSize = Size; Width = 510; Height = 570; foreach (MediaTab videoSource in _sources) videoSource.Init(content, blogID); SetActiveTab(selectedTab); tabs.SelectedTabNumber = selectedTab; tabs.SelectedTabNumberChanged += new EventHandler(tabs_SelectedTabNumberChanged); Closing += new CancelEventHandler(MediaInsertForm_Closing); } void MediaInsertForm_Closing(object sender, CancelEventArgs e) { if (DialogResult == DialogResult.OK) { if (activeSource.ValidateSelection()) { ApplicationPerformance.StartEvent(EventName); DialogResult = DialogResult.OK; } else { DialogResult = DialogResult.Abort; e.Cancel = true; } } } void videoSource_MediaSelected(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } protected override void OnLayout(LayoutEventArgs levent) { base.OnLayout (levent); if (tabs != null && mainTabControl != null) tabs.VirtualSize = new Size(mainTabControl.Width, mainTabControl.Height - 5); } protected override void OnLoad(EventArgs e) { base.OnLoad (e); LayoutHelper.FixupOKCancel(buttonInsert, btnCancel); } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { tabs.CheckForTabSwitch(keyData); return base.ProcessCmdKey(ref msg, keyData); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { copyrightLinkLabel.LinkClicked -= copyrightLinkLabel_LinkClicked; foreach (MediaTab videoSource in _sources) videoSource.MediaSelected -= videoSource_MediaSelected; tabs.SelectedTabNumberChanged -= tabs_SelectedTabNumberChanged; Closing -= MediaInsertForm_Closing; if(components != null) { components.Dispose(); } foreach(MediaTab source in _sources) { source.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.mainTabControl = new OpenLiveWriter.Controls.LightweightControlContainerControl(); this.buttonInsert = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.copyrightLinkLabel = new System.Windows.Forms.LinkLabel(); ((System.ComponentModel.ISupportInitialize)(this.mainTabControl)).BeginInit(); this.SuspendLayout(); // // mainTabControl // this.mainTabControl.AllowDragDropAutoScroll = false; this.mainTabControl.AllPaintingInWmPaint = true; this.mainTabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.mainTabControl.BackColor = System.Drawing.SystemColors.Control; this.mainTabControl.Location = new System.Drawing.Point(0, 0); this.mainTabControl.Name = "mainTabControl"; this.mainTabControl.Size = new System.Drawing.Size(450, 480); this.mainTabControl.TabIndex = 14; // // buttonInsert // this.buttonInsert.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonInsert.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonInsert.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonInsert.Location = new System.Drawing.Point(282, 486); this.buttonInsert.Name = "buttonInsert"; this.buttonInsert.Size = new System.Drawing.Size(75, 23); this.buttonInsert.TabIndex = 20; this.buttonInsert.Text = "Insert"; // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnCancel.Location = new System.Drawing.Point(363, 486); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 21; this.btnCancel.Text = "Cancel"; // // copyrightLinkLabel // this.copyrightLinkLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.copyrightLinkLabel.AutoSize = true; this.copyrightLinkLabel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.copyrightLinkLabel.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.copyrightLinkLabel.LinkColor = System.Drawing.SystemColors.HotTrack; this.copyrightLinkLabel.Location = new System.Drawing.Point(7, 493); this.copyrightLinkLabel.Name = "copyrightLinkLabel"; this.copyrightLinkLabel.Size = new System.Drawing.Size(140, 15); this.copyrightLinkLabel.TabIndex = 19; this.copyrightLinkLabel.TabStop = true; this.copyrightLinkLabel.Text = "Please Respect Copyright"; // // MediaInsertForm // this.AcceptButton = this.buttonInsert; this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(450, 520); this.Controls.Add(this.copyrightLinkLabel); this.Controls.Add(this.btnCancel); this.Controls.Add(this.buttonInsert); this.Controls.Add(this.mainTabControl); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "MediaInsertForm"; this.Text = "Insert Video"; ((System.ComponentModel.ISupportInitialize)(this.mainTabControl)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private void SetActiveTab(int num) { activeSource = _sources[num]; activeSource.TabSelected(); mainTabControl.InitFocusManager(true); mainTabControl.AddFocusableControls(tabs.GetAccessibleControls()); mainTabControl.AddFocusableControls(activeSource.GetAccessibleControls()); mainTabControl.AddFocusableControl(copyrightLinkLabel); mainTabControl.AddFocusableControl(buttonInsert); mainTabControl.AddFocusableControl(btnCancel); } private void tabs_SelectedTabNumberChanged(object sender, EventArgs e) { int tabChosen = ((TabLightweightControl)sender).SelectedTabNumber; tabs.Update(); SetActiveTab(tabChosen); } public void SaveContent(MediaSmartContent content) { activeSource.SaveContent(content); } private void copyrightLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { string link = MarketizationOptions.GetFeatureParameter(MarketizationOptions.Feature.VideoCopyright, "Glink"); if (link != null && link != String.Empty) { try { ShellHelper.LaunchUrl( link ); } catch( Exception ex ) { Trace.Fail( "Unexpected exception navigating to copyright page: " + link + ", " + ex.ToString() ) ; } } } void IRtlAware.Layout() { BidiHelper.RtlLayoutFixup(this, true, true, Controls); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace applicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// NetworkInterfacesOperations operations. /// </summary> public partial interface INetworkInterfacesOperations { /// <summary> /// Deletes the specified network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about the specified network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NetworkInterface>> GetWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network interface /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NetworkInterface>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all network interfaces in a subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all network interfaces in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NetworkInterface>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route tables applied to a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EffectiveRouteListResult>> GetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all network security groups applied to a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> ListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about all network interfaces in a virtual machine /// in a virtual machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetVMNetworkInterfacesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all network interfaces in a virtual machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetNetworkInterfacesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the specified network interface in a virtual machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NetworkInterface>> GetVirtualMachineScaleSetNetworkInterfaceWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network interface /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NetworkInterface>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route tables applied to a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EffectiveRouteListResult>> BeginGetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all network security groups applied to a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> BeginListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all network interfaces in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all network interfaces in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NetworkInterface>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about all network interfaces in a virtual machine /// in a virtual machine scale set. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetVMNetworkInterfacesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all network interfaces in a virtual machine scale set. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetNetworkInterfacesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
//------------------------------------------------------------------------------ // <copyright file="_KerberosClient.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System.Collections; using System.Net.Sockets; using System.Security.Authentication.ExtendedProtection; using System.Security.Permissions; using System.Globalization; internal class KerberosClient : ISessionAuthenticationModule { internal const string AuthType = "Kerberos"; internal static string Signature = AuthType.ToLower(CultureInfo.InvariantCulture); internal static int SignatureSize = Signature.Length; public Authorization Authenticate(string challenge, WebRequest webRequest, ICredentials credentials) { GlobalLog.Print("KerberosClient::Authenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " calling DoAuthenticate()"); return DoAuthenticate(challenge, webRequest, credentials, false); } private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate) { GlobalLog.Print("KerberosClient::DoAuthenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " preAuthenticate:" + preAuthenticate.ToString()); GlobalLog.Assert(credentials != null, "KerberosClient::DoAuthenticate()|credentials == null"); if (credentials == null) { return null; } HttpWebRequest httpWebRequest = webRequest as HttpWebRequest; GlobalLog.Assert(httpWebRequest != null, "KerberosClient::DoAuthenticate()|httpWebRequest == null"); GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "KerberosClient::DoAuthenticate()|httpWebRequest.ChallengedUri == null"); NTAuthentication authSession = null; string incoming = null; if (!preAuthenticate) { int index = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature); if (index < 0) { return null; } int blobBegin = index + SignatureSize; // // there may be multiple challenges. If the next character after the // package name is not a comma then it is challenge data // if (challenge.Length > blobBegin && challenge[blobBegin] != ',') { ++blobBegin; } else { index = -1; } if (index >= 0 && challenge.Length > blobBegin) { // Strip other modules information in case of multiple challenges // i.e do not take ", NTLM" as part of the following Negotiate blob // Negotiate TlRMTVNTUAACAAAADgAOADgAAAA1wo ... MAbwBmAHQALgBjAG8AbQAAAAAA,NTLM index = challenge.IndexOf(',', blobBegin); if (index != -1) incoming = challenge.Substring(blobBegin, index - blobBegin); else incoming = challenge.Substring(blobBegin); } authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this); GlobalLog.Print("KerberosClient::DoAuthenticate() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession)); } if (authSession==null) { NetworkCredential NC = credentials.GetCredential(httpWebRequest.ChallengedUri, Signature); GlobalLog.Print("KerberosClient::DoAuthenticate() GetCredential() returns:" + ValidationHelper.ToString(NC)); if (NC == null || (!(NC is SystemNetworkCredential) && NC.InternalGetUserName().Length == 0)) { return null; } ICredentialPolicy policy = AuthenticationManager.CredentialPolicy; if (policy != null && !policy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, NC, this)) return null; SpnToken spn = httpWebRequest.CurrentAuthenticationState.GetComputeSpn(httpWebRequest); GlobalLog.Print("KerberosClient::Authenticate() ChallengedSpn:" + ValidationHelper.ToString(spn)); ChannelBinding binding = null; if (httpWebRequest.CurrentAuthenticationState.TransportContext != null) { binding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint); } authSession = new NTAuthentication( AuthType, NC, spn, httpWebRequest, binding); GlobalLog.Print("KerberosClient::DoAuthenticate() setting SecurityContext for:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " to authSession:" + ValidationHelper.HashString(authSession)); httpWebRequest.CurrentAuthenticationState.SetSecurityContext(authSession, this); } string clientResponse = authSession.GetOutgoingBlob(incoming); if (clientResponse==null) { return null; } return new Authorization(AuthType + " " + clientResponse, authSession.IsCompleted, string.Empty, authSession.IsMutualAuthFlag); } public bool CanPreAuthenticate { get { return true; } } public Authorization PreAuthenticate(WebRequest webRequest, ICredentials credentials) { GlobalLog.Print("KerberosClient::PreAuthenticate() webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " calling DoAuthenticate()"); return DoAuthenticate(null, webRequest, credentials, true); } public string AuthenticationType { get { return AuthType; } } // // called when getting the final blob on the 200 OK from the server // public bool Update(string challenge, WebRequest webRequest) { GlobalLog.Print("KerberosClient::Update(): " + challenge); HttpWebRequest httpWebRequest = webRequest as HttpWebRequest; GlobalLog.Assert(httpWebRequest != null, "KerberosClient::Update()|httpWebRequest == null"); GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "KerberosClient::Update()|httpWebRequest.ChallengedUri == null"); // // try to retrieve the state of the ongoing handshake // NTAuthentication authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this); GlobalLog.Print("KerberosClient::Update() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession)); if (authSession==null) { GlobalLog.Print("KerberosClient::Update() null session returning true"); return true; } GlobalLog.Print("KerberosClient::Update() authSession.IsCompleted:" + authSession.IsCompleted.ToString()); if (httpWebRequest.CurrentAuthenticationState.StatusCodeMatch==httpWebRequest.ResponseStatusCode) { GlobalLog.Print("KerberosClient::Update() still handshaking (based on status code) returning false"); return false; } // // the whole point here is to to close the Security Context (this will complete the authentication handshake // with server authentication for schemese that support it such as Kerberos) // int index = challenge==null ? -1 : AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature); if (index>=0) { int blobBegin = index + SignatureSize; string incoming = null; // // there may be multiple challenges. If the next character after the // package name is not a comma then it is challenge data // if (challenge.Length > blobBegin && challenge[blobBegin] != ',') { ++blobBegin; } else { index = -1; } if (index >= 0 && challenge.Length > blobBegin) { incoming = challenge.Substring(blobBegin); } GlobalLog.Print("KerberosClient::Update() closing security context using last incoming blob:[" + ValidationHelper.ToString(incoming) + "]"); string clientResponse = authSession.GetOutgoingBlob(incoming); httpWebRequest.CurrentAuthenticationState.Authorization.MutuallyAuthenticated = authSession.IsMutualAuthFlag; GlobalLog.Print("KerberosClient::Update() GetOutgoingBlob() returns clientResponse:[" + ValidationHelper.ToString(clientResponse) + "] IsCompleted:" + authSession.IsCompleted.ToString()); } // Extract the CBT we used and cache it for future requests that want to do preauth httpWebRequest.ServicePoint.SetCachedChannelBinding(httpWebRequest.ChallengedUri, authSession.ChannelBinding); GlobalLog.Print("KerberosClient::Update() session removed and ConnectionGroup released returning true"); ClearSession(httpWebRequest); return true; } public void ClearSession(WebRequest webRequest) { HttpWebRequest httpWebRequest = webRequest as HttpWebRequest; GlobalLog.Assert(httpWebRequest != null, "KerberosClient::ClearSession()|httpWebRequest == null"); httpWebRequest.CurrentAuthenticationState.ClearSession(); } public bool CanUseDefaultCredentials { get { return true; } } }; // class KerberosClient } // namespace System.Net
namespace PTWin { partial class ResourceEdit { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Windows.Forms.Label FirstNameLabel; System.Windows.Forms.Label IdLabel; System.Windows.Forms.Label LastNameLabel; this.CloseButton = new System.Windows.Forms.Button(); this.ApplyButton = new System.Windows.Forms.Button(); this.Cancel_Button = new System.Windows.Forms.Button(); this.OKButton = new System.Windows.Forms.Button(); this.GroupBox1 = new System.Windows.Forms.GroupBox(); this.AssignmentsDataGridView = new System.Windows.Forms.DataGridView(); this.projectIdDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.projectNameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewLinkColumn(); this.assignedDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Role = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.RoleListBindingSource = new System.Windows.Forms.BindingSource(this.components); this.AssignmentsBindingSource = new System.Windows.Forms.BindingSource(this.components); this.ResourceBindingSource = new System.Windows.Forms.BindingSource(this.components); this.UnassignButton = new System.Windows.Forms.Button(); this.AssignButton = new System.Windows.Forms.Button(); this.FirstNameTextBox = new System.Windows.Forms.TextBox(); this.IdLabel1 = new System.Windows.Forms.Label(); this.LastNameTextBox = new System.Windows.Forms.TextBox(); this.ErrorProvider1 = new System.Windows.Forms.ErrorProvider(this.components); this.ReadWriteAuthorization1 = new Csla.Windows.ReadWriteAuthorization(this.components); this.bindingSourceRefresh1 = new Csla.Windows.BindingSourceRefresh(this.components); FirstNameLabel = new System.Windows.Forms.Label(); IdLabel = new System.Windows.Forms.Label(); LastNameLabel = new System.Windows.Forms.Label(); this.GroupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.AssignmentsDataGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.RoleListBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.AssignmentsBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ResourceBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ErrorProvider1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingSourceRefresh1)).BeginInit(); this.SuspendLayout(); // // FirstNameLabel // this.ReadWriteAuthorization1.SetApplyAuthorization(FirstNameLabel, false); FirstNameLabel.AutoSize = true; FirstNameLabel.Location = new System.Drawing.Point(13, 42); FirstNameLabel.Name = "FirstNameLabel"; FirstNameLabel.Size = new System.Drawing.Size(60, 13); FirstNameLabel.TabIndex = 2; FirstNameLabel.Text = "First Name:"; // // IdLabel // this.ReadWriteAuthorization1.SetApplyAuthorization(IdLabel, false); IdLabel.AutoSize = true; IdLabel.Location = new System.Drawing.Point(13, 13); IdLabel.Name = "IdLabel"; IdLabel.Size = new System.Drawing.Size(19, 13); IdLabel.TabIndex = 0; IdLabel.Text = "Id:"; // // LastNameLabel // this.ReadWriteAuthorization1.SetApplyAuthorization(LastNameLabel, false); LastNameLabel.AutoSize = true; LastNameLabel.Location = new System.Drawing.Point(13, 68); LastNameLabel.Name = "LastNameLabel"; LastNameLabel.Size = new System.Drawing.Size(61, 13); LastNameLabel.TabIndex = 4; LastNameLabel.Text = "Last Name:"; // // CloseButton // this.CloseButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.CloseButton, false); this.CloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.CloseButton.Location = new System.Drawing.Point(501, 100); this.CloseButton.Name = "CloseButton"; this.CloseButton.Size = new System.Drawing.Size(75, 23); this.CloseButton.TabIndex = 10; this.CloseButton.Text = "Close"; this.CloseButton.UseVisualStyleBackColor = true; this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click); // // ApplyButton // this.ApplyButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.ApplyButton, false); this.ApplyButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.ApplyButton.Location = new System.Drawing.Point(501, 42); this.ApplyButton.Name = "ApplyButton"; this.ApplyButton.Size = new System.Drawing.Size(75, 23); this.ApplyButton.TabIndex = 8; this.ApplyButton.Text = "Apply"; this.ApplyButton.UseVisualStyleBackColor = true; this.ApplyButton.Click += new System.EventHandler(this.ApplyButton_Click); // // Cancel_Button // this.Cancel_Button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.Cancel_Button, false); this.Cancel_Button.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.Cancel_Button.Location = new System.Drawing.Point(501, 71); this.Cancel_Button.Name = "Cancel_Button"; this.Cancel_Button.Size = new System.Drawing.Size(75, 23); this.Cancel_Button.TabIndex = 9; this.Cancel_Button.Text = "Cancel"; this.Cancel_Button.UseVisualStyleBackColor = true; this.Cancel_Button.Click += new System.EventHandler(this.Cancel_Button_Click); // // OKButton // this.OKButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.OKButton, false); this.OKButton.Location = new System.Drawing.Point(501, 13); this.OKButton.Name = "OKButton"; this.OKButton.Size = new System.Drawing.Size(75, 23); this.OKButton.TabIndex = 7; this.OKButton.Text = "OK"; this.OKButton.UseVisualStyleBackColor = true; this.OKButton.Click += new System.EventHandler(this.OKButton_Click); // // GroupBox1 // this.GroupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.GroupBox1, false); this.GroupBox1.Controls.Add(this.AssignmentsDataGridView); this.GroupBox1.Controls.Add(this.UnassignButton); this.GroupBox1.Controls.Add(this.AssignButton); this.GroupBox1.Location = new System.Drawing.Point(16, 91); this.GroupBox1.Name = "GroupBox1"; this.GroupBox1.Size = new System.Drawing.Size(449, 310); this.GroupBox1.TabIndex = 6; this.GroupBox1.TabStop = false; this.GroupBox1.Text = "Assigned projects"; // // AssignmentsDataGridView // this.AssignmentsDataGridView.AllowUserToAddRows = false; this.AssignmentsDataGridView.AllowUserToDeleteRows = false; this.AssignmentsDataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.AssignmentsDataGridView, false); this.AssignmentsDataGridView.AutoGenerateColumns = false; this.AssignmentsDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; this.AssignmentsDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.projectIdDataGridViewTextBoxColumn, this.projectNameDataGridViewTextBoxColumn, this.assignedDataGridViewTextBoxColumn, this.Role}); this.AssignmentsDataGridView.DataSource = this.AssignmentsBindingSource; this.AssignmentsDataGridView.Location = new System.Drawing.Point(6, 19); this.AssignmentsDataGridView.MultiSelect = false; this.AssignmentsDataGridView.Name = "AssignmentsDataGridView"; this.AssignmentsDataGridView.RowHeadersVisible = false; this.AssignmentsDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.AssignmentsDataGridView.Size = new System.Drawing.Size(356, 285); this.AssignmentsDataGridView.TabIndex = 0; this.AssignmentsDataGridView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.AssignmentsDataGridView_CellContentClick); // // projectIdDataGridViewTextBoxColumn // this.projectIdDataGridViewTextBoxColumn.DataPropertyName = "ProjectId"; this.projectIdDataGridViewTextBoxColumn.HeaderText = "ProjectId"; this.projectIdDataGridViewTextBoxColumn.Name = "projectIdDataGridViewTextBoxColumn"; this.projectIdDataGridViewTextBoxColumn.ReadOnly = true; this.projectIdDataGridViewTextBoxColumn.Visible = false; this.projectIdDataGridViewTextBoxColumn.Width = 74; // // projectNameDataGridViewTextBoxColumn // this.projectNameDataGridViewTextBoxColumn.DataPropertyName = "ProjectName"; this.projectNameDataGridViewTextBoxColumn.HeaderText = "Project Name"; this.projectNameDataGridViewTextBoxColumn.Name = "projectNameDataGridViewTextBoxColumn"; this.projectNameDataGridViewTextBoxColumn.ReadOnly = true; this.projectNameDataGridViewTextBoxColumn.Resizable = System.Windows.Forms.DataGridViewTriState.True; this.projectNameDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic; this.projectNameDataGridViewTextBoxColumn.Width = 96; // // assignedDataGridViewTextBoxColumn // this.assignedDataGridViewTextBoxColumn.DataPropertyName = "Assigned"; this.assignedDataGridViewTextBoxColumn.HeaderText = "Assigned"; this.assignedDataGridViewTextBoxColumn.Name = "assignedDataGridViewTextBoxColumn"; this.assignedDataGridViewTextBoxColumn.ReadOnly = true; this.assignedDataGridViewTextBoxColumn.Width = 75; // // Role // this.Role.DataPropertyName = "Role"; this.Role.DataSource = this.RoleListBindingSource; this.Role.DisplayMember = "Value"; this.Role.HeaderText = "Role"; this.Role.Name = "Role"; this.Role.ValueMember = "Key"; this.Role.Width = 35; // // RoleListBindingSource // this.RoleListBindingSource.DataSource = typeof(ProjectTracker.Library.RoleList); this.bindingSourceRefresh1.SetReadValuesOnChange(this.RoleListBindingSource, false); // // AssignmentsBindingSource // this.AssignmentsBindingSource.DataMember = "Assignments"; this.AssignmentsBindingSource.DataSource = this.ResourceBindingSource; this.bindingSourceRefresh1.SetReadValuesOnChange(this.AssignmentsBindingSource, false); // // ResourceBindingSource // this.ResourceBindingSource.DataSource = typeof(ProjectTracker.Library.ResourceEdit); this.bindingSourceRefresh1.SetReadValuesOnChange(this.ResourceBindingSource, true); // // UnassignButton // this.UnassignButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.UnassignButton, false); this.UnassignButton.Location = new System.Drawing.Point(368, 48); this.UnassignButton.Name = "UnassignButton"; this.UnassignButton.Size = new System.Drawing.Size(75, 23); this.UnassignButton.TabIndex = 2; this.UnassignButton.Text = "Unassign"; this.UnassignButton.UseVisualStyleBackColor = true; this.UnassignButton.Click += new System.EventHandler(this.UnassignButton_Click); // // AssignButton // this.AssignButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.AssignButton, false); this.AssignButton.Location = new System.Drawing.Point(368, 19); this.AssignButton.Name = "AssignButton"; this.AssignButton.Size = new System.Drawing.Size(75, 23); this.AssignButton.TabIndex = 1; this.AssignButton.Text = "Assign"; this.AssignButton.UseVisualStyleBackColor = true; this.AssignButton.Click += new System.EventHandler(this.AssignButton_Click); // // FirstNameTextBox // this.FirstNameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.FirstNameTextBox, true); this.FirstNameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ResourceBindingSource, "FirstName", true)); this.FirstNameTextBox.Location = new System.Drawing.Point(80, 39); this.FirstNameTextBox.Name = "FirstNameTextBox"; this.FirstNameTextBox.Size = new System.Drawing.Size(385, 20); this.FirstNameTextBox.TabIndex = 3; // // IdLabel1 // this.IdLabel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.IdLabel1, true); this.IdLabel1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ResourceBindingSource, "Id", true)); this.IdLabel1.Location = new System.Drawing.Point(80, 13); this.IdLabel1.Name = "IdLabel1"; this.IdLabel1.Size = new System.Drawing.Size(385, 23); this.IdLabel1.TabIndex = 1; // // LastNameTextBox // this.LastNameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.LastNameTextBox, true); this.LastNameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ResourceBindingSource, "LastName", true)); this.LastNameTextBox.Location = new System.Drawing.Point(80, 65); this.LastNameTextBox.Name = "LastNameTextBox"; this.LastNameTextBox.Size = new System.Drawing.Size(385, 20); this.LastNameTextBox.TabIndex = 5; // // ErrorProvider1 // this.ErrorProvider1.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink; this.ErrorProvider1.ContainerControl = this; this.ErrorProvider1.DataSource = this.ResourceBindingSource; // // bindingSourceRefresh1 // this.bindingSourceRefresh1.Host = this; // // ResourceEdit // this.ReadWriteAuthorization1.SetApplyAuthorization(this, false); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.CloseButton); this.Controls.Add(this.ApplyButton); this.Controls.Add(this.Cancel_Button); this.Controls.Add(this.OKButton); this.Controls.Add(this.GroupBox1); this.Controls.Add(FirstNameLabel); this.Controls.Add(this.FirstNameTextBox); this.Controls.Add(IdLabel); this.Controls.Add(this.IdLabel1); this.Controls.Add(LastNameLabel); this.Controls.Add(this.LastNameTextBox); this.Name = "ResourceEdit"; this.Size = new System.Drawing.Size(588, 415); this.Load += new System.EventHandler(this.ResourceEdit_Load); this.GroupBox1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.AssignmentsDataGridView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.RoleListBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.AssignmentsBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ResourceBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ErrorProvider1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingSourceRefresh1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion internal System.Windows.Forms.Button CloseButton; internal System.Windows.Forms.Button ApplyButton; internal System.Windows.Forms.Button Cancel_Button; internal System.Windows.Forms.Button OKButton; internal System.Windows.Forms.GroupBox GroupBox1; internal System.Windows.Forms.Button UnassignButton; internal System.Windows.Forms.Button AssignButton; internal System.Windows.Forms.TextBox FirstNameTextBox; internal System.Windows.Forms.Label IdLabel1; internal System.Windows.Forms.TextBox LastNameTextBox; internal Csla.Windows.ReadWriteAuthorization ReadWriteAuthorization1; internal System.Windows.Forms.DataGridView AssignmentsDataGridView; internal System.Windows.Forms.BindingSource RoleListBindingSource; internal System.Windows.Forms.BindingSource AssignmentsBindingSource; internal System.Windows.Forms.BindingSource ResourceBindingSource; internal System.Windows.Forms.ErrorProvider ErrorProvider1; private System.Windows.Forms.DataGridViewTextBoxColumn projectIdDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewLinkColumn projectNameDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn assignedDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewComboBoxColumn Role; private Csla.Windows.BindingSourceRefresh bindingSourceRefresh1; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/type/date.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Type { /// <summary>Holder for reflection information generated from google/type/date.proto</summary> public static partial class DateReflection { #region Descriptor /// <summary>File descriptor for google/type/date.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static DateReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChZnb29nbGUvdHlwZS9kYXRlLnByb3RvEgtnb29nbGUudHlwZSIwCgREYXRl", "EgwKBHllYXIYASABKAUSDQoFbW9udGgYAiABKAUSCwoDZGF5GAMgASgFQl0K", "D2NvbS5nb29nbGUudHlwZUIJRGF0ZVByb3RvUAFaNGdvb2dsZS5nb2xhbmcu", "b3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvdHlwZS9kYXRlO2RhdGX4AQGiAgNH", "VFBiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.Date), global::Google.Type.Date.Parser, new[]{ "Year", "Month", "Day" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Represents a whole calendar date, e.g. date of birth. The time of day and /// time zone are either specified elsewhere or are not significant. The date /// is relative to the Proleptic Gregorian Calendar. The day may be 0 to /// represent a year and month where the day is not significant, e.g. credit card /// expiration date. The year may be 0 to represent a month and day independent /// of year, e.g. anniversary date. Related types are [google.type.TimeOfDay][google.type.TimeOfDay] /// and `google.protobuf.Timestamp`. /// </summary> public sealed partial class Date : pb::IMessage<Date> { private static readonly pb::MessageParser<Date> _parser = new pb::MessageParser<Date>(() => new Date()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Date> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Type.DateReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Date() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Date(Date other) : this() { year_ = other.year_; month_ = other.month_; day_ = other.day_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Date Clone() { return new Date(this); } /// <summary>Field number for the "year" field.</summary> public const int YearFieldNumber = 1; private int year_; /// <summary> /// Year of date. Must be from 1 to 9999, or 0 if specifying a date without /// a year. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Year { get { return year_; } set { year_ = value; } } /// <summary>Field number for the "month" field.</summary> public const int MonthFieldNumber = 2; private int month_; /// <summary> /// Month of year. Must be from 1 to 12. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Month { get { return month_; } set { month_ = value; } } /// <summary>Field number for the "day" field.</summary> public const int DayFieldNumber = 3; private int day_; /// <summary> /// Day of month. Must be from 1 to 31 and valid for the year and month, or 0 /// if specifying a year/month where the day is not significant. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Day { get { return day_; } set { day_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Date); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Date other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Year != other.Year) return false; if (Month != other.Month) return false; if (Day != other.Day) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Year != 0) hash ^= Year.GetHashCode(); if (Month != 0) hash ^= Month.GetHashCode(); if (Day != 0) hash ^= Day.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Year != 0) { output.WriteRawTag(8); output.WriteInt32(Year); } if (Month != 0) { output.WriteRawTag(16); output.WriteInt32(Month); } if (Day != 0) { output.WriteRawTag(24); output.WriteInt32(Day); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Year != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Year); } if (Month != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Month); } if (Day != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Day); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Date other) { if (other == null) { return; } if (other.Year != 0) { Year = other.Year; } if (other.Month != 0) { Month = other.Month; } if (other.Day != 0) { Day = other.Day; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Year = input.ReadInt32(); break; } case 16: { Month = input.ReadInt32(); break; } case 24: { Day = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Text; using DCalcCore.Remoting; namespace DCalc.Communication { /// <summary> /// Provides a remote server definition. /// </summary> public class RemoteServer : IServer { #region Private Fields private String m_ServerName; private String m_ServerHost; private Int32 m_ServerPort; private String m_ServerKey; private Boolean m_Enabled; private IRemoteGateClient m_Client; private ServerStatus m_Status; private ConnectionType m_ConnectionType; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="RemoteServer"/> class. /// </summary> /// <param name="serverName">Name of the server.</param> /// <param name="serverHost">The server host.</param> /// <param name="serverPort">The server port.</param> /// <param name="securityKey">The security key.</param> /// <param name="isEnabled">if set to <c>true</c> [is enabled].</param> public RemoteServer(String serverName, String serverHost, Int32 serverPort, String securityKey, ConnectionType connectionType, Boolean isEnabled) { if (serverName == null) throw new ArgumentNullException("serverName"); if (serverHost == null) throw new ArgumentNullException("serverHost"); if (serverHost.Length == 0) throw new ArgumentException("serverHost"); if (serverPort < 0 || serverPort > UInt16.MaxValue) throw new ArgumentException("serverPort"); m_ServerName = serverName; m_ServerHost = serverHost; m_ServerPort = serverPort; m_Enabled = isEnabled; m_ServerKey = securityKey; m_ConnectionType = connectionType; } #endregion #region RemoteServer Public Properties /// <summary> /// Gets or sets the host. /// </summary> /// <value>The host.</value> public String Host { get { return m_ServerHost; } set { if (value == null) throw new ArgumentNullException("value"); if (value.Length == 0) throw new ArgumentException("value"); m_ServerHost = value; } } /// <summary> /// Gets or sets the port. /// </summary> /// <value>The port.</value> public Int32 Port { get { return m_ServerPort; } set { if (value < 0 || value > UInt16.MaxValue) throw new ArgumentException("value"); m_ServerPort = value; } } /// <summary> /// Gets or sets the security key. /// </summary> /// <value>The security key.</value> public String SecurityKey { get { return m_ServerKey; } set { m_ServerKey = value; } } /// <summary> /// Gets or sets the client. /// </summary> /// <value>The client.</value> public IRemoteGateClient Client { get { return m_Client; } set { if (value == null) throw new ArgumentNullException("value"); m_Client = value; } } /// <summary> /// Gets or sets the type of the connection. /// </summary> /// <value>The type of the connection.</value> public ConnectionType ConnectionType { get { return m_ConnectionType; } set { m_ConnectionType = value; } } #endregion #region IServer Members /// <summary> /// Gets the signature. /// </summary> /// <value>The signature.</value> public String Signature { get { return String.Format("{0} [{1}:{2}]", m_ServerName, m_ServerHost, m_ServerPort); } } /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public String Name { get { return m_ServerName; } set { if (value == null) throw new ArgumentNullException("value"); m_ServerName = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="IServer"/> is enabled. /// </summary> /// <value><c>true</c> if enabled; otherwise, <c>false</c>.</value> public Boolean Enabled { get { return m_Enabled; } set { m_Enabled = value; } } /// <summary> /// Gets or sets the status. /// </summary> /// <value>The status.</value> public ServerStatus Status { get { return m_Status; } set { m_Status = value; } } #endregion #region ICloneable Members /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> public Object Clone() { RemoteServer copy = new RemoteServer(m_ServerName, m_ServerHost, m_ServerPort, m_ServerKey, m_ConnectionType, m_Enabled); return copy; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using CuSer.Areas.HelpPage.ModelDescriptions; using CuSer.Areas.HelpPage.Models; namespace CuSer.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) 2016 AgileObjects Ltd // Licensed under the MIT license. See LICENSE file in the ReadableExpressions directory for more information. namespace LinkIt.ReadableExpressions { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Extensions; using static System.Environment; internal static class StringExtensions { private static readonly char[] _terminatingCharacters = { ';', ':', ',' }; public static bool IsTerminated(this string codeLine) { if (!codeLine.EndsWith('}')) { return codeLine.EndsWithAny(_terminatingCharacters) || codeLine.IsComment(); } var lastNewLine = codeLine.LastIndexOf(NewLine, StringComparison.Ordinal); if (lastNewLine == -1) { return false; } var codeLines = codeLine.TrimStart().SplitToLines(); while (codeLines[0].StartsWith(IndentSpaces, StringComparison.Ordinal)) { for (var i = 0; i < codeLines.Length; i++) { if (codeLines[i].Length != 0) { codeLines[i] = codeLines[i].Substring(IndentSpaces.Length); } } } var lastNonIndentedCodeLine = codeLines .Last(line => line.IsNonIndentedCodeLine()); if ((lastNonIndentedCodeLine == "catch") || lastNonIndentedCodeLine.StartsWith("if ", StringComparison.Ordinal) || lastNonIndentedCodeLine.StartsWith("while ", StringComparison.Ordinal) || (lastNonIndentedCodeLine == "finally") || lastNonIndentedCodeLine.StartsWith("else if ", StringComparison.Ordinal) || (lastNonIndentedCodeLine == "else") || lastNonIndentedCodeLine.StartsWith("switch ", StringComparison.Ordinal)) { return true; } return false; } public static bool IsNonIndentedCodeLine(this string line) { return line.IsNotIndented() && !line.StartsWith('{') && !line.StartsWith('}'); } public static string Unterminated(this string codeLine) { return codeLine.EndsWith(';') ? codeLine.Substring(0, codeLine.Length - 1) : codeLine; } private static readonly string[] _newLines = { NewLine }; public static string[] SplitToLines(this string line, StringSplitOptions splitOptions = StringSplitOptions.None) { return line.Split(_newLines, splitOptions); } private const string IndentSpaces = " "; public static bool IsNotIndented(this string line) { return (line.Length > 0) && !line.StartsWith(IndentSpaces, StringComparison.Ordinal); } public static string Indented(this string line) { if (string.IsNullOrEmpty(line)) { return string.Empty; } if (line.IsMultiLine()) { return string.Join( NewLine, line.SplitToLines().Select(l => l.Indented())); } return IndentSpaces + line; } public static bool IsMultiLine(this string value) => (value != NewLine) && value.Contains(NewLine); private const string UnindentPlaceholder = "*unindent*"; public static string Unindented(this string line) { return UnindentPlaceholder + line; } public static string WithoutUnindents(this string code) { if (code.Contains(UnindentPlaceholder)) { return code .Replace(IndentSpaces + UnindentPlaceholder, null) .Replace(UnindentPlaceholder, null); } return code; } public static string WithSurroundingParentheses(this string value) { if (!value.HasSurroundingParentheses()) { return "(" + value + ")"; } var openParenthesesCount = 0; for (var i = 1; i < value.Length - 1; ++i) { switch (value[i]) { case '(': ++openParenthesesCount; continue; case ')': --openParenthesesCount; if (openParenthesesCount < 0) { return "(" + value + ")"; } continue; } } return value; } public static string WithoutSurroundingParentheses(this string value, Expression expression) { if (string.IsNullOrEmpty(value) || KeepSurroundingParentheses(expression)) { return value; } return value.HasSurroundingParentheses() ? value.Substring(1, value.Length - 2) : value; } private static bool HasSurroundingParentheses(this string value) { return value.StartsWith('(') && value.EndsWith(')'); } private static bool KeepSurroundingParentheses(Expression expression) { switch (expression.NodeType) { case ExpressionType.Conditional: case ExpressionType.Lambda: return true; case ExpressionType.Call: var parentExpression = expression.GetParentOrNull(); while (parentExpression != null) { expression = parentExpression; parentExpression = expression.GetParentOrNull(); } switch (expression.NodeType) { case ExpressionType.Add: case ExpressionType.Convert: case ExpressionType.Multiply: case ExpressionType.Subtract: return true; } return false; case ExpressionType.Invoke: var invocation = (InvocationExpression)expression; return invocation.Expression.NodeType == ExpressionType.Lambda; } return false; } public static bool StartsWithNewLine(this string value) { return value.StartsWith(NewLine, StringComparison.Ordinal); } public static bool StartsWith(this string value, char character) { return (value.Length > 0) && (value[0] == character); } public static bool EndsWith(this string value, char character) { return (value != string.Empty) && value.EndsWithNoEmptyCheck(character); } private static bool EndsWithAny(this string value, IEnumerable<char> characters) { return (value != string.Empty) && characters.Any(value.EndsWithNoEmptyCheck); } private static bool EndsWithNoEmptyCheck(this string value, char character) { return value[value.Length - 1] == character; } private const string CommentString = "// "; public static string AsComment(this string text) { return CommentString + text .Trim() .Replace(NewLine, NewLine + CommentString); } public static bool IsComment(this string codeLine) { return codeLine.TrimStart().StartsWith(CommentString, StringComparison.Ordinal); } public static string ToStringConcatenation(this IEnumerable<Expression> strings, TranslationContext context) { return string.Join(" + ", strings.Select((str => GetStringValue(str, context)))); } private static string GetStringValue(Expression value, TranslationContext context) { if (value.NodeType == ExpressionType.Call) { var methodCall = (MethodCallExpression)value; if ((methodCall.Method.Name == "ToString") && !methodCall.Arguments.Any()) { value = methodCall.GetSubject(); } } var stringValue = context.Translate(value); switch (value.NodeType) { case ExpressionType.Conditional: stringValue = stringValue.WithSurroundingParentheses(); break; } return stringValue; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace LZ4Sharp { /// <summary> /// Class for compressing a byte array into an LZ4 byte array. /// </summary> public unsafe class LZ4Compressor32 : ILZ4Compressor { //************************************** // Tuning parameters //************************************** // COMPRESSIONLEVEL : // Increasing this value improves compression ratio // Lowering this value reduces memory usage // Reduced memory usage typically improves speed, due to cache effect (ex : L1 32KB for Intel, L1 64KB for AMD) // Memory usage formula : N->2^(N+2) Bytes (examples : 12 -> 16KB ; 17 -> 512KB) const int COMPRESSIONLEVEL = 12; // NOTCOMPRESSIBLE_CONFIRMATION : // Decreasing this value will make the algorithm skip faster data segments considered "incompressible" // This may decrease compression ratio dramatically, but will be faster on incompressible data // Increasing this value will make the algorithm search more before declaring a segment "incompressible" // This could improve compression a bit, but will be slower on incompressible data // The default value (6) is recommended // 2 is the minimum value. const int NOTCOMPRESSIBLE_CONFIRMATION = 6; //************************************** // Constants //************************************** const int HASH_LOG = COMPRESSIONLEVEL; const int MAXD_LOG = 16; const int MAX_DISTANCE = ((1 << MAXD_LOG) - 1); const int MINMATCH = 4; const int MFLIMIT = (LZ4Util.COPYLENGTH + MINMATCH); const int MINLENGTH = (MFLIMIT + 1); const uint LZ4_64KLIMIT = ((1U << 16) + (MFLIMIT - 1)); const int HASHLOG64K = (HASH_LOG + 1); const int HASHTABLESIZE = (1 << HASH_LOG); const int HASH_MASK = (HASHTABLESIZE - 1); const int LASTLITERALS = 5; const int SKIPSTRENGTH = (NOTCOMPRESSIBLE_CONFIRMATION > 2 ? NOTCOMPRESSIBLE_CONFIRMATION : 2); const int SIZE_OF_LONG_TIMES_TWO_SHIFT = 4; const int STEPSIZE = 4; static byte[] DeBruijnBytePos = new byte[32] { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; //************************************** // Macros //************************************** byte[] m_HashTable; public LZ4Compressor32() { m_HashTable = new byte[HASHTABLESIZE * IntPtr.Size]; if (m_HashTable.Length % 16 != 0) throw new Exception("Hash table size must be divisible by 16"); } public byte[] Compress(byte[] source) { int maxCompressedSize = CalculateMaxCompressedLength(source.Length); byte[] dst = new byte[maxCompressedSize]; int length = Compress(source, dst); byte[] dest = new byte[length]; Buffer.BlockCopy(dst, 0, dest, 0, length); return dest; } /// <summary> /// Calculate the max compressed byte[] size given the size of the uncompressed byte[] /// </summary> /// <param name="uncompressedLength">Length of the uncompressed data</param> /// <returns>The maximum required size in bytes of the compressed data</returns> public int CalculateMaxCompressedLength(int uncompressedLength) { return uncompressedLength + (uncompressedLength / 255) + 16; } /// <summary> /// Compress source into dest returning compressed length /// </summary> /// <param name="source">uncompressed data</param> /// <param name="dest">array into which source will be compressed</param> /// <returns>compressed length</returns> public int Compress(byte[] source, byte[] dest) { fixed (byte* s = source) fixed (byte* d = dest) { if (source.Length < (int)LZ4_64KLIMIT) return Compress64K(s, d, source.Length, dest.Length); return Compress(s, d, source.Length, dest.Length); } } /// <summary> /// Compress source into dest returning compressed length /// </summary> /// <param name="source">uncompressed data</param> /// <param name="srcOffset">offset in source array where reading will start</param> /// <param name="count">count of bytes in source array to compress</param> /// <param name="dest">array into which source will be compressed</param> /// <param name="dstOffset">start index in dest array where writing will start</param> /// <returns>compressed length</returns> public int Compress(byte[] source, int srcOffset, int count, byte[] dest, int dstOffset) { fixed (byte* s = &source[srcOffset]) fixed (byte* d = &dest[dstOffset]) { if (source.Length < (int)LZ4_64KLIMIT) return Compress64K(s, d, count, dest.Length - dstOffset); return Compress(s, d, count, dest.Length - dstOffset); } } int Compress(byte* source, byte* dest, int isize, int maxOutputSize) { fixed (byte* hashTablePtr = m_HashTable) fixed (byte* deBruijnBytePos = DeBruijnBytePos) { Clear(hashTablePtr, sizeof(byte*) * HASHTABLESIZE); byte** hashTable = (byte**)hashTablePtr; byte* ip = (byte*)source; int basePtr = 0; ; byte* anchor = ip; byte* iend = ip + isize; byte* mflimit = iend - MFLIMIT; byte* matchlimit = (iend - LASTLITERALS); byte* oend = dest + maxOutputSize; byte* op = (byte*)dest; int len, length; const int skipStrength = SKIPSTRENGTH; uint forwardH; // Init if (isize < MINLENGTH) goto _last_literals; // First Byte hashTable[(((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG))] = ip - basePtr; ip++; forwardH = (((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG)); // Main Loop for (; ; ) { uint findMatchAttempts = (1U << skipStrength) + 3; byte* forwardIp = ip; byte* r; byte* token; // Find a match do { uint h = forwardH; uint step = findMatchAttempts++ >> skipStrength; ip = forwardIp; forwardIp = ip + step; if (forwardIp > mflimit) { goto _last_literals; } // LZ4_HASH_VALUE forwardH = (((*(uint*)forwardIp) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG)); r = hashTable[h] + basePtr; hashTable[h] = ip - basePtr; } while ((r < ip - MAX_DISTANCE) || (*(uint*)r != *(uint*)ip)); // Catch up while ((ip > anchor) && (r > (byte*)source) && (ip[-1] == r[-1])) { ip--; r--; } // Encode Literal Length length = (int)(ip - anchor); token = op++; if (length >= (int)LZ4Util.RUN_MASK) { *token = (byte)(LZ4Util.RUN_MASK << LZ4Util.ML_BITS); len = (int)(length - LZ4Util.RUN_MASK); for (; len > 254; len -= 255) *op++ = 255; *op++ = (byte)len; } else *token = (byte)(length << LZ4Util.ML_BITS); //Copy Literals { byte* e = (op) + length; do { *(uint*)op = *(uint*)anchor; op += 4; anchor += 4; ; *(uint*)op = *(uint*)anchor; op += 4; anchor += 4; ; } while (op < e);; op = e; }; _next_match: // Encode Offset *(ushort*)op = (ushort)(ip - r); op += 2; // Start Counting ip += MINMATCH; r += MINMATCH; // MinMatch verified anchor = ip; // while (*(uint *)r == *(uint *)ip) // { // ip+=4; r+=4; // if (ip>matchlimit-4) { r -= ip - (matchlimit-3); ip = matchlimit-3; break; } // } // if (*(ushort *)r == *(ushort *)ip) { ip+=2; r+=2; } // if (*r == *ip) ip++; while (ip < matchlimit - (STEPSIZE - 1)) { int diff = (int)(*(int*)(r) ^ *(int*)(ip)); if (diff == 0) { ip += STEPSIZE; r += STEPSIZE; continue; } ip += DeBruijnBytePos[((uint)((diff & -diff) * 0x077CB531U)) >> 27]; ; goto _endCount; } if ((ip < (matchlimit - 1)) && (*(ushort*)(r) == *(ushort*)(ip))) { ip += 2; r += 2; } if ((ip < matchlimit) && (*r == *ip)) ip++; _endCount: len = (int)(ip - anchor); if (op + (1 + LASTLITERALS) + (len >> 8) >= oend) return 0; // Check output limit // Encode MatchLength if (len >= (int)LZ4Util.ML_MASK) { *token += (byte)LZ4Util.ML_MASK; len -= (byte)LZ4Util.ML_MASK; for (; len > 509; len -= 510) { *op++ = 255; *op++ = 255; } if (len > 254) { len -= 255; *op++ = 255; } *op++ = (byte)len; } else *token += (byte)len; // Test end of chunk if (ip > mflimit) { anchor = ip; break; } // Fill table hashTable[(((*(uint*)ip - 2) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG))] = ip - 2 - basePtr; // Test next position r = basePtr + hashTable[(((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG))]; hashTable[(((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG))] = ip - basePtr; if ((r > ip - (MAX_DISTANCE + 1)) && (*(uint*)r == *(uint*)ip)) { token = op++; *token = 0; goto _next_match; } // Prepare next loop anchor = ip++; forwardH = (((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG)); } _last_literals: // Encode Last Literals { int lastRun = (int)(iend - anchor); if (((byte*)op - dest) + lastRun + 1 + ((lastRun - 15) / 255) >= maxOutputSize) return 0; if (lastRun >= (int)LZ4Util.RUN_MASK) { *op++ = (byte)(LZ4Util.RUN_MASK << LZ4Util.ML_BITS); lastRun -= (byte)LZ4Util.RUN_MASK; for (; lastRun > 254; lastRun -= 255) *op++ = 255; *op++ = (byte)lastRun; } else *op++ = (byte)(lastRun << LZ4Util.ML_BITS); LZ4Util.CopyMemory(op, anchor, iend - anchor); op += iend - anchor; } // End return (int)(((byte*)op) - dest); } } // Note : this function is valid only if isize < LZ4_64KLIMIT int Compress64K(byte* source, byte* dest, int isize, int maxOutputSize) { fixed (byte* hashTablePtr = m_HashTable) fixed (byte* deBruijnBytePos = DeBruijnBytePos) { Clear(hashTablePtr, sizeof(ushort) * HASHTABLESIZE * 2); ushort* hashTable = (ushort*)hashTablePtr; byte* ip = (byte*)source; byte* anchor = ip; byte* basep = ip; byte* iend = ip + isize; byte* mflimit = iend - MFLIMIT; byte* matchlimit = (iend - LASTLITERALS); byte* op = (byte*)dest; byte* oend = dest + maxOutputSize; int len, length; const int skipStrength = SKIPSTRENGTH; uint forwardH; // Init if (isize < MINLENGTH) goto _last_literals; // First Byte ip++; forwardH = (((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1))); // Main Loop for (; ; ) { int findMatchAttempts = (int)(1U << skipStrength) + 3; byte* forwardIp = ip; byte* r; byte* token; // Find a match do { uint h = forwardH; int step = findMatchAttempts++ >> skipStrength; ip = forwardIp; forwardIp = ip + step; if (forwardIp > mflimit) { goto _last_literals; } forwardH = (((*(uint*)forwardIp) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1))); r = basep + hashTable[h]; hashTable[h] = (ushort)(ip - basep); } while (*(uint*)r != *(uint*)ip); // Catch up while ((ip > anchor) && (r > (byte*)source) && (ip[-1] == r[-1])) { ip--; r--; } // Encode Literal Length length = (int)(ip - anchor); token = op++; if (op + length + (2 + 1 + LASTLITERALS) + (length >> 8) >= oend) return 0; // Check output limit if (length >= (int)LZ4Util.RUN_MASK) { *token = (byte)(LZ4Util.RUN_MASK << LZ4Util.ML_BITS); len = (int)(length - LZ4Util.RUN_MASK); for (; len > 254; len -= 255) *op++ = 255; *op++ = (byte)len; } else *token = (byte)(length << LZ4Util.ML_BITS); // Copy Literals { byte* e = (op) + length; do { *(uint*)op = *(uint*)anchor; op += 4; anchor += 4; ; *(uint*)op = *(uint*)anchor; op += 4; anchor += 4; ; } while (op < e);; op = e; }; _next_match: // Encode Offset *(ushort*)op = (ushort)(ip - r); op += 2; // Start Counting ip += MINMATCH; r += MINMATCH; // MinMatch verified anchor = ip; // while (ip<matchlimit-3) // { // if (*(uint *)r == *(uint *)ip) { ip+=4; r+=4; continue; } // if (*(ushort *)r == *(ushort *)ip) { ip+=2; r+=2; } // if (*r == *ip) ip++; while (ip < matchlimit - (STEPSIZE - 1)) { int diff = (int)(*(int*)(r) ^ *(int*)(ip)); if (diff == 0) { ip += STEPSIZE; r += STEPSIZE; continue; } ip += DeBruijnBytePos[((uint)((diff & -diff) * 0x077CB531U)) >> 27]; ; goto _endCount; } if ((ip < (matchlimit - 1)) && (*(ushort*)r == *(ushort*)ip)) { ip += 2; r += 2; } if ((ip < matchlimit) && (*r == *ip)) ip++; _endCount: len = (int)(ip - anchor); //Encode MatchLength if (len >= (int)LZ4Util.ML_MASK) { *token = (byte)(*token + LZ4Util.ML_MASK); len = (int)(len - LZ4Util.ML_MASK); for (; len > 509; len -= 510) { *op++ = 255; *op++ = 255; } if (len > 254) { len -= 255; *op++ = 255; } *op++ = (byte)len; } else *token = (byte)(*token + len); // Test end of chunk if (ip > mflimit) { anchor = ip; break; } // Fill table hashTable[(((*(uint*)ip - 2) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1)))] = (ushort)(ip - 2 - basep); // Test next position r = basep + hashTable[(((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1)))]; hashTable[(((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1)))] = (ushort)(ip - basep); if (*(uint*)r == *(uint*)ip) { token = op++; *token = 0; goto _next_match; } // Prepare next loop anchor = ip++; forwardH = (((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1))); } _last_literals: { int lastRun = (int)(iend - anchor); if (((byte*)op - dest) + lastRun + 1 + ((lastRun) >> 8) >= maxOutputSize) return 0; if (lastRun >= (int)LZ4Util.RUN_MASK) { *op++ = (byte)(LZ4Util.RUN_MASK << LZ4Util.ML_BITS); lastRun -= (byte)LZ4Util.RUN_MASK; for (; lastRun > 254; lastRun -= 255) *op++ = 255; *op++ = (byte)lastRun; } else *op++ = (byte)(lastRun << LZ4Util.ML_BITS); LZ4Util.CopyMemory(op, anchor, iend - anchor); op += iend - anchor; } return (int)(((byte*)op) - dest); } } /// <summary> /// TODO: test if this is faster or slower than Array.Clear. /// </summary> /// <param name="array"></param> /// <param name="count"></param> static void Clear(byte* ptr, int count) { long* p = (long*)ptr; int longCount = count >> SIZE_OF_LONG_TIMES_TWO_SHIFT; // count / sizeof(long) * 2; while (longCount-- != 0) { *p++ = 0L; *p++ = 0L; } Debug.Assert(count % 16 == 0, "HashTable size must be divisible by 16"); //for (int i = longCount << 4 ; i < count; i++) // ptr[i] = 0; } } }
using System; using System.Collections.Generic; using System.Linq; using Pytocs.Core.Types; using Pytocs.Core.Syntax; namespace Pytocs.Core.TypeInference { /// <summary> /// Visits Python statements and collects data types from: /// - user annotations /// - expression usage. /// The results are collected in the provided <see cref="State"/> object. /// </summary> public class TypeCollector : IStatementVisitor<DataType>, IExpVisitor<DataType> { private readonly State scope; private readonly Analyzer analyzer; public TypeCollector(State s, Analyzer analyzer) { this.scope = s; this.analyzer = analyzer; } private DataType Register(Exp e, DataType t) { analyzer.AddExpType(e, t); return t; } public DataType VisitAliasedExp(AliasedExp a) { return DataType.Unknown; } public DataType VisitAsync(AsyncStatement a) { var dt = VisitFunctionDef((FunctionDef)a.Statement, true); return dt; } public DataType VisitAssert(AssertStatement a) { if (a.Tests != null) { foreach (var t in a.Tests) t.Accept(this); } if (a.Message != null) { a.Message.Accept(this); } return DataType.Cont; } public DataType VisitAssignExp(AssignExp a) { if (scope.stateType == State.StateType.CLASS && a.Dst is Identifier id) { if (id.Name == "__slots__") { // The __slots__ attribute needs to be handled specially: // it actually introduces new attributes. BindClassSlots(a.Src!); } else if (a.Annotation != null) { //$TODO: do something with the type info. //var dt = scope.LookupType(a.Annotation.ToString()); //scope.Bind(analyzer, id, dt ?? DataType.Unknown, BindingKind.ATTRIBUTE); if (a.Src != null) { DataType valueType = a.Src!.Accept(this); scope.BindByScope(analyzer, a.Dst, valueType); } } } else { if (a.Src != null) { DataType valueType = a.Src!.Accept(this); scope.BindByScope(analyzer, a.Dst, valueType); } } return DataType.Cont; } private void BindClassSlots(Exp eSlotNames) { IEnumerable<Exp>? slotNames = null; switch (eSlotNames) { case PyList srcList: slotNames = srcList.elts; break; case PyTuple srcTuple: slotNames = srcTuple.values; break; case ExpList expList: slotNames = expList.Expressions; break; } if (slotNames is null) { //$TODO: dynamically generated slots are hard. } else { // Generate an attribute binding for each slot. foreach (var slotName in slotNames.OfType<Str>()) { var id = new Identifier(slotName.s, slotName.Filename, slotName.Start, slotName.End); scope.Bind(analyzer, id, DataType.Unknown, BindingKind.ATTRIBUTE); } } } public DataType VisitAwait(AwaitExp e) { var dt = e.exp.Accept(this); return dt; } public DataType VisitFieldAccess(AttributeAccess a) { // the form of ::A in ruby if (a.Expression == null) { return a.FieldName.Accept(this); } var targetType = a.Expression.Accept(this); if (targetType is UnionType ut) { ISet<DataType> types = ut.types; DataType retType = DataType.Unknown; foreach (DataType tt in types) { retType = UnionType.Union(retType, GetAttrType(a, tt)); } return retType; } else { return GetAttrType(a, targetType); } } public DataType GetAttrType(AttributeAccess a, DataType targetType) { ISet<Binding>? bs = targetType.Table.LookupAttribute(a.FieldName.Name); if (bs is null) { analyzer.AddProblem(a.FieldName, "attribute not found in type: " + targetType); DataType t = DataType.Unknown; t.Table.Path = targetType.Table.ExtendPath(analyzer, a.FieldName.Name); return t; } else { analyzer.addRef(a, targetType, bs); return State.MakeUnion(bs); } } public DataType VisitBinExp(BinExp b) { DataType ltype = b.l.Accept(this); DataType rtype = b.r.Accept(this); if (b.op.IsBoolean()) { return DataType.Bool; } else { return UnionType.Union(ltype, rtype); } } public DataType VisitSuite(SuiteStatement b) { // first pass: mark global names var globalNames = b.stmts .OfType<GlobalStatement>() .SelectMany(g => g.names) .Concat(b.stmts .OfType<NonlocalStatement>() .SelectMany(g => g.names)); foreach (var id in globalNames) { scope.AddGlobalName(id.Name); ISet<Binding>? nb = scope.Lookup(id.Name); if (nb != null) { analyzer.putRef(id, nb); } } bool returned = false; DataType retType = DataType.Unknown; foreach (var n in b.stmts) { DataType t = n.Accept(this); if (!returned) { retType = UnionType.Union(retType, t); if (!UnionType.Contains(t, DataType.Cont)) { returned = true; retType = UnionType.Remove(retType, DataType.Cont); } } } return retType; } public DataType VisitBreak(BreakStatement b) { return DataType.None; } public DataType VisitBooleanLiteral(BooleanLiteral b) { return DataType.Bool; } /// <remarks> /// Most of the work here is done by the static method invoke, which is also /// used by Analyzer.applyUncalled. By using a static method we avoid building /// a NCall node for those dummy calls. /// </remarks> public DataType VisitApplication(Application c) { var fun = c.fn.Accept(this); var dtPos = c.args.Select(a => a.defval!.Accept(this)).ToList(); var hash = new Dictionary<string, DataType>(); if (c.keywords != null) { foreach (var k in c.keywords) { hash[k.name!.Name] = k.defval!.Accept(this); } } var dtKw = c.kwargs?.Accept(this); var dtStar = c.stargs?.Accept(this); if (fun is UnionType un) { DataType retType = DataType.Unknown; foreach (DataType ft in un.types) { DataType t = ResolveCall(c, ft, dtPos, hash, dtKw, dtStar); retType = UnionType.Union(retType, t); } return retType; } else { return ResolveCall(c, fun, dtPos, hash, dtKw, dtStar); } } private DataType ResolveCall( Application c, DataType fun, List<DataType> pos, IDictionary<string, DataType> hash, DataType? kw, DataType? star) { if (fun is FunType ft) { return Apply(ft, pos, hash, kw, star, c); } else if (fun is ClassType) { var instance = new InstanceType(fun); ApplyConstructor(instance, c, pos); return instance; } else { AddWarning(c, "calling non-function and non-class: " + fun); return DataType.Unknown; } } public void ApplyConstructor(InstanceType i, Application call, List<DataType> args) { if (i.Table.LookupAttributeType("__init__") is FunType initFunc && initFunc.Definition != null) { initFunc.SelfType = i; Apply(initFunc, args, null, null, null, call); initFunc.SelfType = null; } } /// <summary> /// Called when an application of a function is encountered. /// </summary> /// <param name="pos">Types deduced for positional arguments.</param> public DataType Apply( FunType func, List<DataType>? pos, IDictionary<string, DataType>? hash, DataType? kw, DataType? star, Exp? call) { analyzer.RemoveUncalled(func); if (func.Definition != null && !func.Definition.called) { analyzer.CalledFunctions++; func.Definition.called = true; } if (func.Definition == null) { // func without definition (possibly builtins) return func.GetReturnType(); } else if (call != null && analyzer.InStack(call)) { // Recursive call, ignore. func.SelfType = null; return DataType.Unknown; } if (call != null) { analyzer.pushStack(call); } var pTypes = new List<DataType>(); // Python: bind first parameter to self type if (func.SelfType != null) { pTypes.Add(func.SelfType); } else if (func.Class != null) { pTypes.Add(func.Class.GetInstance()); } if (pos != null) { pTypes.AddRange(pos); } BindMethodAttrs(analyzer, func); State funcTable = new State(func.scope, State.StateType.FUNCTION); if (func.Table.Parent != null) { funcTable.Path = func.Table.Parent.ExtendPath(analyzer, func.Definition.name.Name); } else { funcTable.Path = func.Definition.name.Name; } DataType fromType = BindParameters( call, func.Definition, funcTable, func.Definition.parameters, func.Definition.vararg, func.Definition.kwarg, pTypes, func.defaultTypes, hash, kw, star); if (func.arrows.TryGetValue(fromType, out var cachedTo)) { func.SelfType = null; return cachedTo; } else { if (func.Definition.Annotation != null) { var dtReturn = TranslateAnnotation(func.Definition.Annotation, funcTable); func.Definition.body.Accept(new TypeCollector(funcTable, analyzer)); func.AddMapping(fromType, dtReturn); return dtReturn; } DataType toType = func.Definition.body.Accept(new TypeCollector(funcTable, analyzer)); if (MissingReturn(toType)) { analyzer.AddProblem(func.Definition.name, "Function doesn't always return a value"); if (call != null) { analyzer.AddProblem(call, "Call doesn't always return a value"); } } toType = UnionType.Remove(toType, DataType.Cont); func.AddMapping(fromType, toType); func.SelfType = null; return toType; } } public static DataType? FirstArgumentType(FunctionDef f, FunType func, DataType? selfType) { if (f.parameters.Count == 0) return null; if (!func.Definition!.IsStaticMethod()) { if (func.Definition!.IsClassMethod()) { if (func.Class != null) { return func.Class; } else if (selfType != null && selfType is InstanceType inst) { return inst.classType; } } else { // usual method if (selfType != null) { return selfType; } else if (func.Class != null) { if (func.Definition.name.Name != "__init__") { throw new NotImplementedException("return func.Class.getInstance(null, this, call));"); } else { return func.Class.GetInstance(); } } } } return null; } /// <summary> /// Binds the parameters of a call to the called function. /// </summary> /// <param name="analyzer"></param> /// <param name="call"></param> /// <param name="func"></param> /// <param name="funcTable"></param> /// <param name="parameters">Positional parameters as declared by the 'def'</param> /// <param name="rest">Rest parameters declared by the 'def'</param> /// <param name="restKw">Keyword parameters declared by the 'def'</param> /// <param name="pTypes"></param> /// <param name="dTypes">Default types</param> /// <param name="hash"></param> /// <param name="kw"></param> /// <param name="star"></param> /// <returns></returns> private DataType BindParameters( Node? call, FunctionDef func, State funcTable, List<Parameter> parameters, Identifier? rest, Identifier? restKw, List<DataType>? pTypes, List<DataType?>? dTypes, IDictionary<string, DataType>? hash, DataType? kw, DataType? star) { var fromTypes = new List<DataType>(); int pSize = parameters == null ? 0 : parameters.Count; int aSize = pTypes == null ? 0 : pTypes.Count; int dSize = dTypes == null ? 0 : dTypes.Count; int nPos = pSize - dSize; if (star is ListType list) { star = list.ToTupleType(); } // Do the positional parameters first. for (int i = 0, j = 0; i < pSize; i++) { Parameter param = parameters![i]; DataType aType; if (param.Annotation != null) { aType = TranslateAnnotation(param.Annotation, funcTable); } else if (i < aSize) { aType = pTypes![i]; } else if (i - nPos >= 0 && i - nPos < dSize) { aType = dTypes![i - nPos]!; } else { if (hash != null && param.Id != null && hash.ContainsKey(param.Id.Name)) { aType = hash[param.Id.Name]; hash.Remove(param.Id.Name); } else { if (star != null && star is TupleType tup && j < tup.eltTypes.Length) { aType = tup[j]; ++j; } else { aType = DataType.Unknown; if (call != null) { analyzer.AddProblem(param.Id!, //$REVIEW: should be using identifiers "unable to bind argument:" + param); } } } } funcTable.Bind(analyzer, param.Id!, aType, BindingKind.PARAMETER); fromTypes.Add(aType); } TupleType fromType = analyzer.TypeFactory.CreateTuple(fromTypes.ToArray()); if (restKw != null) { DataType dt; if (hash != null && hash.Count > 0) { DataType hashType = UnionType.CreateUnion(hash.Values); dt = analyzer.TypeFactory.CreateDict(DataType.Str, hashType); } else { dt = DataType.Unknown; } funcTable.Bind( analyzer, restKw, dt, BindingKind.PARAMETER); } if (rest != null) { if (pTypes!.Count > pSize) { DataType restType = analyzer.TypeFactory.CreateTuple(pTypes.SubList(pSize, pTypes.Count).ToArray()); funcTable.Bind(analyzer, rest, restType, BindingKind.PARAMETER); } else { funcTable.Bind( analyzer, rest, DataType.Unknown, BindingKind.PARAMETER); } } return fromType; } static bool MissingReturn(DataType toType) { bool hasNone = false; bool hasOther = false; if (toType is UnionType ut) { foreach (DataType t in ut.types) { if (t == DataType.None || t == DataType.Cont) { hasNone = true; } else { hasOther = true; } } } return hasNone && hasOther; } static void BindMethodAttrs(Analyzer analyzer, FunType cl) { if (cl.Table.Parent != null) { DataType? cls = cl.Table.Parent.DataType; if (cls != null && cls is ClassType) { AddReadOnlyAttr(analyzer, cl, "im_class", cls, BindingKind.CLASS); AddReadOnlyAttr(analyzer, cl, "__class__", cls, BindingKind.CLASS); AddReadOnlyAttr(analyzer, cl, "im_self", cls, BindingKind.ATTRIBUTE); AddReadOnlyAttr(analyzer, cl, "__self__", cls, BindingKind.ATTRIBUTE); } } } static void AddReadOnlyAttr( Analyzer analyzer, FunType fun, string name, DataType type, BindingKind kind) { Node loc = Builtins.newDataModelUrl("the-standard-type-hierarchy"); Binding b = analyzer.CreateBinding(name, loc, type, kind); fun.Table.Update(name, b); b.IsSynthetic = true; b.IsStatic = true; } public void AddSpecialAttribute(State s, string name, DataType proptype) { Binding b = analyzer.CreateBinding(name, Builtins.newTutUrl("classes.html"), proptype, BindingKind.ATTRIBUTE); s.Update(name, b); b.IsSynthetic = true; b.IsStatic = true; } public DataType VisitClass(ClassDef c) { var path = scope.ExtendPath(analyzer, c.name.Name); var classType = new ClassType(c.name.Name, scope, path); var baseTypes = new List<DataType>(); foreach (var @base in c.args) { DataType baseType = @base.defval!.Accept(this); switch (baseType) { case ClassType _: classType.AddSuper(baseType); break; case UnionType ut: foreach (DataType parent in ut.types) { classType.AddSuper(parent); } break; default: analyzer.AddProblem(@base, @base + " is not a class"); break; } baseTypes.Add(baseType); } // XXX: Not sure if we should add "bases", "name" and "dict" here. They // must be added _somewhere_ but I'm just not sure if it should be HERE. AddSpecialAttribute(classType.Table, "__bases__", analyzer.TypeFactory.CreateTuple(baseTypes.ToArray())); AddSpecialAttribute(classType.Table, "__name__", DataType.Str); AddSpecialAttribute(classType.Table, "__dict__", analyzer.TypeFactory.CreateDict(DataType.Str, DataType.Unknown)); AddSpecialAttribute(classType.Table, "__module__", DataType.Str); AddSpecialAttribute(classType.Table, "__doc__", DataType.Str); // Bind ClassType to name here before resolving the body because the // methods need this type as self. scope.Bind(analyzer, c.name, classType, BindingKind.CLASS); if (c.body != null) { var xform = new TypeCollector(classType.Table, this.analyzer); c.body.Accept(xform); } return DataType.Cont; } public DataType VisitComment(CommentStatement c) { return DataType.Cont; } public DataType VisitImaginary(ImaginaryLiteral c) { return DataType.Complex; } public DataType VisitCompFor(CompFor f) { var it = f.variable.Accept(this); scope.BindIterator(analyzer, f.variable, f.collection, it, BindingKind.SCOPE); return f.variable.Accept(this); } public DataType VisitCompIf(CompIf i) { throw new NotImplementedException(); } //public DataType VisitComprehension(Comprehension c) //{ // Binder.bindIter(fs, s, c.target, c.iter, Binding.Kind.SCOPE); // resolveList(c.ifs); // return c.target.Accept(this); //} public DataType VisitContinue(ContinueStatement c) { return DataType.Cont; } public DataType VisitDel(DelStatement d) { foreach (var n in d.Expressions.AsList()) { n.Accept(this); if (n is Identifier id) { scope.Remove(id.Name); } } return DataType.Cont; } public DataType VisitDictInitializer(DictInitializer d) { DataType keyType = ResolveUnion(d.KeyValues.Where(kv => kv.Key != null).Select(kv => kv.Key!)); DataType valType = ResolveUnion(d.KeyValues.Select(kv => kv.Value)); return analyzer.TypeFactory.CreateDict(keyType, valType); } /// /// Python's list comprehension will bind the variables used in generators. /// This will erase the original values of the variables even after the /// comprehension. /// public DataType VisitDictComprehension(DictComprehension d) { // ResolveList(d.generator); DataType keyType = d.key.Accept(this); DataType valueType = d.value.Accept(this); return analyzer.TypeFactory.CreateDict(keyType, valueType); } public DataType VisitDottedName(DottedName name) { throw new NotImplementedException(); } public DataType VisitEllipsis(Ellipsis e) { return DataType.None; } public DataType VisitExec(ExecStatement e) { if (e.code != null) { e.code.Accept(this); } if (e.globals != null) { e.globals.Accept(this); } if (e.locals != null) { e.locals.Accept(this); } return DataType.Cont; } public DataType VisitExp(ExpStatement e) { if (e.Expression != null) { e.Expression.Accept(this); } return DataType.Cont; } public DataType VisitExpList(ExpList list) { var elTypes = new List<DataType>(); foreach (var el in list.Expressions) { var elt = el.Accept(this); elTypes.Add(elt); } return new TupleType(elTypes.ToArray()); } public DataType VisitExtSlice(List<Slice> e) { foreach (var d in e) { d.Accept(this); } return new ListType(); } public DataType VisitFor(ForStatement f) { scope.BindIterator(analyzer, f.exprs, f.tests, f.tests.Accept(this), BindingKind.SCOPE); DataType ret; if (f.Body == null) { ret = DataType.Unknown; } else { ret = f.Body.Accept(this); } if (f.Else != null) { ret = UnionType.Union(ret, f.Else.Accept(this)); } return ret; } public DataType VisitIterableUnpacker(IterableUnpacker unpacker) { var it = unpacker.Iterable.Accept(this); var iterType = analyzer.TypeFactory.CreateIterable(it); return iterType; } public DataType VisitLambda(Lambda lambda) { State env = scope.getForwarding(); var fun = new FunType(lambda, env); fun.Table.Parent = this.scope; fun.Table.Path = scope.ExtendPath(analyzer, "{lambda}"); fun.SetDefaultTypes(ResolveList(lambda.args.Select(p => p.test!))); analyzer.AddUncalled(fun); return fun; } public DataType VisitFunctionDef(FunctionDef f) { return VisitFunctionDef(f, false); } public DataType VisitFunctionDef(FunctionDef f, bool isAsync) { State env = scope.getForwarding(); FunType fun = new FunType(f, env); fun.Table.Parent = this.scope; fun.Table.Path = scope.ExtendPath(analyzer, f.name.Name); fun.SetDefaultTypes(ResolveList(f.parameters .Where(p => p.Test != null) .Select(p => p.Test!))); if (isAsync) { fun = fun.MakeAwaitable(); } analyzer.AddUncalled(fun); BindingKind funkind = DetermineFunctionKind(f); var ct = scope.DataType as ClassType; if (ct != null) { fun.Class = ct; } scope.Bind(analyzer, f.name, fun, funkind); var firstArgType = FirstArgumentType(f, fun, ct); if (firstArgType != null) { fun.Table.Bind(analyzer, f.parameters[0].Id!, firstArgType, BindingKind.PARAMETER); } f.body.Accept(new TypeCollector(fun.Table, this.analyzer)); return DataType.Cont; } private BindingKind DetermineFunctionKind(FunctionDef f) { if (scope.stateType == State.StateType.CLASS) { if ("__init__" == f.name.Name) { return BindingKind.CONSTRUCTOR; } else { return BindingKind.METHOD; } } else { return BindingKind.FUNCTION; } } public DataType VisitGlobal(GlobalStatement g) { // Do nothing here because global names are processed by VisitSuite return DataType.Cont; } public DataType VisitNonLocal(NonlocalStatement non) { // Do nothing here because global names are processed by VisitSuite return DataType.Cont; } public DataType VisitHandler(ExceptHandler h) { DataType typeval = DataType.Unknown; if (h.type != null) { typeval = h.type.Accept(this); } if (h.name != null) { scope.BindByScope(analyzer, h.name, typeval); } if (h.body != null) { return h.body.Accept(this); } else { return DataType.Unknown; } } public DataType VisitIf(IfStatement i) { DataType type1, type2; State s1 = scope.Clone(); State s2 = scope.Clone(); // Ignore condition for now i.Test.Accept(this); if (i.Then != null) { type1 = i.Then.Accept(this); } else { type1 = DataType.Cont; } if (i.Else != null) { type2 = i.Else.Accept(this); } else { type2 = DataType.Cont; } bool cont1 = UnionType.Contains(type1, DataType.Cont); bool cont2 = UnionType.Contains(type2, DataType.Cont); // Decide which branch affects the downstream state if (cont1 && cont2) { s1.Merge(s2); scope.Overwrite(s1); } else if (cont1) { scope.Overwrite(s1); } else if (cont2) { scope.Overwrite(s2); } return UnionType.Union(type1, type2); } public DataType VisitTest(TestExp i) { DataType type1, type2; i.Condition.Accept(this); if (i.Consequent != null) { type1 = i.Consequent.Accept(this); } else { type1 = DataType.Cont; } if (i.Alternative != null) { type2 = i.Alternative.Accept(this); } else { type2 = DataType.Cont; } return UnionType.Union(type1, type2); } public DataType VisitImport(ImportStatement i) { foreach (var a in i.names) { DataType? mod = analyzer.LoadModule(a.orig.segs, scope); if (mod is null) { analyzer.AddProblem(i, $"Cannot load module {a}"); } else if (a.alias != null) { scope.Insert(analyzer, a.alias.Name, a.alias, mod, BindingKind.VARIABLE); } } return DataType.Cont; } public DataType VisitFrom(FromStatement i) { if (i.DottedName == null) { return DataType.Cont; } var dtModule = analyzer.LoadModule(i.DottedName.segs, scope); if (dtModule == null) { analyzer.AddProblem(i, "Cannot load module"); } else if (i.isImportStar()) { ImportStar(i, dtModule); } else { foreach (var a in i.AliasedNames) { var idFirst = a.orig.segs[0]; var bs = dtModule.Table.Lookup(idFirst.Name); if (bs != null) { if (a.alias != null) { scope.Update(a.alias.Name, bs); analyzer.putRef(a.alias, bs); } else { scope.Update(idFirst.Name, bs); analyzer.putRef(idFirst, bs); } } else { var ext = new List<Identifier>(i.DottedName.segs) { idFirst }; DataType? mod2 = analyzer.LoadModule(ext, scope); if (mod2 != null) { if (a.alias != null) { scope.Insert(analyzer, a.alias.Name, a.alias, mod2, BindingKind.VARIABLE); } else { scope.Insert(analyzer, idFirst.Name, idFirst, mod2, BindingKind.VARIABLE); } } } } } return DataType.Cont; } private void ImportStar(FromStatement i, DataType mt) { if (mt == null || mt.file == null) { return; } Module? node = analyzer.GetAstForFile(mt.file); if (node == null) { return; } DataType? allType = mt.Table.LookupTypeOf("__all__"); List<string> names = new List<string>(); if (allType != null && allType is ListType lt) { foreach (var s in lt.values.OfType<string>()) { names.Add(s); } } if (names.Count > 0) { int start = i.Start; foreach (string name in names) { ISet<Binding>? b = mt.Table.LookupLocal(name); if (b != null) { scope.Update(name, b); } else { var m2 = new List<Identifier>(i.DottedName!.segs); var fakeName = new Identifier(name, i.Filename, start, start + name.Length); m2.Add(fakeName); DataType? type = analyzer.LoadModule(m2, scope); if (type != null) { start += name.Length; scope.Insert(analyzer, name, fakeName, type, BindingKind.VARIABLE); } } } } else { // Fall back to importing all names not starting with "_". foreach (var e in mt.Table.entrySet().Where(en => !en.Key.StartsWith("_"))) { scope.Update(e.Key, e.Value); } } } public DataType VisitArgument(Argument arg) { return arg.defval!.Accept(this); } public DataType VisitBigLiteral(BigLiteral i) { return Register(i, DataType.Int); } public DataType VisitIntLiteral(IntLiteral i) { return DataType.Int; } public DataType VisitList(PyList l) { var listType = new ListType(); if (l.elts.Count == 0) return Register(l, listType); // list of unknown. foreach (var exp in l.elts) { listType.Add(exp.Accept(this)); if (exp is Str sExp) { listType.addValue(sExp.s); } } return Register(l, listType); } /// <remarks> /// Python's list comprehension will bind the variables used in generators. /// This will erase the original values of the variables even after the /// comprehension. /// </remarks> public DataType VisitListComprehension(ListComprehension l) { l.Collection.Accept(this); return analyzer.TypeFactory.CreateList(l.Projection.Accept(this)); } /// /// Python's list comprehension will erase any variable used in generators. /// This is wrong, but we "respect" this bug here. /// public DataType VisitGeneratorExp(GeneratorExp g) { g.Collection.Accept(this); return analyzer.TypeFactory.CreateList(g.Projection.Accept(this)); } public DataType VisitLongLiteral(LongLiteral l) { return DataType.Int; } public ModuleType VisitModule(Module m) { string? qname = null; if (m.Filename != null) { // This will return null iff specified file is not prefixed by // any path in the module search path -- i.e., the caller asked // the analyzer to load a file not in the search path. qname = analyzer.GetModuleQname(m.Filename); } if (qname == null) { qname = m.Name; } var mt = analyzer.TypeFactory.CreateModule(m.Name, m.Filename!, qname, analyzer.GlobalTable); scope.Insert(analyzer, analyzer.GetModuleQname(m.Filename!), m, mt, BindingKind.MODULE); if (m.Body != null) { m.Body.Accept(new TypeCollector(mt.Table, this.analyzer)); } return mt; } public DataType VisitIdentifier(Identifier id) { ISet<Binding>? b = scope.Lookup(id.Name); if (b != null) { analyzer.putRef(id, b); analyzer.Resolved.Add(id); analyzer.Unresolved.Remove(id); return State.MakeUnion(b); } else if (id.Name == "True" || id.Name == "False") { return DataType.Bool; } else { analyzer.AddProblem(id, $"unbound variable {id.Name}"); analyzer.Unresolved.Add(id); DataType t = DataType.Unknown; t.Table.Path = scope.ExtendPath(analyzer, id.Name); return t; } } public DataType VisitNoneExp() { return DataType.None; } public DataType VisitPass(PassStatement p) { return DataType.Cont; } public DataType VisitPrint(PrintStatement p) { if (p.outputStream != null) { p.outputStream.Accept(this); } if (p.args != null) { ResolveList(p.args.Select(a => a.defval!)); } return DataType.Cont; } public DataType VisitRaise(RaiseStatement r) { if (r.exToRaise != null) { r.exToRaise.Accept(this); } if (r.exOriginal != null) { r.exOriginal.Accept(this); } if (r.traceback != null) { r.traceback.Accept(this); } return DataType.Cont; } public DataType VisitRealLiteral(RealLiteral r) { return DataType.Float; } //public DataType VisitRepr(Repr r) //{ // if (r.value != null) // { // r.value.Accept(this); // } // return DataType.STR; //} public DataType VisitReturn(ReturnStatement r) { if (r.Expression == null) { return DataType.None; } else { return r.Expression.Accept(this); } } public DataType VisitSet(PySet s) { DataType valType = ResolveUnion(s.exps); return new SetType(valType); } public DataType VisitSetComprehension(SetComprehension s) { s.Collection.Accept(this); return new SetType(s.Projection.Accept(this)); } public DataType VisitSlice(Slice s) { if (s.Lower != null) { s.Lower.Accept(this); } if (s.Step != null) { s.Step.Accept(this); } if (s.Upper != null) { s.Upper.Accept(this); } return analyzer.TypeFactory.CreateList(); } public DataType VisitStarExp(StarExp s) { return s.e.Accept(this); } public DataType VisitStr(Str s) { return DataType.Str; } public DataType VisitBytes(Bytes b) { return DataType.Str; } public DataType VisitArrayRef(ArrayRef s) { DataType vt = s.array.Accept(this); DataType? st; if (s.subs == null || s.subs.Count == 0) st = null; else if (s.subs.Count == 1) st = s.subs[0].Accept(this); else st = VisitExtSlice(s.subs); if (vt is UnionType ut) { DataType retType = DataType.Unknown; foreach (DataType t in ut.types) { retType = UnionType.Union( retType, GetSubscript(s, t, st)); } return retType; } else { return GetSubscript(s, vt, st); } } public DataType GetSubscript(ArrayRef s, DataType vt, DataType? st) { if (vt.IsUnknownType()) { return DataType.Unknown; } switch (vt) { case ListType list: return GetListSubscript(s, list, st); case TupleType tup: return GetListSubscript(s, tup.ToListType(), st); case DictType dt: if (!dt.KeyType.Equals(st!)) { AddWarning(s, "Possible KeyError (wrong type for subscript)"); } return dt.ValueType; case StrType _: if (st != null && (st is ListType || st.IsNumType())) { return vt; } else { AddWarning(s, "Possible KeyError (wrong type for subscript)"); return DataType.Unknown; } default: return DataType.Unknown; } } private DataType GetListSubscript(ArrayRef s, DataType vt, DataType? st) { if (vt is ListType list) { if (st != null && st is ListType) { return vt; } else if (st == null || st.IsNumType()) { return list.eltType; } else { DataType? sliceFunc = vt.Table.LookupAttributeType("__getslice__"); if (sliceFunc == null) { AddError(s, "The type can't be sliced: " + vt); return DataType.Unknown; } else if (sliceFunc is FunType ft) { return Apply(ft, null, null, null, null, s); } else { AddError(s, "The type's __getslice__ method is not a function: " + sliceFunc); return DataType.Unknown; } } } else { return DataType.Unknown; } } public DataType VisitTry(TryStatement t) { DataType tp1 = DataType.Unknown; DataType tp2 = DataType.Unknown; DataType tph = DataType.Unknown; DataType tpFinal = DataType.Unknown; if (t.exHandlers != null) { foreach (var h in t.exHandlers) { tph = UnionType.Union(tph, VisitHandler(h)); } } if (t.body != null) { tp1 = t.body.Accept(this); } if (t.elseHandler != null) { tp2 = t.elseHandler.Accept(this); } if (t.finallyHandler != null) { tpFinal = t.finallyHandler.Accept(this); } return new UnionType(tp1, tp2, tph, tpFinal); } public DataType VisitTuple(PyTuple t) { var tts = t.values.Select(e => e.Accept(this)).ToArray(); TupleType tt = analyzer.TypeFactory.CreateTuple(tts); return tt; } public DataType VisitUnary(UnaryExp u) { return u.e.Accept(this); } public DataType VisitUrl(Url s) { return DataType.Str; } public DataType VisitWhile(WhileStatement w) { w.Test.Accept(this); DataType t = DataType.Unknown; if (w.Body != null) { t = w.Body.Accept(this); } if (w.Else != null) { t = UnionType.Union(t, w.Else.Accept(this)); } return t; } public DataType VisitWith(WithStatement w) { foreach (var item in w.items) { DataType val = item.t.Accept(this); if (item.e != null) { scope.BindByScope(analyzer, item.e, val); } } return w.body.Accept(this); } public DataType VisitYieldExp(YieldExp y) { if (y.exp != null) { return analyzer.TypeFactory.CreateList(y.exp.Accept(this)); } else { return DataType.None; } } public DataType VisitYieldFromExp(YieldFromExp y) { if (y.Expression != null) { return analyzer.TypeFactory.CreateList(y.Expression.Accept(this)); } else { return DataType.None; } } public DataType VisitYield(YieldStatement y) { if (y.Expression != null) return analyzer.TypeFactory.CreateList(y.Expression.Accept(this)); else return DataType.None; } protected void AddError(Node n, string msg) { analyzer.AddProblem(n, msg); } protected void AddWarning(Node n, string msg) { analyzer.AddProblem(n, msg); } /// <summary> /// Resolves each element, and constructs a result list. /// </summary> private List<DataType?>? ResolveList(IEnumerable<Exp?> nodes) { if (nodes == null) { return null; } else { return nodes .Select(n => n?.Accept(this)) .ToList(); } } /// <summary> /// Utility method to resolve every node in <param name="nodes"/> and /// return the union of their types. If <param name="nodes" /> is empty or /// null, returns a new {@link Pytocs.Core.Types.UnknownType}. /// </summary> public DataType ResolveUnion(IEnumerable<Exp> nodes) { DataType result = DataType.Unknown; foreach (var node in nodes) { DataType nodeType = node.Accept(this); result = UnionType.Union(result, nodeType); } return result; } /// <summary> /// Translate a Python type annotation to a <see cref="DataType"/>. /// </summary> private DataType TranslateAnnotation(Exp exp, State state) { if (exp is ArrayRef aref) { // Generic types are expressed like: GenericType[TypeArg1,TypeArg2,...] var dts = new List<DataType>(); foreach (var sub in aref.subs) { if (sub.Lower != null) { dts.Add(TranslateAnnotation(sub.Lower, state)); } else { dts.Add(DataType.Unknown); } } var genericType = state.LookupTypeByName(aref.array.ToString()); if (genericType is null) { analyzer.AddProblem(exp, string.Format(Resources2.ErrUnknownTypeInTypeAnnotation, exp)); return DataType.Unknown; } return genericType.MakeGenericType(dts.ToArray()); } if (exp is Identifier id) { var dt = state.LookupTypeByName(id.Name); if (dt is null) { analyzer.AddProblem(exp, string.Format(Resources2.ErrUnknownTypeInTypeAnnotation, exp)); return DataType.Unknown; } return dt; } analyzer.AddProblem(exp, string.Format(Resources2.ErrUnknownTypeInTypeAnnotation, exp)); return DataType.Unknown; } } public static class ListEx { public static List<T> SubList<T>(this List<T> list, int iMin, int iMac) { return list.Skip(iMin).Take(iMac - iMin).ToList(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.Threading.Tasks; namespace System.ServiceModel.Channels { public abstract class ChannelFactoryBase : ChannelManagerBase, IChannelFactory, IAsyncChannelFactory { private TimeSpan _closeTimeout = ServiceDefaults.CloseTimeout; private TimeSpan _openTimeout = ServiceDefaults.OpenTimeout; private TimeSpan _receiveTimeout = ServiceDefaults.ReceiveTimeout; private TimeSpan _sendTimeout = ServiceDefaults.SendTimeout; protected ChannelFactoryBase() { } protected ChannelFactoryBase(IDefaultCommunicationTimeouts timeouts) { this.InitializeTimeouts(timeouts); } protected override TimeSpan DefaultCloseTimeout { get { return _closeTimeout; } } protected override TimeSpan DefaultOpenTimeout { get { return _openTimeout; } } protected override TimeSpan DefaultReceiveTimeout { get { return _receiveTimeout; } } protected override TimeSpan DefaultSendTimeout { get { return _sendTimeout; } } public virtual T GetProperty<T>() where T : class { if (typeof(T) == typeof(IChannelFactory)) { return (T)(object)this; } return default(T); } protected override void OnAbort() { } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new CompletedAsyncResult(callback, state); } protected internal override Task OnCloseAsync(TimeSpan timeout) { return TaskHelpers.CompletedTask(); } protected override void OnClose(TimeSpan timeout) { } protected override void OnEndClose(IAsyncResult result) { CompletedAsyncResult.End(result); } private void InitializeTimeouts(IDefaultCommunicationTimeouts timeouts) { if (timeouts != null) { _closeTimeout = timeouts.CloseTimeout; _openTimeout = timeouts.OpenTimeout; _receiveTimeout = timeouts.ReceiveTimeout; _sendTimeout = timeouts.SendTimeout; } } } public abstract class ChannelFactoryBase<TChannel> : ChannelFactoryBase, IChannelFactory<TChannel> { private CommunicationObjectManager<IChannel> _channels; protected ChannelFactoryBase() : this(null) { } protected ChannelFactoryBase(IDefaultCommunicationTimeouts timeouts) : base(timeouts) { _channels = new CommunicationObjectManager<IChannel>(this.ThisLock); } public TChannel CreateChannel(EndpointAddress address) { if (address == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); return this.InternalCreateChannel(address, address.Uri); } public TChannel CreateChannel(EndpointAddress address, Uri via) { if (address == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); if (via == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("via"); return this.InternalCreateChannel(address, via); } private TChannel InternalCreateChannel(EndpointAddress address, Uri via) { this.ValidateCreateChannel(); TChannel channel = this.OnCreateChannel(address, via); bool success = false; try { _channels.Add((IChannel)(object)channel); success = true; } finally { if (!success) ((IChannel)(object)channel).Abort(); } return channel; } protected abstract TChannel OnCreateChannel(EndpointAddress address, Uri via); protected void ValidateCreateChannel() { ThrowIfDisposed(); if (this.State != CommunicationState.Opened) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ChannelFactoryCannotBeUsedToCreateChannels, this.GetType().ToString()))); } } protected override void OnAbort() { IChannel[] currentChannels = _channels.ToArray(); foreach (IChannel channel in currentChannels) channel.Abort(); _channels.Abort(); } protected override void OnClose(TimeSpan timeout) { IChannel[] currentChannels = _channels.ToArray(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); foreach (IChannel channel in currentChannels) channel.Close(timeoutHelper.RemainingTime()); _channels.Close(timeoutHelper.RemainingTime()); } protected internal override Task OnCloseAsync(TimeSpan timeout) { return OnCloseAsyncInternal(timeout); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedCloseAsyncResult(timeout, callback, state, _channels.BeginClose, _channels.EndClose, _channels.ToArray()); } protected override void OnEndClose(IAsyncResult result) { ChainedCloseAsyncResult.End(result); } private async Task OnCloseAsyncInternal(TimeSpan timeout) { IChannel[] currentChannels = _channels.ToArray(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); foreach (IChannel channel in currentChannels) { IAsyncCommunicationObject iAsyncChannel = channel as IAsyncCommunicationObject; if (iAsyncChannel != null) { await iAsyncChannel.CloseAsync(timeoutHelper.RemainingTime()); } else { channel.Close(timeoutHelper.RemainingTime()); } } await Task.Factory.FromAsync(_channels.BeginClose, _channels.EndClose, timeout, TaskCreationOptions.None); } } }
using J2N.Numerics; using YAF.Lucene.Net.Support; using System; using System.Diagnostics; namespace YAF.Lucene.Net.Codecs.Compressing { /* * 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 DataInput = YAF.Lucene.Net.Store.DataInput; using DataOutput = YAF.Lucene.Net.Store.DataOutput; using PackedInt32s = YAF.Lucene.Net.Util.Packed.PackedInt32s; /// <summary> /// LZ4 compression and decompression routines. /// <para/> /// http://code.google.com/p/lz4/ /// http://fastcompression.blogspot.fr/p/lz4.html /// </summary> public sealed class LZ4 { private LZ4() { } internal const int MEMORY_USAGE = 14; internal const int MIN_MATCH = 4; // minimum length of a match internal static readonly int MAX_DISTANCE = 1 << 16; // maximum distance of a reference internal const int LAST_LITERALS = 5; // the last 5 bytes must be encoded as literals internal const int HASH_LOG_HC = 15; // log size of the dictionary for compressHC internal static readonly int HASH_TABLE_SIZE_HC = 1 << HASH_LOG_HC; internal static readonly int OPTIMAL_ML = 0x0F + 4 - 1; // match length that doesn't require an additional byte private static int Hash(int i, int hashBits) { return (i * -1640531535).TripleShift(32 - hashBits); } private static int HashHC(int i) { return Hash(i, HASH_LOG_HC); } /// <summary> /// NOTE: This was readInt() in Lucene. /// </summary> private static int ReadInt32(byte[] buf, int i) { return ((((sbyte)buf[i]) & 0xFF) << 24) | ((((sbyte)buf[i + 1]) & 0xFF) << 16) | ((((sbyte)buf[i + 2]) & 0xFF) << 8) | (((sbyte)buf[i + 3]) & 0xFF); } /// <summary> /// NOTE: This was readIntEquals() in Lucene. /// </summary> private static bool ReadInt32Equals(byte[] buf, int i, int j) { return ReadInt32(buf, i) == ReadInt32(buf, j); } private static int CommonBytes(byte[] b, int o1, int o2, int limit) { Debug.Assert(o1 < o2); int count = 0; while (o2 < limit && b[o1++] == b[o2++]) { ++count; } return count; } private static int CommonBytesBackward(byte[] b, int o1, int o2, int l1, int l2) { int count = 0; while (o1 > l1 && o2 > l2 && b[--o1] == b[--o2]) { ++count; } return count; } /// <summary> /// Decompress at least <paramref name="decompressedLen"/> bytes into /// <c>dest[dOff]</c>. Please note that <paramref name="dest"/> must be large /// enough to be able to hold <b>all</b> decompressed data (meaning that you /// need to know the total decompressed length). /// </summary> public static int Decompress(DataInput compressed, int decompressedLen, byte[] dest, int dOff) { int destEnd = dest.Length; do { // literals int token = compressed.ReadByte() & 0xFF; int literalLen = (int)(((uint)token) >> 4); if (literalLen != 0) { if (literalLen == 0x0F) { byte len; while ((len = compressed.ReadByte()) == 0xFF) { literalLen += 0xFF; } literalLen += len & 0xFF; } compressed.ReadBytes(dest, dOff, literalLen); dOff += literalLen; } if (dOff >= decompressedLen) { break; } // matchs var byte1 = compressed.ReadByte(); var byte2 = compressed.ReadByte(); int matchDec = (byte1 & 0xFF) | ((byte2 & 0xFF) << 8); Debug.Assert(matchDec > 0); int matchLen = token & 0x0F; if (matchLen == 0x0F) { int len; while ((len = compressed.ReadByte()) == 0xFF) { matchLen += 0xFF; } matchLen += len & 0xFF; } matchLen += MIN_MATCH; // copying a multiple of 8 bytes can make decompression from 5% to 10% faster int fastLen = (int)((matchLen + 7) & 0xFFFFFFF8); if (matchDec < matchLen || dOff + fastLen > destEnd) { // overlap -> naive incremental copy for (int @ref = dOff - matchDec, end = dOff + matchLen; dOff < end; ++@ref, ++dOff) { dest[dOff] = dest[@ref]; } } else { // no overlap -> arraycopy Array.Copy(dest, dOff - matchDec, dest, dOff, fastLen); dOff += matchLen; } } while (dOff < decompressedLen); return dOff; } private static void EncodeLen(int l, DataOutput @out) { while (l >= 0xFF) { @out.WriteByte(unchecked((byte)(sbyte)0xFF)); l -= 0xFF; } @out.WriteByte((byte)(sbyte)l); } private static void EncodeLiterals(byte[] bytes, int token, int anchor, int literalLen, DataOutput @out) { @out.WriteByte((byte)(sbyte)token); // encode literal length if (literalLen >= 0x0F) { EncodeLen(literalLen - 0x0F, @out); } // encode literals @out.WriteBytes(bytes, anchor, literalLen); } private static void EncodeLastLiterals(byte[] bytes, int anchor, int literalLen, DataOutput @out) { int token = Math.Min(literalLen, 0x0F) << 4; EncodeLiterals(bytes, token, anchor, literalLen, @out); } private static void EncodeSequence(byte[] bytes, int anchor, int matchRef, int matchOff, int matchLen, DataOutput @out) { int literalLen = matchOff - anchor; Debug.Assert(matchLen >= 4); // encode token int token = (Math.Min(literalLen, 0x0F) << 4) | Math.Min(matchLen - 4, 0x0F); EncodeLiterals(bytes, token, anchor, literalLen, @out); // encode match dec int matchDec = matchOff - matchRef; Debug.Assert(matchDec > 0 && matchDec < 1 << 16); @out.WriteByte((byte)(sbyte)matchDec); @out.WriteByte((byte)(sbyte)((int)((uint)matchDec >> 8))); // encode match len if (matchLen >= MIN_MATCH + 0x0F) { EncodeLen(matchLen - 0x0F - MIN_MATCH, @out); } } public sealed class HashTable { internal int hashLog; internal PackedInt32s.Mutable hashTable; internal void Reset(int len) { int bitsPerOffset = PackedInt32s.BitsRequired(len - LAST_LITERALS); int bitsPerOffsetLog = 32 - (bitsPerOffset - 1).LeadingZeroCount(); hashLog = MEMORY_USAGE + 3 - bitsPerOffsetLog; if (hashTable == null || hashTable.Count < 1 << hashLog || hashTable.BitsPerValue < bitsPerOffset) { hashTable = PackedInt32s.GetMutable(1 << hashLog, bitsPerOffset, PackedInt32s.DEFAULT); } else { hashTable.Clear(); } } } /// <summary> /// Compress <c>bytes[off:off+len]</c> into <paramref name="out"/> using /// at most 16KB of memory. <paramref name="ht"/> shouldn't be shared across threads /// but can safely be reused. /// </summary> public static void Compress(byte[] bytes, int off, int len, DataOutput @out, HashTable ht) { int @base = off; int end = off + len; int anchor = off++; if (len > LAST_LITERALS + MIN_MATCH) { int limit = end - LAST_LITERALS; int matchLimit = limit - MIN_MATCH; ht.Reset(len); int hashLog = ht.hashLog; PackedInt32s.Mutable hashTable = ht.hashTable; while (off <= limit) { // find a match int @ref; while (true) { if (off >= matchLimit) { goto mainBreak; } int v = ReadInt32(bytes, off); int h = Hash(v, hashLog); @ref = @base + (int)hashTable.Get(h); Debug.Assert(PackedInt32s.BitsRequired(off - @base) <= hashTable.BitsPerValue); hashTable.Set(h, off - @base); if (off - @ref < MAX_DISTANCE && ReadInt32(bytes, @ref) == v) { break; } ++off; } // compute match length int matchLen = MIN_MATCH + CommonBytes(bytes, @ref + MIN_MATCH, off + MIN_MATCH, limit); EncodeSequence(bytes, anchor, @ref, off, matchLen, @out); off += matchLen; anchor = off; //mainContinue: ; // LUCENENET NOTE: Not Referenced } mainBreak: ; } // last literals int literalLen = end - anchor; Debug.Assert(literalLen >= LAST_LITERALS || literalLen == len); EncodeLastLiterals(bytes, anchor, end - anchor, @out); } public class Match { internal int start, @ref, len; internal virtual void Fix(int correction) { start += correction; @ref += correction; len -= correction; } internal virtual int End() { return start + len; } } private static void CopyTo(Match m1, Match m2) { m2.len = m1.len; m2.start = m1.start; m2.@ref = m1.@ref; } public sealed class HCHashTable { internal const int MAX_ATTEMPTS = 256; internal static readonly int MASK = MAX_DISTANCE - 1; internal int nextToUpdate; private int @base; private readonly int[] hashTable; private readonly short[] chainTable; internal HCHashTable() { hashTable = new int[HASH_TABLE_SIZE_HC]; chainTable = new short[MAX_DISTANCE]; } internal void Reset(int @base) { this.@base = @base; nextToUpdate = @base; Arrays.Fill(hashTable, -1); Arrays.Fill(chainTable, (short)0); } private int HashPointer(byte[] bytes, int off) { int v = ReadInt32(bytes, off); int h = HashHC(v); return hashTable[h]; } private int Next(int off) { return off - (chainTable[off & MASK] & 0xFFFF); } private void AddHash(byte[] bytes, int off) { int v = ReadInt32(bytes, off); int h = HashHC(v); int delta = off - hashTable[h]; Debug.Assert(delta > 0, delta.ToString()); if (delta >= MAX_DISTANCE) { delta = MAX_DISTANCE - 1; } chainTable[off & MASK] = (short)delta; hashTable[h] = off; } internal void Insert(int off, byte[] bytes) { for (; nextToUpdate < off; ++nextToUpdate) { AddHash(bytes, nextToUpdate); } } internal bool InsertAndFindBestMatch(byte[] buf, int off, int matchLimit, Match match) { match.start = off; match.len = 0; int delta = 0; int repl = 0; Insert(off, buf); int @ref = HashPointer(buf, off); if (@ref >= off - 4 && @ref <= off && @ref >= @base) // potential repetition { if (ReadInt32Equals(buf, @ref, off)) // confirmed { delta = off - @ref; repl = match.len = MIN_MATCH + CommonBytes(buf, @ref + MIN_MATCH, off + MIN_MATCH, matchLimit); match.@ref = @ref; } @ref = Next(@ref); } for (int i = 0; i < MAX_ATTEMPTS; ++i) { if (@ref < Math.Max(@base, off - MAX_DISTANCE + 1) || @ref > off) { break; } if (buf[@ref + match.len] == buf[off + match.len] && ReadInt32Equals(buf, @ref, off)) { int matchLen = MIN_MATCH + CommonBytes(buf, @ref + MIN_MATCH, off + MIN_MATCH, matchLimit); if (matchLen > match.len) { match.@ref = @ref; match.len = matchLen; } } @ref = Next(@ref); } if (repl != 0) { int ptr = off; int end = off + repl - (MIN_MATCH - 1); while (ptr < end - delta) { chainTable[ptr & MASK] = (short)delta; // pre load ++ptr; } do { chainTable[ptr & MASK] = (short)delta; hashTable[HashHC(ReadInt32(buf, ptr))] = ptr; ++ptr; } while (ptr < end); nextToUpdate = end; } return match.len != 0; } internal bool InsertAndFindWiderMatch(byte[] buf, int off, int startLimit, int matchLimit, int minLen, Match match) { match.len = minLen; Insert(off, buf); int delta = off - startLimit; int @ref = HashPointer(buf, off); for (int i = 0; i < MAX_ATTEMPTS; ++i) { if (@ref < Math.Max(@base, off - MAX_DISTANCE + 1) || @ref > off) { break; } if (buf[@ref - delta + match.len] == buf[startLimit + match.len] && ReadInt32Equals(buf, @ref, off)) { int matchLenForward = MIN_MATCH + CommonBytes(buf, @ref + MIN_MATCH, off + MIN_MATCH, matchLimit); int matchLenBackward = CommonBytesBackward(buf, @ref, off, @base, startLimit); int matchLen = matchLenBackward + matchLenForward; if (matchLen > match.len) { match.len = matchLen; match.@ref = @ref - matchLenBackward; match.start = off - matchLenBackward; } } @ref = Next(@ref); } return match.len > minLen; } } /// <summary> /// Compress <c>bytes[off:off+len]</c> into <paramref name="out"/>. Compared to /// <see cref="LZ4.Compress(byte[], int, int, DataOutput, HashTable)"/>, this method /// is slower and uses more memory (~ 256KB per thread) but should provide /// better compression ratios (especially on large inputs) because it chooses /// the best match among up to 256 candidates and then performs trade-offs to /// fix overlapping matches. <paramref name="ht"/> shouldn't be shared across threads /// but can safely be reused. /// </summary> public static void CompressHC(byte[] src, int srcOff, int srcLen, DataOutput @out, HCHashTable ht) { int srcEnd = srcOff + srcLen; int matchLimit = srcEnd - LAST_LITERALS; int mfLimit = matchLimit - MIN_MATCH; int sOff = srcOff; int anchor = sOff++; ht.Reset(srcOff); Match match0 = new Match(); Match match1 = new Match(); Match match2 = new Match(); Match match3 = new Match(); while (sOff <= mfLimit) { if (!ht.InsertAndFindBestMatch(src, sOff, matchLimit, match1)) { ++sOff; continue; } // saved, in case we would skip too much CopyTo(match1, match0); while (true) { Debug.Assert(match1.start >= anchor); if (match1.End() >= mfLimit || !ht.InsertAndFindWiderMatch(src, match1.End() - 2, match1.start + 1, matchLimit, match1.len, match2)) { // no better match EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out); anchor = sOff = match1.End(); goto mainContinue; } if (match0.start < match1.start) { if (match2.start < match1.start + match0.len) // empirical { CopyTo(match0, match1); } } Debug.Assert(match2.start > match1.start); if (match2.start - match1.start < 3) // First Match too small : removed { CopyTo(match2, match1); goto search2Continue; } while (true) { if (match2.start - match1.start < OPTIMAL_ML) { int newMatchLen = match1.len; if (newMatchLen > OPTIMAL_ML) { newMatchLen = OPTIMAL_ML; } if (match1.start + newMatchLen > match2.End() - MIN_MATCH) { newMatchLen = match2.start - match1.start + match2.len - MIN_MATCH; } int correction = newMatchLen - (match2.start - match1.start); if (correction > 0) { match2.Fix(correction); } } if (match2.start + match2.len >= mfLimit || !ht.InsertAndFindWiderMatch(src, match2.End() - 3, match2.start, matchLimit, match2.len, match3)) { // no better match -> 2 sequences to encode if (match2.start < match1.End()) { match1.len = match2.start - match1.start; } // encode seq 1 EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out); anchor = sOff = match1.End(); // encode seq 2 EncodeSequence(src, anchor, match2.@ref, match2.start, match2.len, @out); anchor = sOff = match2.End(); goto mainContinue; } if (match3.start < match1.End() + 3) // Not enough space for match 2 : remove it { if (match3.start >= match1.End()) // // can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 { if (match2.start < match1.End()) { int correction = match1.End() - match2.start; match2.Fix(correction); if (match2.len < MIN_MATCH) { CopyTo(match3, match2); } } EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out); anchor = sOff = match1.End(); CopyTo(match3, match1); CopyTo(match2, match0); goto search2Continue; } CopyTo(match3, match2); goto search3Continue; } // OK, now we have 3 ascending matches; let's write at least the first one if (match2.start < match1.End()) { if (match2.start - match1.start < 0x0F) { if (match1.len > OPTIMAL_ML) { match1.len = OPTIMAL_ML; } if (match1.End() > match2.End() - MIN_MATCH) { match1.len = match2.End() - match1.start - MIN_MATCH; } int correction = match1.End() - match2.start; match2.Fix(correction); } else { match1.len = match2.start - match1.start; } } EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out); anchor = sOff = match1.End(); CopyTo(match2, match1); CopyTo(match3, match2); goto search3Continue; search3Continue: ; } //search3Break: ; // LUCENENET NOTE: Unreachable search2Continue: ; } //search2Break: ; // LUCENENET NOTE: Not referenced mainContinue: ; } //mainBreak: // LUCENENET NOTE: Not referenced EncodeLastLiterals(src, anchor, srcEnd - anchor, @out); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.GenerateDefaultConstructors; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateDefaultConstructors { public class GenerateDefaultConstructorsTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new GenerateDefaultConstructorsCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestProtectedBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { protected B(int x) { } }", @"class C : B { protected C(int x) : base(x) { } } class B { protected B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPublicBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } class B { public B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestInternalBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPrivateBase() { await TestMissingInRegularAndScriptAsync( @"class C : [||]B { } class B { private B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefOutParams() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(ref int x, out string s, params bool[] b) { } }", @"class C : B { internal C(ref int x, out string s, params bool[] b) : base(ref x, out s, b) { } } class B { internal B(ref int x, out string s, params bool[] b) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { protected C(string x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefactoring1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C(bool x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll_WithTuples() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C((bool, bool) x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", @"class C : B { public C((bool, bool) x) { } protected C((string, string) x) : base(x) { } internal C((int, int) x) : base(x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestMissing1() { await TestMissingInRegularAndScriptAsync( @"class C : [||]B { public C(int x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_1() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C(int y) { } } class B { internal B(int x) { } }", @"class C : B { public C(int y) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_2() { await TestInRegularAndScriptAsync( @"class C : [||]B { private C(int y) { } } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } private C(int y) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixCount1() { await TestActionCountAsync( @"class C : [||]B { } class B { public B(int x) { } }", count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] [WorkItem(544070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544070")] public async Task TestException1() { await TestInRegularAndScriptAsync( @"using System; class Program : Excep[||]tion { }", @"using System; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } }", index: 4, ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException2() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program() { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException3() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException4() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] public async Task Tuple() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B((int, string) x) { } }", @"class C : B { public C((int, string) x) : base(x) { } } class B { public B((int, string) x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] public async Task TupleWithNames() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B((int a, string b) x) { } }", @"class C : B { public C((int a, string b) x) : base(x) { } } class B { public B((int a, string b) x) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass() { await TestInRegularAndScriptAsync( @"class Base { public Base(string value) { } } class [||]Derived : Base { }", @"class Base { public Base(string value) { } } class Derived : Base { public Derived(string value) : base(value) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass2() { await TestInRegularAndScriptAsync( @"class Base { public Base(int a, string value = null) { } } class [||]Derived : Base { }", @"class Base { public Base(int a, string value = null) { } } class Derived : Base { public Derived(int a, string value = null) : base(a, value) { } }"); } } }
/* ==================================================================== 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 System.Collections.ObjectModel; using NPOI.SS.Formula.Function; namespace NPOI.SS.Formula.Atp { using System; using System.Collections; using NPOI.SS.Formula; using NPOI.SS.Formula.Eval; using NPOI.SS.Formula.Functions; using NPOI.SS.Formula.UDF; public class NotImplemented : FreeRefFunction { private String _functionName; public NotImplemented(String functionName) { _functionName = functionName; } public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec) { throw new NotImplementedFunctionException(_functionName); } } public class AnalysisToolPak : UDFFinder { public static UDFFinder instance = new AnalysisToolPak(); private static Dictionary<String, FreeRefFunction> _functionsByName = CreateFunctionsMap(); private AnalysisToolPak() { // no instances of this class } public override FreeRefFunction FindFunction(String name) { // functions that are available in Excel 2007+ have a prefix _xlfn. // if you save such a .xlsx workbook as .xls if (name.StartsWith("_xlfn.")) name = name.Substring(6); string key = name.ToUpper(); if (_functionsByName.ContainsKey(key)) return (FreeRefFunction)_functionsByName[key]; return null; } private static Dictionary<String, FreeRefFunction> CreateFunctionsMap() { Dictionary<String, FreeRefFunction> m = new Dictionary<String, FreeRefFunction>(120); r(m, "ACCRINT", null); r(m, "ACCRINTM", null); r(m, "AMORDEGRC", null); r(m, "AMORLINC", null); r(m, "AVERAGEIF", AverageIf.instance); r(m, "AVERAGEIFS", AverageIfs.instance); r(m, "BAHTTEXT", null); r(m, "BESSELI", null); r(m, "BESSELJ", null); r(m, "BESSELK", null); r(m, "BESSELY", null); r(m, "BIN2DEC", Bin2Dec.instance); r(m, "BIN2HEX", null); r(m, "BIN2OCT", null); r(m, "COMPLEX", Complex.Instance); r(m, "CONVERT", null); r(m, "COUNTIFS", null); r(m, "COUPDAYBS", null); r(m, "COUPDAYS", null); r(m, "COUPDAYSNC", null); r(m, "COUPNCD", null); r(m, "COUPNUM", null); r(m, "COUPPCD", null); r(m, "CUBEKPIMEMBER", null); r(m, "CUBEMEMBER", null); r(m, "CUBEMEMBERPROPERTY", null); r(m, "CUBERANKEDMEMBER", null); r(m, "CUBESET", null); r(m, "CUBESETCOUNT", null); r(m, "CUBEVALUE", null); r(m, "CUMIPMT", null); r(m, "CUMPRINC", null); r(m, "DEC2BIN", Dec2Bin.instance); r(m, "DEC2HEX", Dec2Hex.instance); r(m, "DEC2OCT", null); r(m, "DELTA", Delta.instance); r(m, "DISC", null); r(m, "DOLLARDE", null); r(m, "DOLLARFR", null); r(m, "DURATION", null); r(m, "EDATE", EDate.Instance); r(m, "EFFECT", null); r(m, "EOMONTH", EOMonth.instance); r(m, "ERF", null); r(m, "ERFC", null); r(m, "FACTDOUBLE", FactDouble.instance); r(m, "FVSCHEDULE", null); r(m, "GCD", null); r(m, "GESTEP", null); r(m, "HEX2BIN", null); r(m, "HEX2DEC", Hex2Dec.instance); r(m, "HEX2OCT", null); r(m, "IFERROR", IfError.Instance); r(m, "IMABS", null); r(m, "IMAGINARY", Imaginary.instance); r(m, "IMARGUMENT", null); r(m, "IMCONJUGATE", null); r(m, "IMCOS", null); r(m, "IMDIV", null); r(m, "IMEXP", null); r(m, "IMLN", null); r(m, "IMLOG10", null); r(m, "IMLOG2", null); r(m, "IMPOWER", null); r(m, "IMPRODUCT", null); r(m, "IMREAL", ImReal.instance); r(m, "IMSIN", null); r(m, "IMSQRT", null); r(m, "IMSUB", null); r(m, "IMSUM", null); r(m, "INTRATE", null); r(m, "ISEVEN", ParityFunction.IS_EVEN); r(m, "ISODD", ParityFunction.IS_ODD); r(m, "JIS", null); r(m, "LCM", null); r(m, "MDURATION", null); r(m, "MROUND", MRound.Instance); r(m, "MULTINOMIAL", null); r(m, "NETWORKDAYS", NetworkdaysFunction.instance); r(m, "NOMINAL", null); r(m, "OCT2BIN", null); r(m, "OCT2DEC", Oct2Dec.instance); r(m, "OCT2HEX", null); r(m, "ODDFPRICE", null); r(m, "ODDFYIELD", null); r(m, "ODDLPRICE", null); r(m, "ODDLYIELD", null); r(m, "PRICE", null); r(m, "PRICEDISC", null); r(m, "PRICEMAT", null); r(m, "QUOTIENT", Quotient.instance); r(m, "RANDBETWEEN", RandBetween.Instance); r(m, "RECEIVED", null); r(m, "RTD", null); r(m, "SERIESSUM", null); r(m, "SQRTPI", null); r(m, "SUMIFS", Sumifs.instance); r(m, "TBILLEQ", null); r(m, "TBILLPRICE", null); r(m, "TBILLYIELD", null); r(m, "WEEKNUM", WeekNum.instance); r(m, "WORKDAY", WorkdayFunction.instance); r(m, "XIRR", null); r(m, "XNPV", null); r(m, "YEARFRAC", YearFrac.instance); r(m, "YIELD", null); r(m, "YIELDDISC", null); r(m, "YIELDMAT", null); r(m, "COUNTIFS", Countifs.instance); return m; } private static void r(Dictionary<String, FreeRefFunction> m, String functionName, FreeRefFunction pFunc) { FreeRefFunction func = pFunc == null ? new NotImplemented(functionName) : pFunc; m[functionName]= func; } public static bool IsATPFunction(String name) { //AnalysisToolPak inst = (AnalysisToolPak)instance; return AnalysisToolPak._functionsByName.ContainsKey(name); } /** * Returns a collection of ATP function names implemented by POI. * * @return an array of supported functions * @since 3.8 beta6 */ public static ReadOnlyCollection<String> GetSupportedFunctionNames() { AnalysisToolPak inst = (AnalysisToolPak)instance; List<String> lst = new List<String>(); foreach (KeyValuePair<String, FreeRefFunction> me in AnalysisToolPak._functionsByName) { FreeRefFunction func = me.Value; if (func != null && !(func is NotImplemented)) { lst.Add(me.Key); } } return lst.AsReadOnly(); //Collections.unmodifiableCollection(lst); } /** * Returns a collection of ATP function names NOT implemented by POI. * * @return an array of not supported functions * @since 3.8 beta6 */ public static ReadOnlyCollection<String> GetNotSupportedFunctionNames() { AnalysisToolPak inst = (AnalysisToolPak)instance; List<String> lst = new List<String>(); foreach (KeyValuePair<String, FreeRefFunction> me in AnalysisToolPak._functionsByName) { FreeRefFunction func = me.Value; if (func != null && (func is NotImplemented)) { lst.Add(me.Key); } } return lst.AsReadOnly(); //Collections.unmodifiableCollection(lst); } /** * Register a ATP function in runtime. * * @param name the function name * @param func the functoin to register * @throws ArgumentException if the function is unknown or already registered. * @since 3.8 beta6 */ public static void RegisterFunction(String name, FreeRefFunction func) { AnalysisToolPak inst = (AnalysisToolPak)instance; if (!IsATPFunction(name)) { FunctionMetadata metaData = FunctionMetadataRegistry.GetFunctionByName(name); if (metaData != null) { throw new ArgumentException(name + " is a built-in Excel function. " + "Use FunctoinEval.RegisterFunction(String name, Function func) instead."); } else { throw new ArgumentException(name + " is not a function from the Excel Analysis Toolpack."); } } FreeRefFunction f = inst.FindFunction(name); if (f != null && !(f is NotImplemented)) { throw new ArgumentException("POI already implememts " + name + ". You cannot override POI's implementations of Excel functions"); } if (_functionsByName.ContainsKey(name)) _functionsByName[name] = func; else _functionsByName.Add(name, func); } } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.3.12.11: reports the occurance of a significatnt event to the simulation manager. Needs manual intervention to fix padding in variable datums. UNFINISHED. /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(FixedDatum))] [XmlInclude(typeof(VariableDatum))] public partial class EventReportReliablePdu : SimulationManagementWithReliabilityFamilyPdu, IEquatable<EventReportReliablePdu> { /// <summary> /// Event type /// </summary> private ushort _eventType; /// <summary> /// padding /// </summary> private uint _pad1; /// <summary> /// Fixed datum record count /// </summary> private uint _numberOfFixedDatumRecords; /// <summary> /// variable datum record count /// </summary> private uint _numberOfVariableDatumRecords; /// <summary> /// Fixed datum records /// </summary> private List<FixedDatum> _fixedDatumRecords = new List<FixedDatum>(); /// <summary> /// Variable datum records /// </summary> private List<VariableDatum> _variableDatumRecords = new List<VariableDatum>(); /// <summary> /// Initializes a new instance of the <see cref="EventReportReliablePdu"/> class. /// </summary> public EventReportReliablePdu() { PduType = (byte)61; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(EventReportReliablePdu left, EventReportReliablePdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(EventReportReliablePdu left, EventReportReliablePdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += 2; // this._eventType marshalSize += 4; // this._pad1 marshalSize += 4; // this._numberOfFixedDatumRecords marshalSize += 4; // this._numberOfVariableDatumRecords for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++) { FixedDatum listElement = (FixedDatum)this._fixedDatumRecords[idx]; marshalSize += listElement.GetMarshalledSize(); } for (int idx = 0; idx < this._variableDatumRecords.Count; idx++) { VariableDatum listElement = (VariableDatum)this._variableDatumRecords[idx]; marshalSize += listElement.GetMarshalledSize(); } return marshalSize; } /// <summary> /// Gets or sets the Event type /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "eventType")] public ushort EventType { get { return this._eventType; } set { this._eventType = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(uint), ElementName = "pad1")] public uint Pad1 { get { return this._pad1; } set { this._pad1 = value; } } /// <summary> /// Gets or sets the Fixed datum record count /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfFixedDatumRecords method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "numberOfFixedDatumRecords")] public uint NumberOfFixedDatumRecords { get { return this._numberOfFixedDatumRecords; } set { this._numberOfFixedDatumRecords = value; } } /// <summary> /// Gets or sets the variable datum record count /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfVariableDatumRecords method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "numberOfVariableDatumRecords")] public uint NumberOfVariableDatumRecords { get { return this._numberOfVariableDatumRecords; } set { this._numberOfVariableDatumRecords = value; } } /// <summary> /// Gets the Fixed datum records /// </summary> [XmlElement(ElementName = "fixedDatumRecordsList", Type = typeof(List<FixedDatum>))] public List<FixedDatum> FixedDatumRecords { get { return this._fixedDatumRecords; } } /// <summary> /// Gets the Variable datum records /// </summary> [XmlElement(ElementName = "variableDatumRecordsList", Type = typeof(List<VariableDatum>))] public List<VariableDatum> VariableDatumRecords { get { return this._variableDatumRecords; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { dos.WriteUnsignedShort((ushort)this._eventType); dos.WriteUnsignedInt((uint)this._pad1); dos.WriteUnsignedInt((uint)this._fixedDatumRecords.Count); dos.WriteUnsignedInt((uint)this._variableDatumRecords.Count); for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++) { FixedDatum aFixedDatum = (FixedDatum)this._fixedDatumRecords[idx]; aFixedDatum.Marshal(dos); } for (int idx = 0; idx < this._variableDatumRecords.Count; idx++) { VariableDatum aVariableDatum = (VariableDatum)this._variableDatumRecords[idx]; aVariableDatum.Marshal(dos); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._eventType = dis.ReadUnsignedShort(); this._pad1 = dis.ReadUnsignedInt(); this._numberOfFixedDatumRecords = dis.ReadUnsignedInt(); this._numberOfVariableDatumRecords = dis.ReadUnsignedInt(); for (int idx = 0; idx < this.NumberOfFixedDatumRecords; idx++) { FixedDatum anX = new FixedDatum(); anX.Unmarshal(dis); this._fixedDatumRecords.Add(anX); } for (int idx = 0; idx < this.NumberOfVariableDatumRecords; idx++) { VariableDatum anX = new VariableDatum(); anX.Unmarshal(dis); this._variableDatumRecords.Add(anX); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<EventReportReliablePdu>"); base.Reflection(sb); try { sb.AppendLine("<eventType type=\"ushort\">" + this._eventType.ToString(CultureInfo.InvariantCulture) + "</eventType>"); sb.AppendLine("<pad1 type=\"uint\">" + this._pad1.ToString(CultureInfo.InvariantCulture) + "</pad1>"); sb.AppendLine("<fixedDatumRecords type=\"uint\">" + this._fixedDatumRecords.Count.ToString(CultureInfo.InvariantCulture) + "</fixedDatumRecords>"); sb.AppendLine("<variableDatumRecords type=\"uint\">" + this._variableDatumRecords.Count.ToString(CultureInfo.InvariantCulture) + "</variableDatumRecords>"); for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++) { sb.AppendLine("<fixedDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"FixedDatum\">"); FixedDatum aFixedDatum = (FixedDatum)this._fixedDatumRecords[idx]; aFixedDatum.Reflection(sb); sb.AppendLine("</fixedDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } for (int idx = 0; idx < this._variableDatumRecords.Count; idx++) { sb.AppendLine("<variableDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"VariableDatum\">"); VariableDatum aVariableDatum = (VariableDatum)this._variableDatumRecords[idx]; aVariableDatum.Reflection(sb); sb.AppendLine("</variableDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</EventReportReliablePdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</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) { return this == obj as EventReportReliablePdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(EventReportReliablePdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (this._eventType != obj._eventType) { ivarsEqual = false; } if (this._pad1 != obj._pad1) { ivarsEqual = false; } if (this._numberOfFixedDatumRecords != obj._numberOfFixedDatumRecords) { ivarsEqual = false; } if (this._numberOfVariableDatumRecords != obj._numberOfVariableDatumRecords) { ivarsEqual = false; } if (this._fixedDatumRecords.Count != obj._fixedDatumRecords.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++) { if (!this._fixedDatumRecords[idx].Equals(obj._fixedDatumRecords[idx])) { ivarsEqual = false; } } } if (this._variableDatumRecords.Count != obj._variableDatumRecords.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._variableDatumRecords.Count; idx++) { if (!this._variableDatumRecords[idx].Equals(obj._variableDatumRecords[idx])) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._eventType.GetHashCode(); result = GenerateHash(result) ^ this._pad1.GetHashCode(); result = GenerateHash(result) ^ this._numberOfFixedDatumRecords.GetHashCode(); result = GenerateHash(result) ^ this._numberOfVariableDatumRecords.GetHashCode(); if (this._fixedDatumRecords.Count > 0) { for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++) { result = GenerateHash(result) ^ this._fixedDatumRecords[idx].GetHashCode(); } } if (this._variableDatumRecords.Count > 0) { for (int idx = 0; idx < this._variableDatumRecords.Count; idx++) { result = GenerateHash(result) ^ this._variableDatumRecords[idx].GetHashCode(); } } return result; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Windows; using System.Windows.Controls; namespace Microsoft.Management.UI.Internal { /// <summary> /// Allows the state of the ManagementList to be saved and restored. /// </summary> [Serializable] [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class ManagementListStateDescriptor : StateDescriptor<ManagementList> { #region Fields private Dictionary<string, ColumnStateDescriptor> columns = new Dictionary<string, ColumnStateDescriptor>(); private string searchBoxText; private List<RuleStateDescriptor> rulesSelected = new List<RuleStateDescriptor>(); private string sortOrderPropertyName; #endregion Fields #region Constructors /// <summary> /// Constructs a new instance of the ManagementListStateDescriptor class. /// </summary> public ManagementListStateDescriptor() : base() { // empty } /// <summary> /// Constructs a new instance of the ManagementListStateDescriptor class. /// </summary> /// <param name="name">The name that will be displayed to users.</param> public ManagementListStateDescriptor(string name) : base(name) { // empty } #endregion Constructors #region Save/Restore /// <summary> /// Saves a snapshot of the ManagementList state. /// </summary> /// <param name="subject"> /// The ManagementList instance whose state should be preserved. /// </param> /// <remarks> /// Columns will not be saved if not supported per /// <see cref="VerifyColumnsSavable"/>. /// </remarks> /// <exception cref="InvalidOperationException"> /// ManagementList.AutoGenerateColumns not supported. /// </exception> public override void SaveState(ManagementList subject) { if (subject == null) { throw new ArgumentNullException("subject"); } this.SaveColumns(subject); this.SaveSortOrder(subject); this.SaveRulesSelected(subject); } /// <summary> /// Restores the state of the passed in ManagementList and applies the restored filter. /// </summary> /// <param name="subject">The ManagementList instance whose state should be restored.</param> public override void RestoreState(ManagementList subject) { this.RestoreState(subject, true); } /// <summary> /// Restores the state of the passed in ManagementList. /// </summary> /// <param name="subject"> /// The ManagementList instance whose state should be restored. /// </param> /// <param name="applyRestoredFilter"> /// Whether the restored filter should be automatically applied. /// </param> /// <remarks> /// Columns will not be restored if not supported per /// <see cref="VerifyColumnsRestorable"/>. /// </remarks> /// <exception cref="InvalidOperationException"> /// ManagementList.AutoGenerateColumns not supported. /// </exception> public void RestoreState(ManagementList subject, bool applyRestoredFilter) { if (subject == null) { throw new ArgumentNullException("subject"); } // Clear the sort, otherwise restoring columns and filters may trigger extra sorting \\ subject.List.ClearSort(); this.RestoreColumns(subject); this.RestoreRulesSelected(subject); if (applyRestoredFilter) { subject.Evaluator.StartFilter(); } // Apply sorting after everything else has been set up \\ this.RestoreSortOrder(subject); } #region Verify State Helpers private static bool VerifyColumnsSavable(ManagementList subject, RetryActionCallback<ManagementList> callback) { if (!VerifyColumnsRestorable(subject, callback)) { return false; } if (subject.List.InnerGrid == null) { return false; } return true; } /// <summary> /// Checks whether columns can be restored. /// </summary> /// <param name="subject">Target ManagementList.</param> /// <param name="callback">RetryActionAfterLoaded callback method.</param> /// <returns>True iff columns restorable.</returns> /// <exception cref="InvalidOperationException"> /// ManagementList.AutoGenerateColumns not supported. /// </exception> private static bool VerifyColumnsRestorable(ManagementList subject, RetryActionCallback<ManagementList> callback) { if (WpfHelp.RetryActionAfterLoaded<ManagementList>(subject, callback, subject)) { return false; } if (WpfHelp.RetryActionAfterLoaded<ManagementList>(subject.List, callback, subject)) { return false; } if (subject.List == null) { return false; } // Columns are not savable/restorable if AutoGenerateColumns is true. if (subject.List.AutoGenerateColumns) { throw new InvalidOperationException("View Manager is not supported when AutoGenerateColumns is set."); } return true; } private static bool VerifyRulesSavableAndRestorable(ManagementList subject, RetryActionCallback<ManagementList> callback) { if (WpfHelp.RetryActionAfterLoaded<ManagementList>(subject, callback, subject)) { return false; } if (subject.AddFilterRulePicker == null) { return false; } if (subject.FilterRulePanel == null) { return false; } if (subject.SearchBox == null) { return false; } return true; } #endregion Verify State Helpers #region Save/Restore Helpers #region Columns private void SaveColumns(ManagementList subject) { if (!VerifyColumnsSavable(subject, this.SaveColumns)) { return; } this.columns.Clear(); int i = 0; foreach (InnerListColumn ilc in subject.List.InnerGrid.Columns) { ColumnStateDescriptor csd = CreateColumnStateDescriptor(ilc, true); csd.Index = i++; this.columns.Add(ilc.DataDescription.PropertyName, csd); } foreach (InnerListColumn ilc in subject.List.InnerGrid.AvailableColumns) { if (subject.List.InnerGrid.Columns.Contains(ilc)) { continue; } ColumnStateDescriptor csd = CreateColumnStateDescriptor(ilc, false); csd.Index = i++; this.columns.Add(ilc.DataDescription.PropertyName, csd); } } private void RestoreColumns(ManagementList subject) { if (!VerifyColumnsRestorable(subject, this.RestoreColumns)) { return; } this.RestoreColumnsState(subject); this.RestoreColumnsOrder(subject); subject.List.RefreshColumns(); } /// <summary> /// Set column state for target <see cref="ManagementList"/> to /// previously persisted state. /// </summary> /// <param name="subject"> /// Target <see cref="ManagementList"/> whose column state /// is to be restored. /// </param> /// <remarks> /// Required columns are always visible regardless of persisted state. /// </remarks> private void RestoreColumnsState(ManagementList subject) { ColumnStateDescriptor csd; foreach (InnerListColumn ilc in subject.List.Columns) { if (this.columns.TryGetValue(ilc.DataDescription.PropertyName, out csd)) { SetColumnSortDirection(ilc, csd.SortDirection); SetColumnIsInUse(ilc, csd.IsInUse || ilc.Required); SetColumnWidth(ilc, csd.Width); } else { SetColumnIsInUse(ilc, ilc.Required); } } } private void RestoreColumnsOrder(ManagementList subject) { // Restore the order of Columns // Use the sorted copy to determine what values to swap List<InnerListColumn> columnsCopy = new List<InnerListColumn>(subject.List.Columns); InnerListColumnOrderComparer ilcc = new InnerListColumnOrderComparer(this.columns); columnsCopy.Sort(ilcc); Debug.Assert(columnsCopy.Count == subject.List.Columns.Count, "match count"); Utilities.ResortObservableCollection<InnerListColumn>( subject.List.Columns, columnsCopy); // Restore the order of InnerGrid.Columns // Use the sorted copy to determine what values to swap columnsCopy.Clear(); foreach (GridViewColumn gvc in subject.List.InnerGrid.Columns) { columnsCopy.Add((InnerListColumn)gvc); } columnsCopy.Sort(ilcc); Debug.Assert(columnsCopy.Count == subject.List.InnerGrid.Columns.Count, "match count"); Utilities.ResortObservableCollection<GridViewColumn>( subject.List.InnerGrid.Columns, columnsCopy); } #endregion Columns #region Rules private void SaveRulesSelected(ManagementList subject) { if (!VerifyRulesSavableAndRestorable(subject, this.SaveRulesSelected)) { return; } this.rulesSelected.Clear(); this.searchBoxText = subject.SearchBox.Text; foreach (FilterRulePanelItem item in subject.FilterRulePanel.FilterRulePanelItems) { RuleStateDescriptor rsd = new RuleStateDescriptor(); rsd.UniqueName = item.GroupId; rsd.Rule = item.Rule.DeepCopy(); this.rulesSelected.Add(rsd); } } private void RestoreRulesSelected(ManagementList subject) { if (!VerifyRulesSavableAndRestorable(subject, this.RestoreRulesSelected)) { return; } subject.Evaluator.StopFilter(); subject.SearchBox.Text = this.searchBoxText; this.AddSelectedRules(subject); } private void AddSelectedRules(ManagementList subject) { // Cache values Dictionary<string, FilterRulePanelItem> rulesCache = new Dictionary<string, FilterRulePanelItem>(); foreach (AddFilterRulePickerItem pickerItem in subject.AddFilterRulePicker.ShortcutFilterRules) { rulesCache.Add(pickerItem.FilterRule.GroupId, pickerItem.FilterRule); } foreach (AddFilterRulePickerItem pickerItem in subject.AddFilterRulePicker.ColumnFilterRules) { rulesCache.Add(pickerItem.FilterRule.GroupId, pickerItem.FilterRule); } subject.FilterRulePanel.Controller.ClearFilterRulePanelItems(); foreach (RuleStateDescriptor rsd in this.rulesSelected) { AddSelectedRule(subject, rsd, rulesCache); } } private static void AddSelectedRule(ManagementList subject, RuleStateDescriptor rsd, Dictionary<string, FilterRulePanelItem> rulesCache) { FilterRulePanelItem item; if (rulesCache.TryGetValue(rsd.UniqueName, out item)) { subject.FilterRulePanel.Controller.AddFilterRulePanelItem(new FilterRulePanelItem(rsd.Rule.DeepCopy(), item.GroupId)); } } #endregion Rules #region Sort Order private void SaveSortOrder(ManagementList subject) { if (!VerifyColumnsRestorable(subject, this.SaveSortOrder)) { return; } // NOTE : We only support sorting on one property. if (subject.List.SortedColumn != null) { this.sortOrderPropertyName = subject.List.SortedColumn.DataDescription.PropertyName; } else { this.sortOrderPropertyName = string.Empty; } } private void RestoreSortOrder(ManagementList subject) { if (!VerifyColumnsRestorable(subject, this.RestoreSortOrder)) { return; } subject.List.ClearSort(); if (!string.IsNullOrEmpty(this.sortOrderPropertyName)) { foreach (InnerListColumn column in subject.List.Columns) { if (column.DataDescription.PropertyName == this.sortOrderPropertyName) { subject.List.ApplySort(column, false); break; } } } } #endregion Sort Order #endregion Save/Restore Helpers #region Column Helpers private static ColumnStateDescriptor CreateColumnStateDescriptor(InnerListColumn ilc, bool isInUse) { ColumnStateDescriptor csd = new ColumnStateDescriptor(); csd.IsInUse = isInUse; csd.Width = GetColumnWidth(ilc); csd.SortDirection = ilc.DataDescription.SortDirection; return csd; } #region SortDirection private static void SetColumnSortDirection(InnerListColumn ilc, ListSortDirection sortDirection) { ilc.DataDescription.SortDirection = sortDirection; } #endregion IsInUse #region IsInUse private static void SetColumnIsInUse(InnerListColumn ilc, bool isInUse) { ilc.Visible = isInUse; } #endregion IsInUse #region Width private static double GetColumnWidth(InnerListColumn ilc) { return ilc.Visible ? ilc.ActualWidth : ilc.Width; } private static void SetColumnWidth(GridViewColumn ilc, double width) { if (!double.IsNaN(width)) { ilc.Width = width; } } #endregion Width #endregion Column Helpers #endregion Save/Restore #region Helper Classes [Serializable] internal class ColumnStateDescriptor { private int index; private bool isInUse; private ListSortDirection sortDirection; private double width; /// <summary> /// Gets or sets the location of the column. /// </summary> public int Index { get { return this.index; } set { this.index = value; } } /// <summary> /// Gets or sets a value indicating whether the column should be shown. /// </summary> public bool IsInUse { get { return this.isInUse; } set { this.isInUse = value; } } /// <summary> /// Gets or sets the sort direction of the column. /// </summary> public ListSortDirection SortDirection { get { return this.sortDirection; } set { this.sortDirection = value; } } /// <summary> /// Gets or sets a value indicating the width of a column. /// </summary> public double Width { get { return this.width; } set { this.width = value; } } } [Serializable] internal class RuleStateDescriptor { /// <summary> /// Gets or sets the UniqueName associated with the rule. /// </summary> public string UniqueName { get; set; } /// <summary> /// Gets the FilterRule associated with the rule. /// </summary> public FilterRule Rule { get; set; } } internal class InnerListColumnOrderComparer : IComparer<InnerListColumn> { private Dictionary<string, ColumnStateDescriptor> columns; /// <summary> /// Constructor that takes a lookup dictionary of column information. /// </summary> /// <param name="columns">The lookup dictionary.</param> public InnerListColumnOrderComparer(Dictionary<string, ColumnStateDescriptor> columns) { this.columns = columns; } /// <summary> /// Compares two InnerListColumn objects and determines their relative /// ordering. /// </summary> /// <param name="x">The first object.</param> /// <param name="y">The second object.</param> /// <returns> /// Returns 1 if x should ordered after y in the list, returns -1 if /// x should be order before y, and returns 0 if the ordering should not /// be changed. /// </returns> public int Compare(InnerListColumn x, InnerListColumn y) { if (ReferenceEquals(x, y)) { return 0; } else if (x == null) { return -1; } else if (y == null) { return 1; } ColumnStateDescriptor csdX; ColumnStateDescriptor csdY; this.columns.TryGetValue(x.DataDescription.PropertyName, out csdX); this.columns.TryGetValue(y.DataDescription.PropertyName, out csdY); if (csdX == null || csdY == null || (csdX.IsInUse && csdX.IsInUse) == false) { return 0; } return (csdX.Index > csdY.Index) ? 1 : -1; } } #endregion Helper Classes #region ToString /// <summary> /// Displayable string identifying this class instance. /// </summary> /// <returns>A string to represent the instance of this class.</returns> public override string ToString() { return this.Name; } #endregion ToString } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Server.Base; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalGridServicesConnector")] public class LocalGridServicesConnector : ISharedRegionModule, IGridService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[LOCAL GRID SERVICE CONNECTOR]"; private IGridService m_GridService; private Dictionary<UUID, RegionCache> m_LocalCache = new Dictionary<UUID, RegionCache>(); private bool m_Enabled; public LocalGridServicesConnector() { m_log.DebugFormat("{0} LocalGridServicesConnector no parms.", LogHeader); } public LocalGridServicesConnector(IConfigSource source) { m_log.DebugFormat("{0} LocalGridServicesConnector instantiated directly.", LogHeader); InitialiseService(source); } #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public string Name { get { return "LocalGridServicesConnector"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("GridServices", ""); if (name == Name) { InitialiseService(source); m_log.Info("[LOCAL GRID SERVICE CONNECTOR]: Local grid connector enabled"); } } } private void InitialiseService(IConfigSource source) { IConfig config = source.Configs["GridService"]; if (config == null) { m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: GridService missing from OpenSim.ini"); return; } string serviceDll = config.GetString("LocalServiceModule", String.Empty); if (serviceDll == String.Empty) { m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: No LocalServiceModule named in section GridService"); return; } Object[] args = new Object[] { source }; m_GridService = ServerUtils.LoadPlugin<IGridService>(serviceDll, args); if (m_GridService == null) { m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: Can't load grid service"); return; } m_Enabled = true; } public void PostInitialise() { // FIXME: We will still add this command even if we aren't enabled since RemoteGridServiceConnector // will have instantiated us directly. MainConsole.Instance.Commands.AddCommand("Regions", false, "show neighbours", "show neighbours", "Shows the local regions' neighbours", HandleShowNeighboursCommand); } public void Close() { } public void AddRegion(Scene scene) { if (!m_Enabled) return; scene.RegisterModuleInterface<IGridService>(this); lock (m_LocalCache) { if (m_LocalCache.ContainsKey(scene.RegionInfo.RegionID)) m_log.ErrorFormat("[LOCAL GRID SERVICE CONNECTOR]: simulator seems to have more than one region with the same UUID. Please correct this!"); else m_LocalCache.Add(scene.RegionInfo.RegionID, new RegionCache(scene)); } } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; lock (m_LocalCache) { m_LocalCache[scene.RegionInfo.RegionID].Clear(); m_LocalCache.Remove(scene.RegionInfo.RegionID); } } public void RegionLoaded(Scene scene) { } #endregion #region IGridService public string RegisterRegion(UUID scopeID, GridRegion regionInfo) { return m_GridService.RegisterRegion(scopeID, regionInfo); } public bool DeregisterRegion(UUID regionID) { return m_GridService.DeregisterRegion(regionID); } public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) { return m_GridService.GetNeighbours(scopeID, regionID); } public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) { return m_GridService.GetRegionByUUID(scopeID, regionID); } // Get a region given its base coordinates. // NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST // be the base coordinate of the region. public GridRegion GetRegionByPosition(UUID scopeID, int x, int y) { GridRegion region = null; uint regionX = Util.WorldToRegionLoc((uint)x); uint regionY = Util.WorldToRegionLoc((uint)y); // Sanity check if ((Util.RegionToWorldLoc(regionX) != (uint)x) || (Util.RegionToWorldLoc(regionY) != (uint)y)) { m_log.WarnFormat("{0} GetRegionByPosition. Bad position requested: not the base of the region. Requested Pos=<{1},{2}>, Should Be=<{3},{4}>", LogHeader, x, y, Util.RegionToWorldLoc(regionX), Util.RegionToWorldLoc(regionY)); } // First see if it's a neighbour, even if it isn't on this sim. // Neighbour data is cached in memory, so this is fast lock (m_LocalCache) { foreach (RegionCache rcache in m_LocalCache.Values) { region = rcache.GetRegionByPosition(x, y); if (region != null) { m_log.DebugFormat("{0} GetRegionByPosition. Found region {1} in cache (of region {2}). Pos=<{3},{4}>", LogHeader, region.RegionName, Util.WorldToRegionLoc((uint)region.RegionLocX), Util.WorldToRegionLoc((uint)region.RegionLocY)); break; } } } // Then try on this sim (may be a lookup in DB if this is using MySql). if (region == null) { region = m_GridService.GetRegionByPosition(scopeID, x, y); if (region == null) { m_log.DebugFormat("{0} GetRegionByPosition. Region not found by grid service. Pos=<{1},{2}>", LogHeader, regionX, regionY); } else { m_log.DebugFormat("{0} GetRegionByPosition. Got region {1} from grid service. Pos=<{2},{3}>", LogHeader, region.RegionName, Util.WorldToRegionLoc((uint)region.RegionLocX), Util.WorldToRegionLoc((uint)region.RegionLocY)); } } return region; } public GridRegion GetRegionByName(UUID scopeID, string regionName) { return m_GridService.GetRegionByName(scopeID, regionName); } public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber) { return m_GridService.GetRegionsByName(scopeID, name, maxNumber); } public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) { return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); } public List<GridRegion> GetDefaultRegions(UUID scopeID) { return m_GridService.GetDefaultRegions(scopeID); } public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID) { return m_GridService.GetDefaultHypergridRegions(scopeID); } public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y) { return m_GridService.GetFallbackRegions(scopeID, x, y); } public List<GridRegion> GetHyperlinks(UUID scopeID) { return m_GridService.GetHyperlinks(scopeID); } public int GetRegionFlags(UUID scopeID, UUID regionID) { return m_GridService.GetRegionFlags(scopeID, regionID); } public Dictionary<string, object> GetExtraFeatures() { return m_GridService.GetExtraFeatures(); } #endregion public void HandleShowNeighboursCommand(string module, string[] cmdparams) { System.Text.StringBuilder caps = new System.Text.StringBuilder(); lock (m_LocalCache) { foreach (KeyValuePair<UUID, RegionCache> kvp in m_LocalCache) { caps.AppendFormat("*** Neighbours of {0} ({1}) ***\n", kvp.Value.RegionName, kvp.Key); List<GridRegion> regions = kvp.Value.GetNeighbours(); foreach (GridRegion r in regions) caps.AppendFormat(" {0} @ {1}-{2}\n", r.RegionName, Util.WorldToRegionLoc((uint)r.RegionLocX), Util.WorldToRegionLoc((uint)r.RegionLocY)); } } MainConsole.Instance.Output(caps.ToString()); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Serialization; using Microsoft.Xrm.Sdk; namespace PowerShellLibrary.Crm.CmdletProviders { [DataContract] [GeneratedCode("CrmSvcUtil", "7.1.0001.3108")] [Microsoft.Xrm.Sdk.Client.EntityLogicalName("workflow")] public class Workflow : Entity, INotifyPropertyChanging, INotifyPropertyChanged { public const string EntityLogicalName = "workflow"; public const int EntityTypeCode = 4703; [AttributeLogicalName("activeworkflowid")] public EntityReference ActiveWorkflowId { get { return this.GetAttributeValue<EntityReference>("activeworkflowid"); } } [AttributeLogicalName("asyncautodelete")] public bool? AsyncAutoDelete { get { return this.GetAttributeValue<bool?>("asyncautodelete"); } set { this.OnPropertyChanging("AsyncAutoDelete"); this.SetAttributeValue("asyncautodelete", (object) value); this.OnPropertyChanged("AsyncAutoDelete"); } } [AttributeLogicalName("businessprocesstype")] public OptionSetValue BusinessProcessType { get { return this.GetAttributeValue<OptionSetValue>("businessprocesstype"); } set { this.OnPropertyChanging("BusinessProcessType"); this.SetAttributeValue("businessprocesstype", (object) value); this.OnPropertyChanged("BusinessProcessType"); } } [AttributeLogicalName("category")] public OptionSetValue Category { get { return this.GetAttributeValue<OptionSetValue>("category"); } set { this.OnPropertyChanging("Category"); this.SetAttributeValue("category", (object) value); this.OnPropertyChanged("Category"); } } [AttributeLogicalName("clientdata")] public string ClientData { get { return this.GetAttributeValue<string>("clientdata"); } } [AttributeLogicalName("componentstate")] public OptionSetValue ComponentState { get { return this.GetAttributeValue<OptionSetValue>("componentstate"); } } [AttributeLogicalName("createdby")] public EntityReference CreatedBy { get { return this.GetAttributeValue<EntityReference>("createdby"); } } [AttributeLogicalName("createdon")] public DateTime? CreatedOn { get { return this.GetAttributeValue<DateTime?>("createdon"); } } [AttributeLogicalName("createdonbehalfby")] public EntityReference CreatedOnBehalfBy { get { return this.GetAttributeValue<EntityReference>("createdonbehalfby"); } } [AttributeLogicalName("createstage")] public OptionSetValue CreateStage { get { return this.GetAttributeValue<OptionSetValue>("createstage"); } set { this.OnPropertyChanging("CreateStage"); this.SetAttributeValue("createstage", (object) value); this.OnPropertyChanged("CreateStage"); } } [AttributeLogicalName("deletestage")] public OptionSetValue DeleteStage { get { return this.GetAttributeValue<OptionSetValue>("deletestage"); } set { this.OnPropertyChanging("DeleteStage"); this.SetAttributeValue("deletestage", (object) value); this.OnPropertyChanged("DeleteStage"); } } [AttributeLogicalName("description")] public string Description { get { return this.GetAttributeValue<string>("description"); } set { this.OnPropertyChanging("Description"); this.SetAttributeValue("description", (object) value); this.OnPropertyChanged("Description"); } } [AttributeLogicalName("entityimage")] public byte[] EntityImage { get { return this.GetAttributeValue<byte[]>("entityimage"); } set { this.OnPropertyChanging("EntityImage"); this.SetAttributeValue("entityimage", (object) value); this.OnPropertyChanged("EntityImage"); } } [AttributeLogicalName("entityimage_timestamp")] public long? EntityImage_Timestamp { get { return this.GetAttributeValue<long?>("entityimage_timestamp"); } } [AttributeLogicalName("entityimage_url")] public string EntityImage_URL { get { return this.GetAttributeValue<string>("entityimage_url"); } } [AttributeLogicalName("entityimageid")] public Guid? EntityImageId { get { return this.GetAttributeValue<Guid?>("entityimageid"); } } [AttributeLogicalName("formid")] public Guid? FormId { get { return this.GetAttributeValue<Guid?>("formid"); } set { this.OnPropertyChanging("FormId"); this.SetAttributeValue("formid", (object) value); this.OnPropertyChanged("FormId"); } } [AttributeLogicalName("inputparameters")] public string InputParameters { get { return this.GetAttributeValue<string>("inputparameters"); } set { this.OnPropertyChanging("InputParameters"); this.SetAttributeValue("inputparameters", (object) value); this.OnPropertyChanged("InputParameters"); } } [AttributeLogicalName("introducedversion")] public string IntroducedVersion { get { return this.GetAttributeValue<string>("introducedversion"); } set { this.OnPropertyChanging("IntroducedVersion"); this.SetAttributeValue("introducedversion", (object) value); this.OnPropertyChanged("IntroducedVersion"); } } [AttributeLogicalName("iscrmuiworkflow")] public bool? IsCrmUIWorkflow { get { return this.GetAttributeValue<bool?>("iscrmuiworkflow"); } } [AttributeLogicalName("iscustomizable")] public BooleanManagedProperty IsCustomizable { get { return this.GetAttributeValue<BooleanManagedProperty>("iscustomizable"); } set { this.OnPropertyChanging("IsCustomizable"); this.SetAttributeValue("iscustomizable", (object) value); this.OnPropertyChanged("IsCustomizable"); } } [AttributeLogicalName("ismanaged")] public bool? IsManaged { get { return this.GetAttributeValue<bool?>("ismanaged"); } } [AttributeLogicalName("istransacted")] public bool? IsTransacted { get { return this.GetAttributeValue<bool?>("istransacted"); } set { this.OnPropertyChanging("IsTransacted"); this.SetAttributeValue("istransacted", (object) value); this.OnPropertyChanged("IsTransacted"); } } [AttributeLogicalName("languagecode")] public int? LanguageCode { get { return this.GetAttributeValue<int?>("languagecode"); } set { this.OnPropertyChanging("LanguageCode"); this.SetAttributeValue("languagecode", (object) value); this.OnPropertyChanged("LanguageCode"); } } [AttributeLogicalName("mode")] public OptionSetValue Mode { get { return this.GetAttributeValue<OptionSetValue>("mode"); } set { this.OnPropertyChanging("Mode"); this.SetAttributeValue("mode", (object) value); this.OnPropertyChanged("Mode"); } } [AttributeLogicalName("modifiedby")] public EntityReference ModifiedBy { get { return this.GetAttributeValue<EntityReference>("modifiedby"); } } [AttributeLogicalName("modifiedon")] public DateTime? ModifiedOn { get { return this.GetAttributeValue<DateTime?>("modifiedon"); } } [AttributeLogicalName("modifiedonbehalfby")] public EntityReference ModifiedOnBehalfBy { get { return this.GetAttributeValue<EntityReference>("modifiedonbehalfby"); } } [AttributeLogicalName("name")] public string Name { get { return this.GetAttributeValue<string>("name"); } set { this.OnPropertyChanging("Name"); this.SetAttributeValue("name", (object) value); this.OnPropertyChanged("Name"); } } [AttributeLogicalName("ondemand")] public bool? OnDemand { get { return this.GetAttributeValue<bool?>("ondemand"); } set { this.OnPropertyChanging("OnDemand"); this.SetAttributeValue("ondemand", (object) value); this.OnPropertyChanged("OnDemand"); } } [AttributeLogicalName("overwritetime")] public DateTime? OverwriteTime { get { return this.GetAttributeValue<DateTime?>("overwritetime"); } } [AttributeLogicalName("ownerid")] public EntityReference OwnerId { get { return this.GetAttributeValue<EntityReference>("ownerid"); } set { this.OnPropertyChanging("OwnerId"); this.SetAttributeValue("ownerid", (object) value); this.OnPropertyChanged("OwnerId"); } } [AttributeLogicalName("owningbusinessunit")] public EntityReference OwningBusinessUnit { get { return this.GetAttributeValue<EntityReference>("owningbusinessunit"); } } [AttributeLogicalName("owningteam")] public EntityReference OwningTeam { get { return this.GetAttributeValue<EntityReference>("owningteam"); } } [AttributeLogicalName("owninguser")] public EntityReference OwningUser { get { return this.GetAttributeValue<EntityReference>("owninguser"); } } [AttributeLogicalName("parentworkflowid")] public EntityReference ParentWorkflowId { get { return this.GetAttributeValue<EntityReference>("parentworkflowid"); } } [AttributeLogicalName("plugintypeid")] public EntityReference PluginTypeId { get { return this.GetAttributeValue<EntityReference>("plugintypeid"); } } [AttributeLogicalName("primaryentity")] public string PrimaryEntity { get { return this.GetAttributeValue<string>("primaryentity"); } set { this.OnPropertyChanging("PrimaryEntity"); this.SetAttributeValue("primaryentity", (object) value); this.OnPropertyChanged("PrimaryEntity"); } } [AttributeLogicalName("processorder")] public int? ProcessOrder { get { return this.GetAttributeValue<int?>("processorder"); } set { this.OnPropertyChanging("ProcessOrder"); this.SetAttributeValue("processorder", (object) value); this.OnPropertyChanged("ProcessOrder"); } } [AttributeLogicalName("processroleassignment")] public string ProcessRoleAssignment { get { return this.GetAttributeValue<string>("processroleassignment"); } set { this.OnPropertyChanging("ProcessRoleAssignment"); this.SetAttributeValue("processroleassignment", (object) value); this.OnPropertyChanged("ProcessRoleAssignment"); } } [AttributeLogicalName("rank")] public int? Rank { get { return this.GetAttributeValue<int?>("rank"); } set { this.OnPropertyChanging("Rank"); this.SetAttributeValue("rank", (object) value); this.OnPropertyChanged("Rank"); } } [AttributeLogicalName("rendererobjecttypecode")] public string RendererObjectTypeCode { get { return this.GetAttributeValue<string>("rendererobjecttypecode"); } set { this.OnPropertyChanging("RendererObjectTypeCode"); this.SetAttributeValue("rendererobjecttypecode", (object) value); this.OnPropertyChanged("RendererObjectTypeCode"); } } [AttributeLogicalName("runas")] public OptionSetValue RunAs { get { return this.GetAttributeValue<OptionSetValue>("runas"); } set { this.OnPropertyChanging("RunAs"); this.SetAttributeValue("runas", (object) value); this.OnPropertyChanged("RunAs"); } } [AttributeLogicalName("scope")] public OptionSetValue Scope { get { return this.GetAttributeValue<OptionSetValue>("scope"); } set { this.OnPropertyChanging("Scope"); this.SetAttributeValue("scope", (object) value); this.OnPropertyChanged("Scope"); } } [AttributeLogicalName("sdkmessageid")] public EntityReference SdkMessageId { get { return this.GetAttributeValue<EntityReference>("sdkmessageid"); } } [AttributeLogicalName("solutionid")] public Guid? SolutionId { get { return this.GetAttributeValue<Guid?>("solutionid"); } } [AttributeLogicalName("statecode")] public WorkflowState? StateCode { get { OptionSetValue attributeValue = this.GetAttributeValue<OptionSetValue>("statecode"); if (attributeValue != null) return new WorkflowState?((WorkflowState) Enum.ToObject(typeof (WorkflowState), attributeValue.Value)); return new WorkflowState?(); } set { this.OnPropertyChanging("StateCode"); if (!value.HasValue) this.SetAttributeValue("statecode", (object) null); else this.SetAttributeValue("statecode", (object) new OptionSetValue((int) value.Value)); this.OnPropertyChanged("StateCode"); } } [AttributeLogicalName("statuscode")] public OptionSetValue StatusCode { get { return this.GetAttributeValue<OptionSetValue>("statuscode"); } set { this.OnPropertyChanging("StatusCode"); this.SetAttributeValue("statuscode", (object) value); this.OnPropertyChanged("StatusCode"); } } [AttributeLogicalName("subprocess")] public bool? Subprocess { get { return this.GetAttributeValue<bool?>("subprocess"); } set { this.OnPropertyChanging("Subprocess"); this.SetAttributeValue("subprocess", (object) value); this.OnPropertyChanged("Subprocess"); } } [AttributeLogicalName("syncworkflowlogonfailure")] public bool? SyncWorkflowLogOnFailure { get { return this.GetAttributeValue<bool?>("syncworkflowlogonfailure"); } set { this.OnPropertyChanging("SyncWorkflowLogOnFailure"); this.SetAttributeValue("syncworkflowlogonfailure", (object) value); this.OnPropertyChanged("SyncWorkflowLogOnFailure"); } } [AttributeLogicalName("triggeroncreate")] public bool? TriggerOnCreate { get { return this.GetAttributeValue<bool?>("triggeroncreate"); } set { this.OnPropertyChanging("TriggerOnCreate"); this.SetAttributeValue("triggeroncreate", (object) value); this.OnPropertyChanged("TriggerOnCreate"); } } [AttributeLogicalName("triggerondelete")] public bool? TriggerOnDelete { get { return this.GetAttributeValue<bool?>("triggerondelete"); } set { this.OnPropertyChanging("TriggerOnDelete"); this.SetAttributeValue("triggerondelete", (object) value); this.OnPropertyChanged("TriggerOnDelete"); } } [AttributeLogicalName("triggeronupdateattributelist")] public string TriggerOnUpdateAttributeList { get { return this.GetAttributeValue<string>("triggeronupdateattributelist"); } set { this.OnPropertyChanging("TriggerOnUpdateAttributeList"); this.SetAttributeValue("triggeronupdateattributelist", (object) value); this.OnPropertyChanged("TriggerOnUpdateAttributeList"); } } [AttributeLogicalName("type")] public OptionSetValue Type { get { return this.GetAttributeValue<OptionSetValue>("type"); } set { this.OnPropertyChanging("Type"); this.SetAttributeValue("type", (object) value); this.OnPropertyChanged("Type"); } } [AttributeLogicalName("uniquename")] public string UniqueName { get { return this.GetAttributeValue<string>("uniquename"); } set { this.OnPropertyChanging("UniqueName"); this.SetAttributeValue("uniquename", (object) value); this.OnPropertyChanged("UniqueName"); } } [AttributeLogicalName("updatestage")] public OptionSetValue UpdateStage { get { return this.GetAttributeValue<OptionSetValue>("updatestage"); } set { this.OnPropertyChanging("UpdateStage"); this.SetAttributeValue("updatestage", (object) value); this.OnPropertyChanged("UpdateStage"); } } [AttributeLogicalName("versionnumber")] public long? VersionNumber { get { return this.GetAttributeValue<long?>("versionnumber"); } } [AttributeLogicalName("workflowid")] public Guid? WorkflowId { get { return this.GetAttributeValue<Guid?>("workflowid"); } set { this.OnPropertyChanging("WorkflowId"); this.SetAttributeValue("workflowid", (object) value); if (value.HasValue) base.Id = value.Value; else base.Id = Guid.Empty; this.OnPropertyChanged("WorkflowId"); } } [AttributeLogicalName("workflowid")] public override Guid Id { get { return base.Id; } set { this.WorkflowId = new Guid?(value); } } [AttributeLogicalName("workflowidunique")] public Guid? WorkflowIdUnique { get { return this.GetAttributeValue<Guid?>("workflowidunique"); } } [AttributeLogicalName("xaml")] public string Xaml { get { return this.GetAttributeValue<string>("xaml"); } set { this.OnPropertyChanging("Xaml"); this.SetAttributeValue("xaml", (object) value); this.OnPropertyChanged("Xaml"); } } [RelationshipSchemaName("lk_asyncoperation_workflowactivationid")] public IEnumerable<AsyncOperation> lk_asyncoperation_workflowactivationid { get { return this.GetRelatedEntities<AsyncOperation>("lk_asyncoperation_workflowactivationid", new EntityRole?()); } set { this.OnPropertyChanging("lk_asyncoperation_workflowactivationid"); this.SetRelatedEntities<AsyncOperation>("lk_asyncoperation_workflowactivationid", new EntityRole?(), value); this.OnPropertyChanged("lk_asyncoperation_workflowactivationid"); } } [RelationshipSchemaName("workflow_active_workflow", EntityRole.Referenced)] public IEnumerable<Workflow> Referencedworkflow_active_workflow { get { return this.GetRelatedEntities<Workflow>("workflow_active_workflow", new EntityRole?(EntityRole.Referenced)); } set { this.OnPropertyChanging("Referencedworkflow_active_workflow"); this.SetRelatedEntities<Workflow>("workflow_active_workflow", new EntityRole?(EntityRole.Referenced), value); this.OnPropertyChanged("Referencedworkflow_active_workflow"); } } [RelationshipSchemaName("workflow_dependencies")] public IEnumerable<WorkflowDependency> workflow_dependencies { get { return this.GetRelatedEntities<WorkflowDependency>("workflow_dependencies", new EntityRole?()); } set { this.OnPropertyChanging("workflow_dependencies"); this.SetRelatedEntities<WorkflowDependency>("workflow_dependencies", new EntityRole?(), value); this.OnPropertyChanged("workflow_dependencies"); } } [RelationshipSchemaName("workflow_parent_workflow", EntityRole.Referenced)] public IEnumerable<Workflow> Referencedworkflow_parent_workflow { get { return this.GetRelatedEntities<Workflow>("workflow_parent_workflow", new EntityRole?(EntityRole.Referenced)); } set { this.OnPropertyChanging("Referencedworkflow_parent_workflow"); this.SetRelatedEntities<Workflow>("workflow_parent_workflow", new EntityRole?(EntityRole.Referenced), value); this.OnPropertyChanged("Referencedworkflow_parent_workflow"); } } [AttributeLogicalName("owningbusinessunit")] [RelationshipSchemaName("business_unit_workflow")] public BusinessUnit business_unit_workflow { get { return this.GetRelatedEntity<BusinessUnit>("business_unit_workflow", new EntityRole?()); } } [RelationshipSchemaName("system_user_workflow")] [AttributeLogicalName("owninguser")] public SystemUser system_user_workflow { get { return this.GetRelatedEntity<SystemUser>("system_user_workflow", new EntityRole?()); } } [AttributeLogicalName("activeworkflowid")] [RelationshipSchemaName("workflow_active_workflow", EntityRole.Referencing)] public Workflow Referencingworkflow_active_workflow { get { return this.GetRelatedEntity<Workflow>("workflow_active_workflow", new EntityRole?(EntityRole.Referencing)); } } [RelationshipSchemaName("workflow_createdby")] [AttributeLogicalName("createdby")] public SystemUser workflow_createdby { get { return this.GetRelatedEntity<SystemUser>("workflow_createdby", new EntityRole?()); } } [AttributeLogicalName("createdonbehalfby")] [RelationshipSchemaName("workflow_createdonbehalfby")] public SystemUser workflow_createdonbehalfby { get { return this.GetRelatedEntity<SystemUser>("workflow_createdonbehalfby", new EntityRole?()); } } [RelationshipSchemaName("workflow_modifiedby")] [AttributeLogicalName("modifiedby")] public SystemUser workflow_modifiedby { get { return this.GetRelatedEntity<SystemUser>("workflow_modifiedby", new EntityRole?()); } } [RelationshipSchemaName("workflow_modifiedonbehalfby")] [AttributeLogicalName("modifiedonbehalfby")] public SystemUser workflow_modifiedonbehalfby { get { return this.GetRelatedEntity<SystemUser>("workflow_modifiedonbehalfby", new EntityRole?()); } } [AttributeLogicalName("parentworkflowid")] [RelationshipSchemaName("workflow_parent_workflow", EntityRole.Referencing)] public Workflow Referencingworkflow_parent_workflow { get { return this.GetRelatedEntity<Workflow>("workflow_parent_workflow", new EntityRole?(EntityRole.Referencing)); } } public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangingEventHandler PropertyChanging; public Workflow() : base("workflow") { } private void OnPropertyChanged(string propertyName) { if (this.PropertyChanged == null) return; this.PropertyChanged((object) this, new PropertyChangedEventArgs(propertyName)); } private void OnPropertyChanging(string propertyName) { if (this.PropertyChanging == null) return; this.PropertyChanging((object) this, new PropertyChangingEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace AuthApp.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows.Forms; using CodeContractNullability.Test.TestDataBuilders; using Xunit; namespace CodeContractNullability.Test.Specs { /// <summary> /// Tests for reporting item nullability diagnostics on fields of collection types. /// </summary> public sealed class FieldCollectionSpecs : ItemNullabilityTest { [Fact] public void When_field_is_annotated_with_item_not_nullable_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .WithNullabilityAttributes(new NullabilityAttributesBuilder() .InCodeNamespace("N.M")) .Using(typeof(IEnumerable<>).Namespace) .InGlobalScope(@" class C { [N.M.ItemNotNull] // Using fully qualified namespace IEnumerable<string> f; } ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } [Fact] public void When_field_is_annotated_with_item_nullable_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .WithNullabilityAttributes(new NullabilityAttributesBuilder() .InCodeNamespace("N1")) .Using(typeof(IEnumerable<>).Namespace) .InGlobalScope(@" namespace N2 { using ICBN = N1.ItemCanBeNullAttribute; class C { [ICBN()] // Using type/namespace alias IEnumerable<string> f; } } ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } [Fact] public void When_field_is_constant_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" public const string[] f = null; ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } [Fact] public void When_field_item_type_is_value_type_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(List<>).Namespace) .InDefaultClass(@" List<int> f; ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } [Fact] public void When_field_item_type_is_generic_value_type_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .Using(typeof(IList<>).Namespace) .InGlobalScope(@" class C<T> where T : struct { IList<T> f; } ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } [Fact] public void When_field_item_type_is_enum_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .WithReference(typeof(HashSet<>).Assembly) .Using(typeof(HashSet<>).Namespace) .Using(typeof(BindingFlags).Namespace) .InDefaultClass(@" HashSet<BindingFlags> f; ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } [Fact] public void When_field_item_type_is_object_it_must_be_reported_and_fixed() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(IList).Namespace) .InDefaultClass(@" [+NullabilityAttributePlaceholder+] IList [|f|]; ") .Build(); // Act and assert VerifyNullabilityFix(source, CreateMessageForField("f")); } [Fact] public void When_field_item_type_is_nullable_it_must_be_reported_and_fixed() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(IList<>).Namespace) .InDefaultClass(@" [+NullabilityAttributePlaceholder+] IList<int?> [|f|]; ") .Build(); // Act and assert VerifyNullabilityFix(source, CreateMessageForField("f")); } [Fact] public void When_field_item_type_is_nullable_but_analysis_is_disabled_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .WithSettings(new AnalyzerSettingsBuilder() .DisableReportOnNullableValueTypes) .Using(typeof(IList<>).Namespace) .InDefaultClass(@" IList<int?> f; ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } [Fact] public void When_field_item_type_is_generic_nullable_it_must_be_reported_and_fixed() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .Using(typeof(ISet<>).Namespace) .InGlobalScope(@" class C<T> where T : struct { [+NullabilityAttributePlaceholder+] ISet<T?> [|f|]; } ") .Build(); // Act and assert VerifyNullabilityFix(source, CreateMessageForField("f")); } [Fact] public void When_field_item_type_is_reference_it_must_be_reported_and_fixed() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(IEnumerable<>).Namespace) .InDefaultClass(@" [+NullabilityAttributePlaceholder+] IEnumerable<string> [|f|]; ") .Build(); // Act and assert VerifyNullabilityFix(source, CreateMessageForField("f")); } #if !NET452 [Fact] public void When_field_type_is_tuple_of_reference_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(ValueTuple<>).Namespace) .InDefaultClass(@" private protected (string, string) f; ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } #endif [Fact] public void When_field_is_compiler_generated_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(IEnumerable<>).Namespace) .Using(typeof(CompilerGeneratedAttribute).Namespace) .InDefaultClass(@" [CompilerGenerated] IEnumerable<string> f; ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } [Fact] public void When_field_is_in_designer_generated_file_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InFileNamed("MainForm.Designer.cs") .WithReference(typeof(Control).Assembly) .Using(typeof(IList<>).Namespace) .Using(typeof(Control).Namespace) .InGlobalScope(@" public partial class DerivedControl : Control { private IList<Control> controls; } ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } [Fact] public void When_field_is_in_file_with_code_gen_comment_at_top_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(IList).Namespace) .WithHeader(@" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ ") .InDefaultClass(@" private IList f; ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } [Fact] public void When_field_contains_multiple_variables_they_must_be_reported_and_fixed() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(List<>).Namespace) .InDefaultClass(@" [+NullabilityAttributePlaceholder+] List<int?> [|f|], [|g|]; ") .Build(); // Act and assert VerifyNullabilityFix(source, CreateMessageForField("f"), CreateMessageForField("g")); } [Fact] public void When_field_type_is_lazy_it_must_be_reported_and_fixed() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" [+NullabilityAttributePlaceholder+] Lazy<string> [|f|]; ") .Build(); // Act and assert VerifyNullabilityFix(source, CreateMessageForField("f")); } [Fact] public void When_field_type_is_task_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Task).Namespace) .InDefaultClass(@" Task f; ") .Build(); // Act and assert VerifyNullabilityDiagnostic(source); } [Fact] public void When_field_type_is_generic_task_it_must_be_reported_and_fixed() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Task<>).Namespace) .InDefaultClass(@" [+NullabilityAttributePlaceholder+] Task<string> [|f|]; ") .Build(); // Act and assert VerifyNullabilityFix(source, CreateMessageForField("f")); } [Fact] public void When_field_type_is_generic_value_task_it_must_be_reported_and_fixed() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .WithReference(typeof(ValueTask<>).Assembly) .Using(typeof(ValueTask<>).Namespace) .InDefaultClass(@" [+NullabilityAttributePlaceholder+] ValueTask<string> [|f|]; ") .Build(); // Act and assert VerifyNullabilityFix(source, CreateMessageForField("f")); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.Table; using Microsoft.Extensions.Logging; using Orleans.Clustering.AzureStorage; using Orleans.Clustering.AzureStorage.Utilities; using Orleans.Internal; using Orleans.Runtime; namespace Orleans.AzureUtils { internal class OrleansSiloInstanceManager { public string TableName { get; } private readonly string INSTANCE_STATUS_CREATED = SiloStatus.Created.ToString(); //"Created"; private readonly string INSTANCE_STATUS_ACTIVE = SiloStatus.Active.ToString(); //"Active"; private readonly string INSTANCE_STATUS_DEAD = SiloStatus.Dead.ToString(); //"Dead"; private readonly AzureTableDataManager<SiloInstanceTableEntry> storage; private readonly ILogger logger; private readonly AzureStoragePolicyOptions storagePolicyOptions; public string DeploymentId { get; private set; } private OrleansSiloInstanceManager( string clusterId, ILoggerFactory loggerFactory, AzureStorageOperationOptions options) { DeploymentId = clusterId; TableName = options.TableName; logger = loggerFactory.CreateLogger<OrleansSiloInstanceManager>(); storage = new AzureTableDataManager<SiloInstanceTableEntry>( options, loggerFactory.CreateLogger<AzureTableDataManager<SiloInstanceTableEntry>>()); this.storagePolicyOptions = options.StoragePolicyOptions; } public static async Task<OrleansSiloInstanceManager> GetManager( string clusterId, ILoggerFactory loggerFactory, AzureStorageOperationOptions options) { var instance = new OrleansSiloInstanceManager(clusterId, loggerFactory, options); try { await instance.storage.InitTableAsync(); } catch (Exception ex) { string errorMsg = string.Format("Exception trying to create or connect to the Azure table: {0}", ex.Message); instance.logger.Error((int)TableStorageErrorCode.AzureTable_33, errorMsg, ex); throw new OrleansException(errorMsg, ex); } return instance; } public SiloInstanceTableEntry CreateTableVersionEntry(int tableVersion) { return new SiloInstanceTableEntry { DeploymentId = DeploymentId, PartitionKey = DeploymentId, RowKey = SiloInstanceTableEntry.TABLE_VERSION_ROW, MembershipVersion = tableVersion.ToString(CultureInfo.InvariantCulture) }; } public void RegisterSiloInstance(SiloInstanceTableEntry entry) { entry.Status = INSTANCE_STATUS_CREATED; logger.Info(ErrorCode.Runtime_Error_100270, "Registering silo instance: {0}", entry.ToString()); Task.WaitAll(new Task[] { storage.UpsertTableEntryAsync(entry) }); } public Task<string> UnregisterSiloInstance(SiloInstanceTableEntry entry) { entry.Status = INSTANCE_STATUS_DEAD; logger.Info(ErrorCode.Runtime_Error_100271, "Unregistering silo instance: {0}", entry.ToString()); return storage.UpsertTableEntryAsync(entry); } public Task<string> ActivateSiloInstance(SiloInstanceTableEntry entry) { logger.Info(ErrorCode.Runtime_Error_100272, "Activating silo instance: {0}", entry.ToString()); entry.Status = INSTANCE_STATUS_ACTIVE; return storage.UpsertTableEntryAsync(entry); } public async Task<IList<Uri>> FindAllGatewayProxyEndpoints() { IEnumerable<SiloInstanceTableEntry> gatewaySiloInstances = await FindAllGatewaySilos(); return gatewaySiloInstances.Select(ConvertToGatewayUri).ToList(); } /// <summary> /// Represent a silo instance entry in the gateway URI format. /// </summary> /// <param name="gateway">The input silo instance</param> /// <returns></returns> private static Uri ConvertToGatewayUri(SiloInstanceTableEntry gateway) { int proxyPort = 0; if (!string.IsNullOrEmpty(gateway.ProxyPort)) int.TryParse(gateway.ProxyPort, out proxyPort); int gen = 0; if (!string.IsNullOrEmpty(gateway.Generation)) int.TryParse(gateway.Generation, out gen); SiloAddress address = SiloAddress.New(new IPEndPoint(IPAddress.Parse(gateway.Address), proxyPort), gen); return address.ToGatewayUri(); } private async Task<IEnumerable<SiloInstanceTableEntry>> FindAllGatewaySilos() { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Runtime_Error_100277, "Searching for active gateway silos for deployment {0}.", this.DeploymentId); const string zeroPort = "0"; try { string filterOnPartitionKey = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.PartitionKey), QueryComparisons.Equal, this.DeploymentId); string filterOnStatus = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.Status), QueryComparisons.Equal, INSTANCE_STATUS_ACTIVE); string filterOnProxyPort = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.ProxyPort), QueryComparisons.NotEqual, zeroPort); string query = TableQuery.CombineFilters(filterOnPartitionKey, TableOperators.And, TableQuery.CombineFilters(filterOnStatus, TableOperators.And, filterOnProxyPort)); var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query); List<SiloInstanceTableEntry> gatewaySiloInstances = queryResults.Select(entity => entity.Item1).ToList(); logger.Info(ErrorCode.Runtime_Error_100278, "Found {0} active Gateway Silos for deployment {1}.", gatewaySiloInstances.Count, this.DeploymentId); return gatewaySiloInstances; }catch(Exception exc) { logger.Error(ErrorCode.Runtime_Error_100331, string.Format("Error searching for active gateway silos for deployment {0} ", this.DeploymentId), exc); throw; } } public async Task<string> DumpSiloInstanceTable() { var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId); SiloInstanceTableEntry[] entries = queryResults.Select(entry => entry.Item1).ToArray(); var sb = new StringBuilder(); sb.Append(String.Format("Deployment {0}. Silos: ", DeploymentId)); // Loop through the results, displaying information about the entity Array.Sort(entries, (e1, e2) => { if (e1 == null) return (e2 == null) ? 0 : -1; if (e2 == null) return (e1 == null) ? 0 : 1; if (e1.SiloName == null) return (e2.SiloName == null) ? 0 : -1; if (e2.SiloName == null) return (e1.SiloName == null) ? 0 : 1; return String.CompareOrdinal(e1.SiloName, e2.SiloName); }); foreach (SiloInstanceTableEntry entry in entries) { sb.AppendLine(String.Format("[IP {0}:{1}:{2}, {3}, Instance={4}, Status={5}]", entry.Address, entry.Port, entry.Generation, entry.HostName, entry.SiloName, entry.Status)); } return sb.ToString(); } internal Task<string> MergeTableEntryAsync(SiloInstanceTableEntry data) { return storage.MergeTableEntryAsync(data, AzureTableUtils.ANY_ETAG); // we merge this without checking eTags. } internal Task<Tuple<SiloInstanceTableEntry, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey) { return storage.ReadSingleTableEntryAsync(partitionKey, rowKey); } internal async Task<int> DeleteTableEntries(string clusterId) { if (clusterId == null) throw new ArgumentNullException(nameof(clusterId)); var entries = await storage.ReadAllTableEntriesForPartitionAsync(clusterId); var entriesList = new List<Tuple<SiloInstanceTableEntry, string>>(entries); await DeleteEntriesBatch(entriesList); return entriesList.Count; } public async Task CleanupDefunctSiloEntries(DateTimeOffset beforeDate) { var entriesList = (await FindAllSiloEntries()) .Where(entry => !string.Equals(SiloInstanceTableEntry.TABLE_VERSION_ROW, entry.Item1.RowKey) && entry.Item1.Status != INSTANCE_STATUS_ACTIVE && entry.Item1.Timestamp < beforeDate) .ToList(); await DeleteEntriesBatch(entriesList); } private async Task DeleteEntriesBatch(List<Tuple<SiloInstanceTableEntry, string>> entriesList) { if (entriesList.Count <= this.storagePolicyOptions.MaxBulkUpdateRows) { await storage.DeleteTableEntriesAsync(entriesList); } else { var tasks = new List<Task>(); foreach (var batch in entriesList.BatchIEnumerable(this.storagePolicyOptions.MaxBulkUpdateRows)) { tasks.Add(storage.DeleteTableEntriesAsync(batch)); } await Task.WhenAll(tasks); } } internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindSiloEntryAndTableVersionRow(SiloAddress siloAddress) { string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress); string filterOnPartitionKey = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.PartitionKey), QueryComparisons.Equal, this.DeploymentId); string filterOnRowKey1 = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.RowKey), QueryComparisons.Equal, rowKey); string filterOnRowKey2 = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.RowKey), QueryComparisons.Equal, SiloInstanceTableEntry.TABLE_VERSION_ROW); string query = TableQuery.CombineFilters(filterOnPartitionKey, TableOperators.And, TableQuery.CombineFilters(filterOnRowKey1, TableOperators.Or, filterOnRowKey2)); var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query); var asList = queryResults.ToList(); if (asList.Count < 1 || asList.Count > 2) throw new KeyNotFoundException(string.Format("Could not find table version row or found too many entries. Was looking for key {0}, found = {1}", siloAddress.ToLongString(), Utils.EnumerableToString(asList))); int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW); if (numTableVersionRows < 1) throw new KeyNotFoundException(string.Format("Did not read table version row. Read = {0}", Utils.EnumerableToString(asList))); if (numTableVersionRows > 1) throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList))); return asList; } internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindAllSiloEntries() { var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId); var asList = queryResults.ToList(); if (asList.Count < 1) throw new KeyNotFoundException(string.Format("Could not find enough rows in the FindAllSiloEntries call. Found = {0}", Utils.EnumerableToString(asList))); int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW); if (numTableVersionRows < 1) throw new KeyNotFoundException(string.Format("Did not find table version row. Read = {0}", Utils.EnumerableToString(asList))); if (numTableVersionRows > 1) throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList))); return asList; } /// <summary> /// Insert (create new) row entry /// </summary> internal async Task<bool> TryCreateTableVersionEntryAsync() { try { var versionRow = await storage.ReadSingleTableEntryAsync(DeploymentId, SiloInstanceTableEntry.TABLE_VERSION_ROW); if (versionRow != null && versionRow.Item1 != null) { return false; } SiloInstanceTableEntry entry = CreateTableVersionEntry(0); await storage.CreateTableEntryAsync(entry); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureTableUtils.IsContentionError(httpStatusCode)) return false; throw; } } /// <summary> /// Insert (create new) row entry /// </summary> /// <param name="siloEntry">Silo Entry to be written</param> /// <param name="tableVersionEntry">Version row to update</param> /// <param name="tableVersionEtag">Version row eTag</param> internal async Task<bool> InsertSiloEntryConditionally(SiloInstanceTableEntry siloEntry, SiloInstanceTableEntry tableVersionEntry, string tableVersionEtag) { try { await storage.InsertTwoTableEntriesConditionallyAsync(siloEntry, tableVersionEntry, tableVersionEtag); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureTableUtils.IsContentionError(httpStatusCode)) return false; throw; } } /// <summary> /// Conditionally update the row for this entry, but only if the eTag matches with the current record in data store /// </summary> /// <param name="siloEntry">Silo Entry to be written</param> /// <param name="entryEtag">ETag value for the entry being updated</param> /// <param name="tableVersionEntry">Version row to update</param> /// <param name="versionEtag">ETag value for the version row</param> /// <returns></returns> internal async Task<bool> UpdateSiloEntryConditionally(SiloInstanceTableEntry siloEntry, string entryEtag, SiloInstanceTableEntry tableVersionEntry, string versionEtag) { try { await storage.UpdateTwoTableEntriesConditionallyAsync(siloEntry, entryEtag, tableVersionEntry, versionEtag); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("UpdateSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureTableUtils.IsContentionError(httpStatusCode)) return false; throw; } } } }
#if !(UNITY_4_3 || UNITY_4_5) using UnityEngine; using UnityEngine.Events; using System; using System.Collections; using System.Collections.Generic; using PixelCrushers.DialogueSystem; namespace PixelCrushers.DialogueSystem { /// <summary> /// This is an implementation of the abstract QuestLogWindow class for the Unity UI. /// </summary> [AddComponentMenu("Dialogue System/UI/Unity UI/Quest/Unity UI Quest Log Window")] public class UnityUIQuestLogWindow : QuestLogWindow { /// <summary> /// The main quest log window panel. /// </summary> public UnityEngine.UI.Graphic mainPanel; /// <summary> /// The active quests button. /// </summary> public UnityEngine.UI.Button activeQuestsButton; /// <summary> /// The completed quests button. /// </summary> public UnityEngine.UI.Button completedQuestsButton; /// <summary> /// The quest table. /// </summary> public UnityEngine.UI.Graphic questTable; public UnityUIQuestGroupTemplate questGroupTemplate; /// <summary> /// The quest template. /// </summary> public UnityUIQuestTemplate questTemplate; /// <summary> /// The confirmation popup to use if the player clicks the abandon quest button. /// It should send ClickConfirmAbandonQuest if the player confirms, or /// ClickCancelAbandonQuest if the player cancels. /// </summary> public UnityEngine.UI.Graphic abandonPopup; /// <summary> /// The quest title label to set in the abandon quest dialog popup. /// </summary> public UnityEngine.UI.Text abandonQuestTitle; /// <summary> /// Set <c>true</c> to always keep a control focused; useful for gamepads. /// </summary> public bool autoFocus = false; public UnityEvent onOpen = new UnityEvent(); public UnityEvent onClose = new UnityEvent(); public UnityEvent onContentChanged = new UnityEvent(); [Serializable] public class AnimationTransitions { public string showTrigger = "Show"; public string hideTrigger = "Hide"; } public AnimationTransitions animationTransitions = new AnimationTransitions(); /// <summary> /// This handler is called if the player confirms abandonment of a quest. /// </summary> private System.Action confirmAbandonQuestHandler = null; private UIShowHideController showHideController = null; private List<string> collapsedGroups = new List<string>(); private List<UnityUIQuestGroupTemplate> groupTemplateInstances = new List<UnityUIQuestGroupTemplate>(); private List<UnityUIQuestTemplate> questTemplateInstances = new List<UnityUIQuestTemplate>(); private List<UnityUIQuestGroupTemplate> unusedGroupTemplateInstances = new List<UnityUIQuestGroupTemplate>(); private List<UnityUIQuestTemplate> unusedQuestTemplateInstances = new List<UnityUIQuestTemplate>(); private int siblingIndexCounter = 0; public override void Awake() { showHideController = new UIShowHideController(this.gameObject, mainPanel); } /// <summary> /// Hide the main panel and all of the templates on start. /// </summary> public virtual void Start() { UITools.RequireEventSystem(); Tools.SetGameObjectActive(mainPanel, false); Tools.SetGameObjectActive(abandonPopup, false); Tools.SetGameObjectActive(questGroupTemplate, false); Tools.SetGameObjectActive(questTemplate, false); SetStateButtonListeners(); SetStateToggleButtons(); if (DialogueDebug.LogWarnings) { if (mainPanel == null) Debug.LogWarning(string.Format("{0}: {1} Main Panel is unassigned", new object[] { DialogueDebug.Prefix, name })); if (questTable == null) Debug.LogWarning(string.Format("{0}: {1} Quest Table is unassigned", new object[] { DialogueDebug.Prefix, name })); if (useGroups && ((questTemplate == null || !questTemplate.ArePropertiesAssigned))) { Debug.LogWarning(string.Format("{0}: {1} Quest Group Template or one of its properties is unassigned", new object[] { DialogueDebug.Prefix, name })); } if (questTemplate == null || !questTemplate.ArePropertiesAssigned) { Debug.LogWarning(string.Format("{0}: {1} Quest Template or one of its properties is unassigned", new object[] { DialogueDebug.Prefix, name })); } } } /// <summary> /// Open the window by showing the main panel. The bark UI may conflict with the quest /// log window, so temporarily disable it. /// </summary> /// <param name="openedWindowHandler">Opened window handler.</param> public override void OpenWindow(System.Action openedWindowHandler) { showHideController.Show(animationTransitions.showTrigger, pauseWhileOpen, openedWindowHandler, false); IsOpen = true; AutoFocus(); onOpen.Invoke(); } public void AutoFocus() { if (autoFocus && (UnityEngine.EventSystems.EventSystem.current != null)) { GameObject go = completedQuestsButton.gameObject.activeSelf ? completedQuestsButton.gameObject : activeQuestsButton.gameObject; UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject(go); } } /// <summary> /// Close the window by hiding the main panel. Re-enable the bark UI. /// </summary> /// <param name="closedWindowHandler">Closed window handler.</param> public override void CloseWindow(System.Action closedWindowHandler) { showHideController.Hide(animationTransitions.hideTrigger, closedWindowHandler); IsOpen = false; onClose.Invoke(); } /// <summary> /// Whenever the quest list is updated, repopulate the scroll panel. /// </summary> public override void OnQuestListUpdated() { unusedGroupTemplateInstances.AddRange(groupTemplateInstances); unusedQuestTemplateInstances.AddRange(questTemplateInstances); groupTemplateInstances.Clear(); questTemplateInstances.Clear(); // Add content, drawing from unused list when possible: if (Quests.Length == 0) { AddQuestToTable(new QuestInfo(string.Empty, new FormattedText(NoQuestsMessage), FormattedText.empty, new FormattedText[0], new QuestState[0], false, false, false)); } else { AddQuestsToTable(); } // Destroy all unused instances: for (int i = 0; i < unusedGroupTemplateInstances.Count; i++) { Destroy(unusedGroupTemplateInstances[i].gameObject); } unusedGroupTemplateInstances.Clear(); for (int i = 0; i < unusedQuestTemplateInstances.Count; i++) { Destroy(unusedQuestTemplateInstances[i].gameObject); } unusedQuestTemplateInstances.Clear(); //if (questTable == null) return; //ClearQuestTable(); //if (Quests.Length == 0) //{ // AddQuestToTable(new QuestInfo(string.Empty, new FormattedText(NoQuestsMessage), FormattedText.empty, new FormattedText[0], new QuestState[0], false, false, false), 0); //} //else //{ // AddQuestsToTable(); //} SetStateToggleButtons(); } private void SetStateButtonListeners() { if (activeQuestsButton != null) { activeQuestsButton.onClick.RemoveListener(() => ClickShowActiveQuestsButton()); activeQuestsButton.onClick.AddListener(() => ClickShowActiveQuestsButton()); } if (completedQuestsButton != null) { completedQuestsButton.onClick.RemoveListener(() => ClickShowCompletedQuestsButton()); completedQuestsButton.onClick.AddListener(() => ClickShowCompletedQuestsButton()); } } private void SetStateToggleButtons() { if (activeQuestsButton != null) activeQuestsButton.interactable = !IsShowingActiveQuests; if (completedQuestsButton != null) completedQuestsButton.interactable = IsShowingActiveQuests; } private void ClearQuestTable() { if (questTable == null) return; foreach (Transform child in questTable.transform) { if (child.gameObject.activeSelf) { Destroy(child.gameObject); } } NotifyContentChanged(); } private void AddQuestsToTable() { if (questTable == null) return; string currentGroup = null; var isCurrentGroupCollapsed = false; for (int i = 0; i < Quests.Length; i++) { if (!string.Equals(Quests[i].Group, currentGroup)) { currentGroup = Quests[i].Group; AddQuestGroupToTable(currentGroup); isCurrentGroupCollapsed = collapsedGroups.Contains(currentGroup); } if (!isCurrentGroupCollapsed) { AddQuestToTable(Quests[i]); } } NotifyContentChanged(); } /// <summary> /// Adds a quest group to the table using the template. /// </summary> /// <param name="questInfo">Quest info.</param> private void AddQuestGroupToTable(string group) { if (string.IsNullOrEmpty(group) || questGroupTemplate == null || !questGroupTemplate.ArePropertiesAssigned) return; // Try to use existing instance from unused list first: var existingChild = unusedGroupTemplateInstances.Find(x => string.Equals(x.heading.text, group)); if (existingChild != null) { unusedGroupTemplateInstances.Remove(existingChild); groupTemplateInstances.Add(existingChild); existingChild.transform.SetSiblingIndex(siblingIndexCounter++); return; } // Otherwise create a new one: GameObject questGroupGameObject = Instantiate(questGroupTemplate.gameObject) as GameObject; if (questGroupGameObject == null) { Debug.LogError(string.Format("{0}: {1} couldn't instantiate quest group template", new object[] { DialogueDebug.Prefix, name })); return; } questGroupGameObject.name = group; questGroupGameObject.transform.SetParent(questTable.transform, false); questGroupGameObject.SetActive(true); UnityUIQuestGroupTemplate template = questGroupGameObject.GetComponent<UnityUIQuestGroupTemplate>(); if (template == null) return; groupTemplateInstances.Add(template); template.transform.SetSiblingIndex(siblingIndexCounter++); template.Initialize(); template.heading.text = group; // Set up the collapse/expand button: var button = questGroupGameObject.GetComponentInChildren<UnityEngine.UI.Button>(); if (button != null) { button.onClick.AddListener(() => ClickQuestGroupFoldout(group)); } } /// <summary> /// Adds a quest to the table using the template. /// </summary> /// <param name="questInfo">Quest info.</param> private void AddQuestToTable(QuestInfo questInfo) { if ((questTable == null) || (questTemplate == null) || !questTemplate.ArePropertiesAssigned) return; // Try to use existing instance from unused list first: var existingChild = unusedQuestTemplateInstances.Find(x => x.heading.GetComponentInChildren<UnityEngine.UI.Text>() != null && string.Equals(x.heading.GetComponentInChildren<UnityEngine.UI.Text>().text, questInfo.Heading.text)); if (existingChild != null) { unusedQuestTemplateInstances.Remove(existingChild); questTemplateInstances.Add(existingChild); existingChild.transform.SetSiblingIndex(siblingIndexCounter++); existingChild.description.text = questInfo.Description.text; existingChild.ClearQuestDetails(); SetQuestDetails(existingChild, questInfo); return; } // Otherwise create a new one: // Instantiate a copy of the template: GameObject questGameObject = Instantiate(questTemplate.gameObject) as GameObject; if (questGameObject == null) { Debug.LogError(string.Format("{0}: {1} couldn't instantiate quest template", new object[] { DialogueDebug.Prefix, name })); return; } questGameObject.name = questInfo.Heading.text; questGameObject.transform.SetParent(questTable.transform, false); questGameObject.transform.SetSiblingIndex(siblingIndexCounter++); questGameObject.SetActive(true); UnityUIQuestTemplate questControl = questGameObject.GetComponent<UnityUIQuestTemplate>(); if (questControl == null) return; questTemplateInstances.Add(questControl); questControl.Initialize(); // Set the heading button: var questHeadingButton = questControl.heading; var heading = questHeadingButton.GetComponentInChildren<UnityEngine.UI.Text>(); if (heading != null) heading.text = questInfo.Heading.text; questHeadingButton.onClick.AddListener(() => ClickQuestFoldout(questInfo.Title)); SetQuestDetails(questControl, questInfo); } protected void SetQuestDetails(UnityUIQuestTemplate questControl, QuestInfo questInfo) { // Set details if this is the selected quest: if (IsSelectedQuest(questInfo)) { // Set the description: if (questHeadingSource == QuestHeadingSource.Name) { questControl.description.text = questInfo.Description.text; Tools.SetGameObjectActive(questControl.description, true); } // Set the entry description: if (questInfo.EntryStates.Length > 0) { for (int i = 0; i < questInfo.Entries.Length; i++) { questControl.AddEntryDescription(questInfo.Entries[i].text, questInfo.EntryStates[i]); } } UnityUIQuestTitle unityUIQuestTitle = null; // Set the track button: if (questControl.trackButton != null) { unityUIQuestTitle = questControl.trackButton.gameObject.AddComponent<UnityUIQuestTitle>(); unityUIQuestTitle.questTitle = questInfo.Title; questControl.trackButton.onClick.RemoveListener(() => ClickTrackQuestButton()); questControl.trackButton.onClick.AddListener(() => ClickTrackQuestButton()); Tools.SetGameObjectActive(questControl.trackButton, questInfo.Trackable); } // Set the abandon button: if (questControl.abandonButton != null) { unityUIQuestTitle = questControl.abandonButton.gameObject.AddComponent<UnityUIQuestTitle>(); unityUIQuestTitle.questTitle = questInfo.Title; questControl.abandonButton.onClick.RemoveListener(() => ClickAbandonQuestButton()); questControl.abandonButton.onClick.AddListener(() => ClickAbandonQuestButton()); Tools.SetGameObjectActive(questControl.abandonButton, questInfo.Abandonable); } } else { Tools.SetGameObjectActive(questControl.description, false); Tools.SetGameObjectActive(questControl.entryDescription, false); Tools.SetGameObjectActive(questControl.trackButton, false); Tools.SetGameObjectActive(questControl.abandonButton, false); } } public void NotifyContentChanged() { onContentChanged.Invoke(); } public void ClickQuestFoldout(string questTitle) { ClickQuest(questTitle); } public void ClickQuestGroupFoldout(string group) { if (collapsedGroups.Contains(group)) { collapsedGroups.Remove(group); } else { collapsedGroups.Add(group); } OnQuestListUpdated(); } /// <summary> /// Track button clicked event that sets SelectedQuest first. /// </summary> /// <param name="button">Button.</param> private void OnTrackButtonClicked(GameObject button) { SelectedQuest = button.GetComponent<UnityUIQuestTitle>().questTitle; ClickTrackQuest(SelectedQuest); } /// <summary> /// Abandon button clicked event that sets SelectedQuest first. /// </summary> /// <param name="button">Button.</param> private void OnAbandonButtonClicked(GameObject button) { SelectedQuest = button.GetComponent<UnityUIQuestTitle>().questTitle; ClickAbandonQuest(SelectedQuest); } /// <summary> /// Opens the abandon confirmation popup. /// </summary> /// <param name="title">Quest title.</param> /// <param name="confirmAbandonQuestHandler">Confirm abandon quest handler.</param> public override void ConfirmAbandonQuest(string title, System.Action confirmAbandonQuestHandler) { this.confirmAbandonQuestHandler = confirmAbandonQuestHandler; OpenAbandonPopup(title); } /// <summary> /// Opens the abandon popup modally if assigned; otherwise immediately confirms. /// </summary> /// <param name="title">Quest title.</param> private void OpenAbandonPopup(string title) { if (abandonPopup != null) { Tools.SetGameObjectActive(abandonPopup, true); if (abandonQuestTitle != null) abandonQuestTitle.text = title; if (autoFocus && (UnityEngine.EventSystems.EventSystem.current != null)) { var button = abandonPopup.GetComponentInChildren<UnityEngine.UI.Button>(); if (button != null) { UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject(button.gameObject); } } else { this.confirmAbandonQuestHandler(); } } } /// <summary> /// Closes the abandon popup. /// </summary> private void CloseAbandonPopup() { Tools.SetGameObjectActive(abandonPopup, false); } public void ClickConfirmAbandonQuestButton() { CloseAbandonPopup(); confirmAbandonQuestHandler(); } public void ClickCancelAbandonQuestButton() { CloseAbandonPopup(); } } } #endif
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using System.Collections.Generic; namespace OpenSim.Region.RegionCombinerModule { public class RegionCombinerPermissionModule { private Scene m_rootScene; public RegionCombinerPermissionModule(Scene RootScene) { m_rootScene = RootScene; } #region Permission Override public bool BypassPermissions() { return m_rootScene.Permissions.BypassPermissions(); } public bool CanAbandonParcel(UUID user, ILandObject parcel, Scene scene) { return m_rootScene.Permissions.CanAbandonParcel(user, parcel); } public bool CanBuyLand(UUID user, ILandObject parcel, Scene scene) { return m_rootScene.Permissions.CanBuyLand(user, parcel); } public bool CanCompileScript(UUID owneruuid, int scripttype, Scene scene) { return m_rootScene.Permissions.CanCompileScript(owneruuid, scripttype); } public bool CanCopyObjectInventory(UUID itemid, UUID objectid, UUID userid) { return m_rootScene.Permissions.CanCopyObjectInventory(itemid, objectid, userid); } public bool CanCopyUserInventory(UUID itemid, UUID userid) { return m_rootScene.Permissions.CanCopyUserInventory(itemid, userid); } public bool CanCreateObjectInventory(int invtype, UUID objectid, UUID userid) { return m_rootScene.Permissions.CanCreateObjectInventory(invtype, objectid, userid); } public bool CanCreateUserInventory(int invtype, UUID userid) { return m_rootScene.Permissions.CanCreateUserInventory(invtype, userid); } public bool CanDeedObject(UUID user, UUID @group, Scene scene) { return m_rootScene.Permissions.CanDeedObject(user, @group); } public bool CanDeedParcel(UUID user, ILandObject parcel, Scene scene) { return m_rootScene.Permissions.CanDeedParcel(user, parcel); } public bool CanDeleteObject(UUID objectid, UUID deleter, Scene scene) { return m_rootScene.Permissions.CanDeleteObject(objectid, deleter); } public bool CanDeleteObjectInventory(UUID itemid, UUID objectid, UUID userid) { return m_rootScene.Permissions.CanDeleteObjectInventory(itemid, objectid, userid); } public bool CanDeleteUserInventory(UUID itemid, UUID userid) { return m_rootScene.Permissions.CanDeleteUserInventory(itemid, userid); } public bool CanDelinkObject(UUID user, UUID objectid) { return m_rootScene.Permissions.CanDelinkObject(user, objectid); } public bool CanDuplicateObject(int objectcount, UUID objectid, UUID owner, Scene scene, Vector3 objectposition) { return m_rootScene.Permissions.CanDuplicateObject(objectcount, objectid, owner, objectposition); } public bool CanEditNotecard(UUID notecard, UUID objectid, UUID user, Scene scene) { return m_rootScene.Permissions.CanEditNotecard(notecard, objectid, user); } public bool CanEditObject(UUID objectid, UUID editorid, Scene scene) { return m_rootScene.Permissions.CanEditObject(objectid, editorid); } public bool CanEditObjectInventory(UUID objectid, UUID editorid, Scene scene) { return m_rootScene.Permissions.CanEditObjectInventory(objectid, editorid); } public bool CanEditParcelProperties(UUID user, ILandObject parcel, GroupPowers g, Scene scene) { return m_rootScene.Permissions.CanEditParcelProperties(user, parcel, g); } public bool CanEditScript(UUID script, UUID objectid, UUID user, Scene scene) { return m_rootScene.Permissions.CanEditScript(script, objectid, user); } public bool CanEditUserInventory(UUID itemid, UUID userid) { return m_rootScene.Permissions.CanEditUserInventory(itemid, userid); } public bool CanInstantMessage(UUID user, UUID target, Scene startscene) { return m_rootScene.Permissions.CanInstantMessage(user, target); } public bool CanInventoryTransfer(UUID user, UUID target, Scene startscene) { return m_rootScene.Permissions.CanInventoryTransfer(user, target); } public bool CanIssueEstateCommand(UUID user, Scene requestfromscene, bool ownercommand) { return m_rootScene.Permissions.CanIssueEstateCommand(user, ownercommand); } public bool CanLinkObject(UUID user, UUID objectid) { return m_rootScene.Permissions.CanLinkObject(user, objectid); } public bool CanMoveObject(UUID objectid, UUID moverid, Scene scene) { return m_rootScene.Permissions.CanMoveObject(objectid, moverid); } public bool CanObjectEntry(UUID objectid, bool enteringregion, Vector3 newpoint, Scene scene) { return m_rootScene.Permissions.CanObjectEntry(objectid, enteringregion, newpoint); } public bool CanReclaimParcel(UUID user, ILandObject parcel, Scene scene) { return m_rootScene.Permissions.CanReclaimParcel(user, parcel); } public bool CanResetScript(UUID prim, UUID script, UUID user, Scene scene) { return m_rootScene.Permissions.CanResetScript(prim, script, user); } public bool CanReturnObjects(ILandObject land, UUID user, List<SceneObjectGroup> objects, Scene scene) { return m_rootScene.Permissions.CanReturnObjects(land, user, objects); } public bool CanRezObject(int objectcount, UUID owner, Vector3 objectposition, Scene scene) { return m_rootScene.Permissions.CanRezObject(objectcount, owner, objectposition); } public bool CanRunConsoleCommand(UUID user, Scene requestfromscene) { return m_rootScene.Permissions.CanRunConsoleCommand(user); } public bool CanRunScript(UUID script, UUID objectid, UUID user, Scene scene) { return m_rootScene.Permissions.CanRunScript(script, objectid, user); } public bool CanSellParcel(UUID user, ILandObject parcel, Scene scene) { return m_rootScene.Permissions.CanSellParcel(user, parcel); } public bool CanTakeCopyObject(UUID objectid, UUID userid, Scene inscene) { return m_rootScene.Permissions.CanTakeObject(objectid, userid); } public bool CanTakeObject(UUID objectid, UUID stealer, Scene scene) { return m_rootScene.Permissions.CanTakeObject(objectid, stealer); } public bool CanTeleport(UUID userid, Scene scene) { return m_rootScene.Permissions.CanTeleport(userid); } public bool CanTerraformLand(UUID user, Vector3 position, Scene requestfromscene) { return m_rootScene.Permissions.CanTerraformLand(user, position); } public bool CanViewNotecard(UUID script, UUID objectid, UUID user, Scene scene) { return m_rootScene.Permissions.CanViewNotecard(script, objectid, user); } public bool CanViewScript(UUID script, UUID objectid, UUID user, Scene scene) { return m_rootScene.Permissions.CanViewScript(script, objectid, user); } public uint GenerateClientFlags(UUID userid, UUID objectidid) { return m_rootScene.Permissions.GenerateClientFlags(userid, objectidid); } public bool IsGod(UUID user, Scene requestfromscene) { return m_rootScene.Permissions.IsGod(user); } public bool PropagatePermissions() { return m_rootScene.Permissions.PropagatePermissions(); } public void SetBypassPermissions(bool value) { m_rootScene.Permissions.SetBypassPermissions(value); } #endregion Permission Override } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using ParquetSharp.Column; using ParquetSharp.Column.Impl; using ParquetSharp.Column.Page; using ParquetSharp.Column.Statistics; using ParquetSharp.Example.Data; using ParquetSharp.Example.Data.Simple; using ParquetSharp.Format.Converter; using ParquetSharp.Hadoop; using ParquetSharp.Hadoop.Example; using ParquetSharp.Hadoop.Metadata; using ParquetSharp.Hadoop.Util; using ParquetSharp.IO.Api; using ParquetSharp.Schema; using Xunit; using static ParquetSharp.Schema.PrimitiveType; namespace ParquetHadoopTests.Statistics { public class TestStatistics { private const int MEGABYTE = 1 << 20; private const long RANDOM_SEED = 1441990701846L; //Epoch.currentTimeMillis(); public static class DataGenerationContext { public abstract class WriteContext { protected readonly File path; protected readonly Path fsPath; protected readonly MessageType schema; protected readonly int blockSize; protected readonly int pageSize; protected readonly bool enableDictionary; protected readonly bool enableValidation; protected readonly ParquetProperties.WriterVersion version; public WriteContext(File path, MessageType schema, int blockSize, int pageSize, bool enableDictionary, bool enableValidation, ParquetProperties.WriterVersion version) { this.path = path; this.fsPath = new Path(path.ToString()); this.schema = schema; this.blockSize = blockSize; this.pageSize = pageSize; this.enableDictionary = enableDictionary; this.enableValidation = enableValidation; this.version = version; } public abstract void write(ParquetWriter<Group> writer); public abstract void test(); } public static void writeAndTest(WriteContext context) { // Create the configuration, and then apply the schema to our configuration. Configuration configuration = new Configuration(); GroupWriteSupport.setSchema(context.schema, configuration); GroupWriteSupport groupWriteSupport = new GroupWriteSupport(); // Create the writer properties int blockSize = context.blockSize; int pageSize = context.pageSize; int dictionaryPageSize = pageSize; bool enableDictionary = context.enableDictionary; bool enableValidation = context.enableValidation; ParquetProperties.WriterVersion writerVersion = context.version; CompressionCodecName codec = CompressionCodecName.UNCOMPRESSED; ParquetWriter<Group> writer = new ParquetWriter<Group>(context.fsPath, groupWriteSupport, codec, blockSize, pageSize, dictionaryPageSize, enableDictionary, enableValidation, writerVersion, configuration); context.write(writer); writer.close(); context.test(); context.path.delete(); } } public class SingletonPageReader : PageReader { private readonly DictionaryPage dict; private readonly DataPage data; public SingletonPageReader(DictionaryPage dict, DataPage data) { this.dict = dict; this.data = data; } public DictionaryPage readDictionaryPage() { return dict; } public long getTotalValueCount() { return data.getValueCount(); } public DataPage readPage() { return data; } } private static Statistics<T> getStatisticsFromPageHeader<T>(DataPage page) where T : IComparable<T> { return page.accept(new DataPageVisitor<T>()); } class DataPageVisitor<T> : DataPage.Visitor<Statistics<T>> where T : IComparable<T> { public Statistics<T> visit(DataPageV1 dataPageV1) { return (Statistics<T>)dataPageV1.getStatistics(); } public Statistics<T> visit(DataPageV2 dataPageV2) { return (Statistics<T>)dataPageV2.getStatistics(); } } class StatsValidator<T> where T : IComparable<T> { private readonly bool hasNonNull; private readonly T min; private readonly T max; public StatsValidator(DataPage page) { Statistics<T> stats = getStatisticsFromPageHeader(page); this.hasNonNull = stats.hasNonNullValue(); if (hasNonNull) { this.min = stats.genericGetMin(); this.max = stats.genericGetMax(); } else { this.min = null; this.max = null; } } public void validate(T value) { if (hasNonNull) { Assert.True("min should be <= all values", min.CompareTo(value) <= 0); Assert.True("min should be >= all values", max.CompareTo(value) >= 0); } } } private static PrimitiveConverter getValidatingConverter( DataPage page, PrimitiveType.PrimitiveTypeName type) { return type.convert(new ValidatingPrimitiveTypeConverter(page)); } class ValidatingPrimitiveTypeConverter : PrimitiveTypeNameConverter<PrimitiveConverter> { readonly DataPage page; public ValidatingPrimitiveTypeConverter(DataPage page) { this.page = page; } public PrimitiveConverter convertFLOAT(PrimitiveTypeName primitiveTypeName) { return new FloatConverter(this.page); } public PrimitiveConverter convertDOUBLE(PrimitiveTypeName primitiveTypeName) { return new DoubleConverter(this.page); } public PrimitiveConverter convertINT32(PrimitiveTypeName primitiveTypeName) { return new Int32Converter(this.page); } public PrimitiveConverter convertINT64(PrimitiveTypeName primitiveTypeName) { return new Int64Converter(this.page); } public PrimitiveConverter convertBOOLEAN(PrimitiveTypeName primitiveTypeName) { return new BooleanConverter(this.page); } public PrimitiveConverter convertINT96(PrimitiveTypeName primitiveTypeName) { return new BinaryConverter(this.page); } public PrimitiveConverter convertFIXED_LEN_BYTE_ARRAY(PrimitiveTypeName primitiveTypeName) { return new BinaryConverter(this.page); } public PrimitiveConverter convertBINARY(PrimitiveTypeName primitiveTypeName) { return new BinaryConverter(this.page); } class FloatConverter : PrimitiveConverter { readonly StatsValidator<float> validator; public FloatConverter(DataPage page) { this.validator = new StatsValidator<float>(page); } public override void addFloat(float value) { validator.validate(value); } } class DoubleConverter : PrimitiveConverter { readonly StatsValidator<double> validator; public DoubleConverter(DataPage page) { this.validator = new StatsValidator<double>(page); } public override void addDouble(double value) { validator.validate(value); } } class Int32Converter : PrimitiveConverter { readonly StatsValidator<int> validator; public Int32Converter(DataPage page) { this.validator = new StatsValidator<int>(page); } public override void addInt(int value) { validator.validate(value); } } class Int64Converter : PrimitiveConverter { readonly StatsValidator<long> validator; public Int64Converter(DataPage page) { this.validator = new StatsValidator<long>(page); } public override void addLong(long value) { validator.validate(value); } } class BooleanConverter : PrimitiveConverter { readonly StatsValidator<bool> validator; public BooleanConverter(DataPage page) { this.validator = new StatsValidator<bool>(page); } public override void addBoolean(bool value) { validator.validate(value); } } class BinaryConverter : PrimitiveConverter { readonly StatsValidator<Binary> validator; public BinaryConverter(DataPage page) { this.validator = new StatsValidator<Binary>(page); } public override void addBinary(Binary value) { validator.validate(value); } } } public class PageStatsValidator { public void validate(MessageType schema, PageReadStore store) { foreach (ColumnDescriptor desc in schema.getColumns()) { PageReader reader = store.getPageReader(desc); DictionaryPage dict = reader.readDictionaryPage(); DataPage page; while ((page = reader.readPage()) != null) { validateStatsForPage(page, dict, desc); } } } private void validateStatsForPage(DataPage page, DictionaryPage dict, ColumnDescriptor desc) { SingletonPageReader reader = new SingletonPageReader(dict, page); PrimitiveConverter converter = getValidatingConverter(page, desc.getType()); Statistics stats = getStatisticsFromPageHeader(page); long numNulls = 0; ColumnReaderImpl column = new ColumnReaderImpl(desc, reader, converter, null); for (int i = 0; i < reader.getTotalValueCount(); i += 1) { if (column.getCurrentDefinitionLevel() >= desc.getMaxDefinitionLevel()) { column.writeCurrentValueToConverter(); } else { numNulls += 1; } column.consume(); } Assert.Equal(numNulls, stats.getNumNulls()); System.Console.WriteLine(string.Format( "Validated stats min=%s max=%s nulls=%d for page=%s col=%s", string.valueOf(stats.genericGetMin()), string.valueOf(stats.genericGetMax()), stats.getNumNulls(), page, Arrays.ToString(desc.getPath()))); } } public class DataContext : DataGenerationContext.WriteContext { private const int MAX_TOTAL_ROWS = 1000000; private readonly int seed; private readonly Random random; private readonly int recordCount; private readonly int fixedLength; private readonly RandomValues.IntGenerator intGenerator; private readonly RandomValues.LongGenerator longGenerator; private readonly RandomValues.Int96Generator int96Generator; private readonly RandomValues.FloatGenerator floatGenerator; private readonly RandomValues.DoubleGenerator doubleGenerator; private readonly RandomValues.StringGenerator stringGenerator; private readonly RandomValues.BinaryGenerator binaryGenerator; private readonly RandomValues.FixedGenerator fixedBinaryGenerator; public DataContext(int seed, File path, int blockSize, int pageSize, bool enableDictionary, ParquetProperties.WriterVersion version) : base(path, buildSchema(seed), blockSize, pageSize, enableDictionary, true, version) { this.seed = seed; this.random = new Random(seed); this.recordCount = random.Next(MAX_TOTAL_ROWS); this.fixedLength = schema.getType("fixed-binary").asPrimitiveType().getTypeLength(); this.intGenerator = new RandomValues.IntGenerator(random.nextLong()); this.longGenerator = new RandomValues.LongGenerator(random.nextLong()); this.int96Generator = new RandomValues.Int96Generator(random.nextLong()); this.floatGenerator = new RandomValues.FloatGenerator(random.nextLong()); this.doubleGenerator = new RandomValues.DoubleGenerator(random.nextLong()); this.stringGenerator = new RandomValues.StringGenerator(random.nextLong()); this.binaryGenerator = new RandomValues.BinaryGenerator(random.nextLong()); this.fixedBinaryGenerator = new RandomValues.FixedGenerator(random.nextLong(), fixedLength); } private static MessageType buildSchema(int seed) { Random random = new Random(seed); int fixedBinaryLength = random.nextInt(21) + 1; return new MessageType("schema", new PrimitiveType(OPTIONAL, INT32, "i32"), new PrimitiveType(OPTIONAL, INT64, "i64"), new PrimitiveType(OPTIONAL, INT96, "i96"), new PrimitiveType(OPTIONAL, FLOAT, "sngl"), new PrimitiveType(OPTIONAL, DOUBLE, "dbl"), new PrimitiveType(OPTIONAL, BINARY, "strings"), new PrimitiveType(OPTIONAL, BINARY, "binary"), new PrimitiveType(OPTIONAL, FIXED_LEN_BYTE_ARRAY, fixedBinaryLength, "fixed-binary"), new PrimitiveType(REQUIRED, INT32, "unconstrained-i32"), new PrimitiveType(REQUIRED, INT64, "unconstrained-i64"), new PrimitiveType(REQUIRED, FLOAT, "unconstrained-sngl"), new PrimitiveType(REQUIRED, DOUBLE, "unconstrained-dbl") ); } public override void write(ParquetWriter<Group> writer) { for (int index = 0; index < recordCount; index++) { Group group = new SimpleGroup(base.schema); if (!intGenerator.shouldGenerateNull()) { group.append("i32", intGenerator.nextValue()); } if (!longGenerator.shouldGenerateNull()) { group.append("i64", longGenerator.nextValue()); } if (!int96Generator.shouldGenerateNull()) { group.append("i96", int96Generator.nextBinaryValue()); } if (!floatGenerator.shouldGenerateNull()) { group.append("sngl", floatGenerator.nextValue()); } if (!doubleGenerator.shouldGenerateNull()) { group.append("dbl", doubleGenerator.nextValue()); } if (!stringGenerator.shouldGenerateNull()) { group.append("strings", stringGenerator.nextBinaryValue()); } if (!binaryGenerator.shouldGenerateNull()) { group.append("binary", binaryGenerator.nextBinaryValue()); } if (!fixedBinaryGenerator.shouldGenerateNull()) { group.append("fixed-binary", fixedBinaryGenerator.nextBinaryValue()); } group.append("unconstrained-i32", random.nextInt()); group.append("unconstrained-i64", random.nextLong()); group.append("unconstrained-sngl", random.nextFloat()); group.append("unconstrained-dbl", random.nextDouble()); writer.write(group); } } public override void test() { Configuration configuration = new Configuration(); ParquetMetadata metadata = ParquetFileReader.readFooter(configuration, base.fsPath, ParquetMetadataConverter.NO_FILTER); ParquetFileReader reader = new ParquetFileReader(configuration, metadata.getFileMetaData(), base.fsPath, metadata.getBlocks(), metadata.getFileMetaData().getSchema().getColumns()); PageStatsValidator validator = new PageStatsValidator(); PageReadStore pageReadStore; while ((pageReadStore = reader.readNextRowGroup()) != null) { validator.validate(metadata.getFileMetaData().getSchema(), pageReadStore); } } } // @Rule public readonly TemporaryFolder folder = new TemporaryFolder(); [Fact] public void testStatistics() { File file = folder.newFile("test_file.parquet"); file.delete(); System.Console.WriteLine(string.Format("RANDOM SEED: %s", RANDOM_SEED)); Random random = new Random(RANDOM_SEED); int blockSize = (random.Next(54) + 10) * MEGABYTE; int pageSize = (random.Next(10) + 1) * MEGABYTE; List<DataContext> contexts = Arrays.asList( new DataContext(random.nextLong(), file, blockSize, pageSize, false, ParquetProperties.WriterVersion.PARQUET_1_0), new DataContext(random.nextLong(), file, blockSize, pageSize, true, ParquetProperties.WriterVersion.PARQUET_1_0), new DataContext(random.nextLong(), file, blockSize, pageSize, false, ParquetProperties.WriterVersion.PARQUET_2_0), new DataContext(random.nextLong(), file, blockSize, pageSize, true, ParquetProperties.WriterVersion.PARQUET_2_0) ); foreach (DataContext test in contexts) { DataGenerationContext.writeAndTest(test); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using DotVVM.Framework.Controls; using DotVVM.Framework.Utils; using System.Diagnostics; using DotVVM.Framework.Compilation; using DotVVM.Framework.Binding.Expressions; using DotVVM.Framework.Compilation.ControlTree; using DotVVM.Framework.Compilation.ControlTree.Resolved; using Newtonsoft.Json; namespace DotVVM.Framework.Binding { /// <summary> /// Represents a property of DotVVM controls. /// </summary> [DebuggerDisplay("{FullName}")] public class DotvvmProperty : IPropertyDescriptor { /// <summary> /// Gets or sets the name of the property. /// </summary> public string Name { get; protected set; } [JsonIgnore] ITypeDescriptor IControlAttributeDescriptor.DeclaringType => new ResolvedTypeDescriptor(DeclaringType); [JsonIgnore] ITypeDescriptor IControlAttributeDescriptor.PropertyType => new ResolvedTypeDescriptor(PropertyType); /// <summary> /// Gets the default value of the property. /// </summary> public object DefaultValue { get; protected set; } /// <summary> /// Gets the type of the property. /// </summary> public Type PropertyType { get; protected set; } /// <summary> /// Gets the type of the class where the property is registered. /// </summary> public Type DeclaringType { get; protected set; } /// <summary> /// Gets whether the value can be inherited from the parent controls. /// </summary> public bool IsValueInherited { get; protected set; } /// <summary> /// Gets or sets the Reflection property information. /// </summary> [JsonIgnore] public PropertyInfo PropertyInfo { get; private set; } /// <summary> /// Gets or sets the markup options. /// </summary> public MarkupOptionsAttribute MarkupOptions { get; set; } /// <summary> /// Virtual DotvvmProperty are not explicitly registred but marked with [MarkupOptions] attribute on DotvvmControl /// </summary> public bool IsVirtual { get; set; } /// <summary> /// Determines if property type inherits from IBinding /// </summary> public bool IsBindingProperty { get; private set; } /// <summary> /// Gets the full name of the descriptor. /// </summary> public string DescriptorFullName { get { return DeclaringType.FullName + "." + Name + "Property"; } } /// <summary> /// Gets the full name of the property. /// </summary> public string FullName { get { return DeclaringType.Name + "." + Name; } } [JsonIgnore] public DataContextChangeAttribute[] DataContextChangeAttributes { get; private set; } [JsonIgnore] public DataContextStackManipulationAttribute DataContextManipulationAttribute { get; private set; } /// <summary> /// Prevents a default instance of the <see cref="DotvvmProperty"/> class from being created. /// </summary> internal DotvvmProperty() { } /// <summary> /// Gets the value of the property. /// </summary> public virtual object GetValue(DotvvmBindableObject control, bool inherit = true) { object value; if (control.properties != null && control.properties.TryGetValue(this, out value)) { return value; } if (IsValueInherited && inherit && control.Parent != null) { return GetValue(control.Parent); } return DefaultValue; } /// <summary> /// Gets whether the value of the property is set /// </summary> public virtual bool IsSet(DotvvmBindableObject control, bool inherit = true) { if (control.properties != null && control.properties.ContainsKey(this)) { return true; } if (IsValueInherited && inherit && control.Parent != null) { return IsSet(control.Parent); } return false; } /// <summary> /// Sets the value of the property. /// </summary> public virtual void SetValue(DotvvmBindableObject control, object value) { control.Properties[this] = value; } /// <summary> /// Registers the specified DotVVM property. /// </summary> public static DotvvmProperty Register<TPropertyType, TDeclaringType>(Expression<Func<DotvvmProperty>> fieldAccessor, TPropertyType defaultValue = default(TPropertyType), bool isValueInherited = false) { var field = ReflectionUtils.GetMemberFromExpression(fieldAccessor.Body) as FieldInfo; if (field == null || !field.IsStatic) throw new ArgumentException("The expression should be simple static field access", nameof(fieldAccessor)); if (!field.Name.EndsWith("Property", StringComparison.Ordinal)) throw new ArgumentException($"DotVVM property backing field's '{field.Name}' name should end with 'Property'"); return Register<TPropertyType, TDeclaringType>(field.Name.Remove(field.Name.Length - "Property".Length), defaultValue, isValueInherited); } /// <summary> /// Registers the specified DotVVM property. /// </summary> public static DotvvmProperty Register<TPropertyType, TDeclaringType>(Expression<Func<TDeclaringType, object>> propertyAccessor, TPropertyType defaultValue = default(TPropertyType), bool isValueInherited = false) { var property = ReflectionUtils.GetMemberFromExpression(propertyAccessor.Body) as PropertyInfo; if (property == null) throw new ArgumentException("The expression should be simple property access", nameof(propertyAccessor)); return Register<TPropertyType, TDeclaringType>(property.Name, defaultValue, isValueInherited); } /// <summary> /// Registers the specified DotVVM property. /// </summary> public static DotvvmProperty Register<TPropertyType, TDeclaringType>(string propertyName, TPropertyType defaultValue = default(TPropertyType), bool isValueInherited = false, DotvvmProperty property = null) { var field = typeof(TDeclaringType).GetField(propertyName + "Property", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field == null) throw new ArgumentException($"'{typeof(TDeclaringType).Name}' does not contain static field '{propertyName}Property'."); return Register(propertyName, typeof(TPropertyType), typeof(TDeclaringType), defaultValue, isValueInherited, property, field); } public static DotvvmProperty Register(string propertyName, Type propertyType, Type declaringType, object defaultValue, bool isValueInherited, DotvvmProperty property, ICustomAttributeProvider attributeProvider) { var fullName = declaringType.FullName + "." + propertyName; if (property == null) property = new DotvvmProperty(); property.Name = propertyName; property.IsValueInherited = isValueInherited; property.DeclaringType = declaringType; property.PropertyType = propertyType; property.DefaultValue = defaultValue; InitializeProperty(property, attributeProvider); if (!registeredProperties.TryAdd(property.DeclaringType.FullName + "." + property.Name, property)) throw new ArgumentException($"Property is already registered: {fullName}"); return property; } public static void InitializeProperty(DotvvmProperty property, ICustomAttributeProvider attributeProvider) { var propertyInfo = property.DeclaringType.GetProperty(property.Name); var markupOptions = propertyInfo?.GetCustomAttribute<MarkupOptionsAttribute>() ?? attributeProvider.GetCustomAttribute<MarkupOptionsAttribute>() ?? new MarkupOptionsAttribute() { AllowBinding = true, AllowHardCodedValue = true, MappingMode = MappingMode.Attribute, Name = property.Name }; if (string.IsNullOrEmpty(markupOptions.Name)) markupOptions.Name = property.Name; if (property == null) property = new DotvvmProperty(); property.PropertyInfo = propertyInfo; property.DataContextChangeAttributes = (propertyInfo != null ? propertyInfo.GetCustomAttributes<DataContextChangeAttribute>(true) : attributeProvider.GetCustomAttributes<DataContextChangeAttribute>()).ToArray(); property.DataContextManipulationAttribute = propertyInfo != null ? propertyInfo.GetCustomAttribute<DataContextStackManipulationAttribute>(true) : attributeProvider.GetCustomAttribute<DataContextStackManipulationAttribute>(); if (property.DataContextManipulationAttribute != null && property.DataContextChangeAttributes.Any()) throw new ArgumentException($"{nameof(DataContextChangeAttributes)} and {nameof(DataContextManipulationAttribute)} can not be set both at property '{property.FullName}'."); property.MarkupOptions = markupOptions; property.IsBindingProperty = typeof(IBinding).IsAssignableFrom(property.PropertyType); } public static IEnumerable<DotvvmProperty> GetVirtualProperties(Type controlType) => from p in controlType.GetProperties(BindingFlags.Public | BindingFlags.Instance) where !registeredProperties.ContainsKey(p.DeclaringType.FullName + "." + p.Name) let markupOptions = GetVirtualPropertyMarkupOptions(p) where markupOptions != null where markupOptions.MappingMode != MappingMode.Exclude select new DotvvmProperty { DeclaringType = controlType, IsValueInherited = false, MarkupOptions = markupOptions, Name = p.Name, PropertyInfo = p, PropertyType = p.PropertyType, IsVirtual = true }; private static MarkupOptionsAttribute GetVirtualPropertyMarkupOptions(PropertyInfo p) { var mo = p.GetCustomAttribute<MarkupOptionsAttribute>(); if (mo == null) return null; mo.AllowBinding = false; return mo; } private static ConcurrentDictionary<string, DotvvmProperty> registeredProperties = new ConcurrentDictionary<string, DotvvmProperty>(); /// <summary> /// Resolves the <see cref="DotvvmProperty"/> by the declaring type and name. /// </summary> public static DotvvmProperty ResolveProperty(Type type, string name) { var fullName = type.FullName + "." + name; DotvvmProperty property; while (!registeredProperties.TryGetValue(fullName, out property) && type.GetTypeInfo().BaseType != null) { type = type.GetTypeInfo().BaseType; fullName = type.FullName + "." + name; } return property; } /// <summary> /// Resolves the <see cref="DotvvmProperty"/> from the full name (DeclaringTypeName.PropertyName). /// </summary> public static DotvvmProperty ResolveProperty(string fullName, bool caseSensitive = true) { return registeredProperties.Values.LastOrDefault(p => p.FullName.Equals(fullName, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Resolves all properties of specified type. /// </summary> public static IReadOnlyList<DotvvmProperty> ResolveProperties(Type type) { var types = new HashSet<Type>(); while (type.GetTypeInfo().BaseType != null) { types.Add(type); type = type.GetTypeInfo().BaseType; } return registeredProperties.Values.Where(p => types.Contains(p.DeclaringType)).ToList(); } /// <summary> /// Called when a control of the property type is created and initialized. /// </summary> protected internal virtual void OnControlInitialized(DotvvmBindableObject dotvvmControl) { } /// <summary> /// Called right before the page is rendered. /// </summary> public void OnControlRendering(DotvvmBindableObject dotvvmControl) { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MigAz.Azure.Core.Interface; using MigAz.Azure.Interface; using System.Net; using MigAz.Azure.Arm; using MigAz.Azure.Forms; using MigAz.Azure.Core; using Microsoft.IdentityModel.Clients.ActiveDirectory; namespace MigAz.Azure.UserControls { public partial class MigrationAzureSourceContext : UserControl, IMigrationSourceUserControl { private AzureContext _AzureContextSource; private List<TreeNode> _SelectedNodes = new List<TreeNode>(); private TreeNode _SourceAsmNode; private TargetSettings _TargetSettings; private ImageList _ImageList; private ArmDiskType _DefaultTargetDiskType = ArmDiskType.ManagedDisk; private bool _AutoSelectDependencies = true; private bool _IsAuthenticated = false; private ILogProvider _LogProvider; private IStatusProvider _StatusProvider; #region Matching Events from AzureContext public delegate Task BeforeAzureTenantChangedHandler(AzureContext sender); public event BeforeAzureTenantChangedHandler BeforeAzureTenantChange; public delegate Task AfterAzureTenantChangedHandler(AzureContext sender); public event AfterAzureTenantChangedHandler AfterAzureTenantChange; public delegate Task BeforeAzureSubscriptionChangedHandler(AzureContext sender); public event BeforeAzureSubscriptionChangedHandler BeforeAzureSubscriptionChange; public delegate Task AfterAzureSubscriptionChangedHandler(AzureContext sender); public event AfterAzureSubscriptionChangedHandler AfterAzureSubscriptionChange; public delegate Task AzureEnvironmentChangedHandler(AzureContext sender); public event AzureEnvironmentChangedHandler AzureEnvironmentChanged; public delegate Task UserAuthenticatedHandler(AzureContext sender); public event UserAuthenticatedHandler UserAuthenticated; public delegate Task BeforeUserSignOutHandler(); public event BeforeUserSignOutHandler BeforeUserSignOut; public delegate Task AfterUserSignOutHandler(); public event AfterUserSignOutHandler AfterUserSignOut; #endregion #region New Events from MigrationSourceAzure public delegate Task AfterNodeCheckedHandler(Core.MigrationTarget sender); public event AfterNodeCheckedHandler AfterNodeChecked; public delegate Task AfterNodeUncheckedHandler(Core.MigrationTarget sender); public event AfterNodeUncheckedHandler AfterNodeUnchecked; public delegate Task AfterNodeChangedHandler(Core.MigrationTarget sender); public event AfterNodeChangedHandler AfterNodeChanged; public delegate void ClearContextHandler(); public event ClearContextHandler ClearContext; public delegate void AfterContextChangedHandler(UserControl sender); public event AfterContextChangedHandler AfterContextChanged; #endregion #region Constructor(s) public MigrationAzureSourceContext() { InitializeComponent(); cmbAzureResourceTypeSource.SelectedIndex = 0; treeAzureASM.Left = 0; treeAzureASM.Width = this.Width; treeViewSourceResourceManager1.Left = 0; treeViewSourceResourceManager1.Width = this.Width; } #endregion #region Properties public ILogProvider LogProvider { get { return _LogProvider; } } public bool IsSourceContextAuthenticated { get { return _IsAuthenticated; } set { _IsAuthenticated = value; } } public String MigrationSourceType { get { return cmbAzureResourceTypeSource.SelectedItem.ToString(); } } public AzureContext AzureContext { get { return _AzureContextSource; } } public ArmDiskType DefaultTargetDiskType { get { return _DefaultTargetDiskType; } set { _DefaultTargetDiskType = value; } } public bool AutoSelectDependencies { get { return _AutoSelectDependencies; } set { _AutoSelectDependencies = value; } } #endregion #region Methods public void Bind(AzureRetriever azureRetriever, IStatusProvider statusProvider, ILogProvider logProvider, TargetSettings targetSettings, ImageList imageList, PromptBehavior promptBehavior, List<AzureEnvironment> azureEnvironments, ref List<AzureEnvironment> userDefinedAzureEnvironments) { _TargetSettings = targetSettings; _LogProvider = logProvider; _StatusProvider = statusProvider; _ImageList = imageList; _AzureContextSource = new AzureContext(azureRetriever, targetSettings, promptBehavior); _AzureContextSource.AzureEnvironmentChanged += _AzureContext_AzureEnvironmentChanged; _AzureContextSource.UserAuthenticated += _AzureContext_UserAuthenticated; _AzureContextSource.BeforeAzureSubscriptionChange += _AzureContext_BeforeAzureSubscriptionChange; _AzureContextSource.AfterAzureSubscriptionChange += _AzureContext_AfterAzureSubscriptionChange; _AzureContextSource.BeforeUserSignOut += _AzureContext_BeforeUserSignOut; _AzureContextSource.AfterUserSignOut += _AzureContext_AfterUserSignOut; _AzureContextSource.AfterAzureTenantChange += _AzureContext_AfterAzureTenantChange; _AzureContextSource.BeforeAzureTenantChange += _AzureContextSource_BeforeAzureTenantChange; azureLoginContextViewerSource.AfterContextChanged += AzureLoginContextViewerSource_AfterContextChanged; azureLoginContextViewerSource.Bind(_AzureContextSource, azureRetriever, azureEnvironments, ref userDefinedAzureEnvironments); treeViewSourceResourceManager1.Bind(logProvider, statusProvider, targetSettings, imageList, promptBehavior); } private void ResetForm() { if (treeAzureASM != null) { treeAzureASM.Enabled = false; treeAzureASM.Nodes.Clear(); } if (treeViewSourceResourceManager1 != null) { treeViewSourceResourceManager1.Enabled = false; treeViewSourceResourceManager1.ResetForm(); } if (_SelectedNodes != null) _SelectedNodes.Clear(); ClearContext?.Invoke(); } #endregion #region Event Handlers private async Task AzureLoginContextViewerSource_AfterContextChanged(AzureLoginContextViewer sender) { AfterContextChanged?.Invoke(this); } private async Task _AzureContextSource_BeforeAzureTenantChange(AzureContext sender) { BeforeAzureTenantChange?.Invoke(sender); } private async Task _AzureContext_AfterAzureTenantChange(AzureContext sender) { AfterAzureTenantChange?.Invoke(sender); } private async Task _AzureContext_BeforeAzureSubscriptionChange(AzureContext sender) { BeforeAzureSubscriptionChange?.Invoke(sender); } private async Task _AzureContext_AzureEnvironmentChanged(AzureContext sender) { AzureEnvironmentChanged?.Invoke(sender); } private async Task _AzureContext_UserAuthenticated(AzureContext sender) { this.IsSourceContextAuthenticated = true; UserAuthenticated?.Invoke(sender); } private async Task _AzureContext_BeforeUserSignOut() { await BeforeUserSignOut?.Invoke(); } private async Task _AzureContext_AfterUserSignOut() { ResetForm(); this.IsSourceContextAuthenticated = false; await AfterUserSignOut?.Invoke(); } private async Task _AzureContext_AfterAzureSubscriptionChange(AzureContext sender) { try { ResetForm(); if (sender.AzureSubscription != null) { switch (cmbAzureResourceTypeSource.SelectedItem.ToString()) { case "Azure Service Management (ASM / Classic)": await BindAsmResources(sender, _TargetSettings); break; case "Azure Resource Manager (ARM)": treeViewSourceResourceManager1.Enabled = true; treeViewSourceResourceManager1.Visible = true; await sender.AzureSubscription.InitializeChildrenAsync(); await sender.AzureSubscription.BindArmResources(_TargetSettings); await treeViewSourceResourceManager1.BindArmResources(sender, sender.AzureSubscription, _TargetSettings); break; default: throw new ArgumentException("Unexpected Source Resource Tab: " + cmbAzureResourceTypeSource.SelectedValue); } _AzureContextSource.AzureRetriever.SaveRestCache(); } } catch (Exception exc) { UnhandledExceptionDialog unhandledException = new UnhandledExceptionDialog(_AzureContextSource.LogProvider, exc); unhandledException.ShowDialog(); } _AzureContextSource.StatusProvider.UpdateStatus("Ready"); AfterAzureSubscriptionChange?.Invoke(sender); } private async Task BindAsmResources(AzureContext azureContext, TargetSettings targetSettings) { treeAzureASM.Nodes.Clear(); try { if (_AzureContextSource != null && _AzureContextSource.AzureSubscription != null) { await _AzureContextSource.AzureSubscription.BindAsmResources(targetSettings); if (_AzureContextSource != null && _AzureContextSource.AzureSubscription != null) { TreeNode subscriptionNodeASM = new TreeNode(_AzureContextSource.AzureSubscription.Name); treeAzureASM.Nodes.Add(subscriptionNodeASM); subscriptionNodeASM.Expand(); foreach (Azure.MigrationTarget.NetworkSecurityGroup targetNetworkSecurityGroup in _AzureContextSource.AzureSubscription.AsmTargetNetworkSecurityGroups) { Azure.Asm.NetworkSecurityGroup asmNetworkSecurityGroup = (Azure.Asm.NetworkSecurityGroup)targetNetworkSecurityGroup.SourceNetworkSecurityGroup; TreeNode parentNode = GetDataCenterTreeViewNode(subscriptionNodeASM, asmNetworkSecurityGroup.Location, "Network Security Groups"); TreeNode tnNetworkSecurityGroup = new TreeNode(targetNetworkSecurityGroup.SourceName); tnNetworkSecurityGroup.Name = targetNetworkSecurityGroup.SourceName; tnNetworkSecurityGroup.Tag = targetNetworkSecurityGroup; parentNode.Nodes.Add(tnNetworkSecurityGroup); parentNode.Expand(); } foreach (Azure.MigrationTarget.VirtualNetwork targetVirtualNetwork in _AzureContextSource.AzureSubscription.AsmTargetVirtualNetworks) { Azure.Asm.VirtualNetwork asmVirtualNetwork = (Azure.Asm.VirtualNetwork)targetVirtualNetwork.SourceVirtualNetwork; TreeNode parentNode = GetDataCenterTreeViewNode(subscriptionNodeASM, asmVirtualNetwork.Location, "Virtual Networks"); TreeNode tnVirtualNetwork = new TreeNode(targetVirtualNetwork.SourceName); tnVirtualNetwork.Name = targetVirtualNetwork.SourceName; tnVirtualNetwork.Text = targetVirtualNetwork.SourceName; tnVirtualNetwork.Tag = targetVirtualNetwork; parentNode.Nodes.Add(tnVirtualNetwork); parentNode.Expand(); } foreach (Azure.MigrationTarget.StorageAccount targetStorageAccount in _AzureContextSource.AzureSubscription.AsmTargetStorageAccounts) { TreeNode parentNode = GetDataCenterTreeViewNode(subscriptionNodeASM, targetStorageAccount.SourceAccount.PrimaryLocation, "Storage Accounts"); TreeNode tnStorageAccount = new TreeNode(targetStorageAccount.SourceName); tnStorageAccount.Name = targetStorageAccount.SourceName; tnStorageAccount.Tag = targetStorageAccount; parentNode.Nodes.Add(tnStorageAccount); parentNode.Expand(); } foreach (Azure.MigrationTarget.VirtualMachine targetVirtualMachine in _AzureContextSource.AzureSubscription.AsmTargetVirtualMachines) { Azure.Asm.VirtualMachine asmVirtualMachine = (Azure.Asm.VirtualMachine)targetVirtualMachine.Source; TreeNode parentNode = GetDataCenterTreeViewNode(subscriptionNodeASM, asmVirtualMachine.Location, "Cloud Services"); TreeNode[] cloudServiceNodeSearch = parentNode.Nodes.Find(targetVirtualMachine.TargetAvailabilitySet.TargetName, false); TreeNode cloudServiceNode = null; if (cloudServiceNodeSearch.Count() == 1) { cloudServiceNode = cloudServiceNodeSearch[0]; } cloudServiceNode = new TreeNode(targetVirtualMachine.TargetAvailabilitySet.TargetName); cloudServiceNode.Name = targetVirtualMachine.TargetAvailabilitySet.TargetName; cloudServiceNode.Tag = targetVirtualMachine.TargetAvailabilitySet; parentNode.Nodes.Add(cloudServiceNode); parentNode.Expand(); TreeNode virtualMachineNode = new TreeNode(targetVirtualMachine.SourceName); virtualMachineNode.Name = targetVirtualMachine.SourceName; virtualMachineNode.Tag = targetVirtualMachine; cloudServiceNode.Nodes.Add(virtualMachineNode); cloudServiceNode.Expand(); foreach (Azure.MigrationTarget.NetworkInterface targetNetworkInterface in targetVirtualMachine.NetworkInterfaces) { if (targetNetworkInterface.BackEndAddressPool != null && targetNetworkInterface.BackEndAddressPool.LoadBalancer != null) { TreeNode loadBalancerNode = new TreeNode(targetNetworkInterface.BackEndAddressPool.LoadBalancer.SourceName); loadBalancerNode.Name = targetNetworkInterface.BackEndAddressPool.LoadBalancer.SourceName; loadBalancerNode.Tag = targetNetworkInterface.BackEndAddressPool.LoadBalancer; cloudServiceNode.Nodes.Add(loadBalancerNode); cloudServiceNode.Expand(); foreach (Azure.MigrationTarget.FrontEndIpConfiguration frontEnd in targetNetworkInterface.BackEndAddressPool.LoadBalancer.FrontEndIpConfigurations) { if (frontEnd.PublicIp != null && frontEnd.PublicIp.GetType() == typeof(MigrationTarget.PublicIp)) // if external load balancer { MigrationTarget.PublicIp targetPublicIp = (MigrationTarget.PublicIp)frontEnd.PublicIp; TreeNode publicIPAddressNode = new TreeNode(targetPublicIp.SourceName); publicIPAddressNode.Name = targetPublicIp.SourceName; publicIPAddressNode.Tag = targetPublicIp; cloudServiceNode.Nodes.Add(publicIPAddressNode); cloudServiceNode.Expand(); } } } } } subscriptionNodeASM.Expand(); treeAzureASM.Enabled = true; } } } catch (Exception exc) { if (exc.GetType() == typeof(System.Net.WebException)) { System.Net.WebException webException = (System.Net.WebException)exc; if (webException.Response != null) { HttpWebResponse exceptionResponse = (HttpWebResponse)webException.Response; if (exceptionResponse.StatusCode == HttpStatusCode.Forbidden) { ASM403ForbiddenExceptionDialog forbiddenDialog = new ASM403ForbiddenExceptionDialog(_AzureContextSource.LogProvider, exc); return; } } } UnhandledExceptionDialog exceptionDialog = new UnhandledExceptionDialog(_AzureContextSource.LogProvider, exc); exceptionDialog.ShowDialog(); } _AzureContextSource.StatusProvider.UpdateStatus("Ready"); } #endregion #region Source Resource TreeView Methods private async Task SelectDependencies(TreeNode selectedNode) { if (this.AutoSelectDependencies && (selectedNode.Checked) && (selectedNode.Tag != null)) { if (selectedNode.Tag.GetType() == typeof(Azure.MigrationTarget.AvailabilitySet)) { Azure.MigrationTarget.AvailabilitySet targetAvailabilitySet = (Azure.MigrationTarget.AvailabilitySet)selectedNode.Tag; foreach (Azure.MigrationTarget.VirtualMachine targetVirtualMachine in targetAvailabilitySet.TargetVirtualMachines) { foreach (TreeNode treeNode in selectedNode.TreeView.Nodes.Find(targetVirtualMachine.TargetName, true)) { if ((treeNode.Tag != null) && (treeNode.Tag.GetType() == typeof(Azure.MigrationTarget.VirtualMachine))) { if (!treeNode.Checked) treeNode.Checked = true; } } } } if (selectedNode.Tag.GetType() == typeof(Azure.MigrationTarget.VirtualMachine)) { Azure.MigrationTarget.VirtualMachine targetVirtualMachine = (Azure.MigrationTarget.VirtualMachine)selectedNode.Tag; if (targetVirtualMachine.Source != null) { if (targetVirtualMachine.Source.GetType() == typeof(Azure.Asm.VirtualMachine)) { Azure.Asm.VirtualMachine asmVirtualMachine = (Azure.Asm.VirtualMachine)targetVirtualMachine.Source; #region process virtual network foreach (Azure.MigrationTarget.NetworkInterface networkInterface in targetVirtualMachine.NetworkInterfaces) { #region Auto Select Virtual Network from each IpConfiguration // This source code to auto select the Virtual Network as a Parent node has been commented out purposefully. // It was observed through use of MigAz that users were not aware that "including the Virtual Network" in multiple // migrations was actually creating new / independent / non-connected versions of the same Virtual Network. // It is valid that the user would want to migrate the Virtual Network during the first run migration; however, beyond // that first pass (the Azure ARM Virtual Network exists) the user is more likely to need to migrate the Virtual Machine(s) // into an existing Azure Virtual Network. In order to guide the user in this direction, we do not want to auto select the // source Virtual Network to be included in the Migration Template as a new Virtual Network. We want the user to explicitly // select and include the source Azure Virtual Network into the Migration Template (if they want to include it), or utilize // the built in property editor dialogs to "select an existing Virtual Network and Subnet". //foreach (Azure.MigrationTarget.NetworkInterfaceIpConfiguration ipConfiguration in networkInterface.TargetNetworkInterfaceIpConfigurations) //{ // if (ipConfiguration.TargetVirtualNetwork != null && ipConfiguration.TargetVirtualNetwork.GetType() == typeof(Azure.MigrationTarget.VirtualNetwork)) // { // Azure.MigrationTarget.VirtualNetwork targetVirtualNetwork = (Azure.MigrationTarget.VirtualNetwork)ipConfiguration.TargetVirtualNetwork; // foreach (TreeNode treeNode in selectedNode.TreeView.Nodes.Find(targetVirtualNetwork.SourceName, true)) // { // if ((treeNode.Tag != null) && (treeNode.Tag.GetType() == typeof(Azure.MigrationTarget.VirtualNetwork))) // { // if (!treeNode.Checked) // treeNode.Checked = true; // } // } // } //} #endregion #region Auto Select Network Security Group if (asmVirtualMachine.NetworkSecurityGroup != null) { foreach (TreeNode treeNode in selectedNode.TreeView.Nodes.Find(asmVirtualMachine.NetworkSecurityGroup.Name, true)) { if ((treeNode.Tag != null) && (treeNode.Tag.GetType() == typeof(Azure.MigrationTarget.NetworkSecurityGroup))) { if (!treeNode.Checked) treeNode.Checked = true; } } } #endregion } #endregion } } } else if (selectedNode.Tag.GetType() == typeof(Azure.MigrationTarget.VirtualNetwork)) { Azure.MigrationTarget.VirtualNetwork targetVirtualNetwork = (Azure.MigrationTarget.VirtualNetwork)selectedNode.Tag; foreach (Azure.MigrationTarget.Subnet targetSubnet in targetVirtualNetwork.TargetSubnets) { if (targetSubnet.NetworkSecurityGroup != null) { if (targetSubnet.NetworkSecurityGroup.SourceNetworkSecurityGroup != null) { if (targetSubnet.NetworkSecurityGroup.SourceNetworkSecurityGroup.GetType() == typeof(Azure.Asm.NetworkSecurityGroup)) { foreach (TreeNode treeNode in selectedNode.TreeView.Nodes.Find(targetSubnet.NetworkSecurityGroup.SourceName, true)) { if ((treeNode.Tag != null) && (treeNode.Tag.GetType() == typeof(Azure.MigrationTarget.NetworkSecurityGroup))) { if (!treeNode.Checked) treeNode.Checked = true; } } } } } } } _AzureContextSource.StatusProvider.UpdateStatus("Ready"); } } private async void treeAzureASM_AfterCheck(object sender, TreeViewEventArgs e) { if (_SourceAsmNode == null) { _SourceAsmNode = e.Node; } if (e.Node.Checked) await SelectDependencies(e.Node); TreeNode resultUpdateARMTree = null; Core.MigrationTarget migrationTarget = null; if (e.Node.Tag != null && e.Node.Tag.GetType().BaseType == typeof(Core.MigrationTarget)) { migrationTarget = (Core.MigrationTarget)e.Node.Tag; if (e.Node.Checked) { resultUpdateARMTree = e.Node; AfterNodeChecked?.Invoke(migrationTarget); } else { AfterNodeUnchecked?.Invoke(migrationTarget); } } if (_SourceAsmNode != null && _SourceAsmNode == e.Node) { if (e.Node.Checked) { await RecursiveCheckToggleDown(e.Node, e.Node.Checked); FillUpIfFullDown(e.Node); treeAzureASM.SelectedNode = e.Node; } else { await RecursiveCheckToggleUp(e.Node, e.Node.Checked); await RecursiveCheckToggleDown(e.Node, e.Node.Checked); } _SelectedNodes = this.GetSelectedNodes(treeAzureASM); _SourceAsmNode = null; AfterNodeChanged?.Invoke(migrationTarget); } } private List<TreeNode> GetSelectedNodes(TreeView treeView) { List<TreeNode> selectedNodes = new List<TreeNode>(); foreach (TreeNode treeNode in treeView.Nodes) { RecursiveNodeSelectedAdd(ref selectedNodes, treeNode); } return selectedNodes; } private void RecursiveNodeSelectedAdd(ref List<TreeNode> selectedNodes, TreeNode parentNode) { if (parentNode.Checked && parentNode.Tag != null && (parentNode.Tag.GetType() == typeof(Azure.MigrationTarget.NetworkSecurityGroup) || parentNode.Tag.GetType() == typeof(Azure.MigrationTarget.VirtualNetwork) || parentNode.Tag.GetType() == typeof(Azure.MigrationTarget.StorageAccount) || parentNode.Tag.GetType() == typeof(Azure.MigrationTarget.VirtualMachine) )) selectedNodes.Add(parentNode); foreach (TreeNode childNode in parentNode.Nodes) { RecursiveNodeSelectedAdd(ref selectedNodes, childNode); } } private void FillUpIfFullDown(TreeNode node) { if (IsSelectedFullDown(node) && (node.Parent != null)) { node = node.Parent; while (node != null) { if (AllChildrenChecked(node)) { node.Checked = true; node = node.Parent; } else node = null; } } } private bool AllChildrenChecked(TreeNode node) { foreach (TreeNode childNode in node.Nodes) if (!childNode.Checked) return false; return true; } #endregion private TreeNode GetDataCenterTreeViewNode(TreeNode subscriptionNode, string dataCenter, string containerName) { TreeNode dataCenterNode = null; foreach (TreeNode treeNode in subscriptionNode.Nodes) { if (treeNode.Text == dataCenter && treeNode.Tag.ToString() == "DataCenter") { dataCenterNode = treeNode; foreach (TreeNode dataCenterContainerNode in treeNode.Nodes) { if (dataCenterContainerNode.Text == containerName) return dataCenterContainerNode; } } } if (dataCenterNode == null) { dataCenterNode = new TreeNode(dataCenter); dataCenterNode.Tag = "DataCenter"; subscriptionNode.Nodes.Add(dataCenterNode); dataCenterNode.Expand(); } TreeNode containerNode = new TreeNode(containerName); dataCenterNode.Nodes.Add(containerNode); containerNode.Expand(); return containerNode; } private bool IsSelectedFullDown(TreeNode node) { if (!node.Checked) return false; foreach (TreeNode childNode in node.Nodes) { if (!IsSelectedFullDown(childNode)) return false; } return true; } private async Task RecursiveCheckToggleDown(TreeNode node, bool isChecked) { if (node.Checked != isChecked) { node.Checked = isChecked; } foreach (TreeNode subNode in node.Nodes) { await RecursiveCheckToggleDown(subNode, isChecked); } } private async Task RecursiveCheckToggleUp(TreeNode node, bool isChecked) { if (node.Checked != isChecked) { node.Checked = isChecked; } if (node.Parent != null) await RecursiveCheckToggleUp(node.Parent, isChecked); } private async void cmbAzureResourceTypeSource_SelectedIndexChanged(object sender, EventArgs e) { treeAzureASM.Nodes.Clear(); treeViewSourceResourceManager1.ResetForm(); switch (cmbAzureResourceTypeSource.SelectedItem.ToString()) { case "Azure Service Management (ASM / Classic)": treeAzureASM.Enabled = true; treeAzureASM.Visible = true; treeViewSourceResourceManager1.Enabled = false; treeViewSourceResourceManager1.Visible = false; await BindAsmResources(_AzureContextSource, _TargetSettings); break; case "Azure Resource Manager (ARM)": treeAzureASM.Enabled = false; treeAzureASM.Visible = false; treeViewSourceResourceManager1.Enabled = true; treeViewSourceResourceManager1.Visible = true; if (_TargetSettings != null) await treeViewSourceResourceManager1.BindArmResources(_AzureContextSource, _AzureContextSource.AzureSubscription, _TargetSettings); break; default: throw new ArgumentException("Unknown Azure Resource Type Source: " + cmbAzureResourceTypeSource.SelectedItem.ToString()); } ClearContext?.Invoke(); } private void MigrationSourceAzure_Resize(object sender, EventArgs e) { treeViewSourceResourceManager1.Height = this.Height - 135; treeViewSourceResourceManager1.Width = this.Width; treeAzureASM.Height = this.Height - 135; treeAzureASM.Width = this.Width; azureLoginContextViewerSource.Width = this.Width; } public async Task UncheckMigrationTarget(Core.MigrationTarget migrationTarget) { LogProvider.WriteLog("UncheckMigrationTarget", "Start"); if (treeViewSourceResourceManager1.Enabled) { LogProvider.WriteLog("UncheckMigrationTarget", "Seeking Originating MigrationTarget TreeNode in treeViewSourceResourceManager1"); await treeViewSourceResourceManager1.UncheckMigrationTarget(migrationTarget); } else if (treeAzureASM.Enabled) { TreeNode sourceMigrationNode = null; LogProvider.WriteLog("UncheckMigrationTarget", "Seeking Originating MigrationTarget TreeNode in treeAzureASM"); sourceMigrationNode = TargetTreeView.SeekMigrationTargetTreeNode(treeAzureASM.Nodes, migrationTarget); if (sourceMigrationNode == null) { LogProvider.WriteLog("UncheckMigrationTarget", "Originating MigrationTarget TreeNode not found."); } else { LogProvider.WriteLog("UncheckMigrationTarget", "Seeking Originating MigrationTarget TreeNode"); sourceMigrationNode.Checked = false; } } LogProvider.WriteLog("UncheckMigrationTarget", "End"); } private async Task treeViewSourceResourceManager1_AfterNodeChecked(Core.MigrationTarget sender) { await AfterNodeChecked?.Invoke(sender); } private async Task treeViewSourceResourceManager1_AfterNodeUnchecked(Core.MigrationTarget sender) { await AfterNodeUnchecked?.Invoke(sender); } private async Task treeViewSourceResourceManager1_AfterNodeChanged(Core.MigrationTarget sender) { await AfterNodeChanged?.Invoke(sender); } private void treeViewSourceResourceManager1_ClearContext() { ClearContext?.Invoke(); } private void treeViewSourceResourceManager1_AfterContextChanged(UserControl sender) { AfterContextChanged?.Invoke(sender); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tenancy_config/room_call_billing_rates.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.TenancyConfig { /// <summary>Holder for reflection information generated from tenancy_config/room_call_billing_rates.proto</summary> public static partial class RoomCallBillingRatesReflection { #region Descriptor /// <summary>File descriptor for tenancy_config/room_call_billing_rates.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static RoomCallBillingRatesReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cix0ZW5hbmN5X2NvbmZpZy9yb29tX2NhbGxfYmlsbGluZ19yYXRlcy5wcm90", "bxIaaG9sbXMudHlwZXMudGVuYW5jeV9jb25maWcaHmdvb2dsZS9wcm90b2J1", "Zi9kdXJhdGlvbi5wcm90bxofcHJpbWl0aXZlL21vbmV0YXJ5X2Ftb3VudC5w", "cm90byLoBQoUUm9vbUNhbGxCaWxsaW5nUmF0ZXMSOQoWZnJlZV9jYWxsX2dy", "YWNlX3BlcmlvZBgBIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbhIX", "Cg9sb2NhbF9hcmVhX2NvZGUYAiABKAkSSAoZbG9jYWxfZmlyc3RfbWludXRl", "X2NoYXJnZRgDIAEoCzIlLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5Nb25ldGFy", "eUFtb3VudBJNCh5sb2NhbF9hZGRpdGlvbmFsX21pbnV0ZV9jaGFyZ2UYBCAB", "KAsyJS5ob2xtcy50eXBlcy5wcmltaXRpdmUuTW9uZXRhcnlBbW91bnQSUAoh", "bG9uZ19kaXN0YW5jZV9maXJzdF9taW51dGVfY2hhcmdlGAUgASgLMiUuaG9s", "bXMudHlwZXMucHJpbWl0aXZlLk1vbmV0YXJ5QW1vdW50ElUKJmxvbmdfZGlz", "dGFuY2VfYWRkaXRpb25hbF9taW51dGVfY2hhcmdlGAYgASgLMiUuaG9sbXMu", "dHlwZXMucHJpbWl0aXZlLk1vbmV0YXJ5QW1vdW50ElAKIWludGVybmF0aW9u", "YWxfZmlyc3RfbWludXRlX2NoYXJnZRgHIAEoCzIlLmhvbG1zLnR5cGVzLnBy", "aW1pdGl2ZS5Nb25ldGFyeUFtb3VudBJVCiZpbnRlcm5hdGlvbmFsX2FkZGl0", "aW9uYWxfbWludXRlX2NoYXJnZRgIIAEoCzIlLmhvbG1zLnR5cGVzLnByaW1p", "dGl2ZS5Nb25ldGFyeUFtb3VudBJCChN0b2xsX2ZyZWVfZmxhdF9yYXRlGAkg", "ASgLMiUuaG9sbXMudHlwZXMucHJpbWl0aXZlLk1vbmV0YXJ5QW1vdW50Ek0K", "HmRpcmVjdG9yeV9hc3Npc3RhbmNlX2ZsYXRfcmF0ZRgKIAEoCzIlLmhvbG1z", "LnR5cGVzLnByaW1pdGl2ZS5Nb25ldGFyeUFtb3VudEIrWg10ZW5hbmN5Y29u", "ZmlnqgIZSE9MTVMuVHlwZXMuVGVuYW5jeUNvbmZpZ2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RoomCallBillingRates), global::HOLMS.Types.TenancyConfig.RoomCallBillingRates.Parser, new[]{ "FreeCallGracePeriod", "LocalAreaCode", "LocalFirstMinuteCharge", "LocalAdditionalMinuteCharge", "LongDistanceFirstMinuteCharge", "LongDistanceAdditionalMinuteCharge", "InternationalFirstMinuteCharge", "InternationalAdditionalMinuteCharge", "TollFreeFlatRate", "DirectoryAssistanceFlatRate" }, null, null, null) })); } #endregion } #region Messages public sealed partial class RoomCallBillingRates : pb::IMessage<RoomCallBillingRates> { private static readonly pb::MessageParser<RoomCallBillingRates> _parser = new pb::MessageParser<RoomCallBillingRates>(() => new RoomCallBillingRates()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RoomCallBillingRates> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.TenancyConfig.RoomCallBillingRatesReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomCallBillingRates() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomCallBillingRates(RoomCallBillingRates other) : this() { FreeCallGracePeriod = other.freeCallGracePeriod_ != null ? other.FreeCallGracePeriod.Clone() : null; localAreaCode_ = other.localAreaCode_; LocalFirstMinuteCharge = other.localFirstMinuteCharge_ != null ? other.LocalFirstMinuteCharge.Clone() : null; LocalAdditionalMinuteCharge = other.localAdditionalMinuteCharge_ != null ? other.LocalAdditionalMinuteCharge.Clone() : null; LongDistanceFirstMinuteCharge = other.longDistanceFirstMinuteCharge_ != null ? other.LongDistanceFirstMinuteCharge.Clone() : null; LongDistanceAdditionalMinuteCharge = other.longDistanceAdditionalMinuteCharge_ != null ? other.LongDistanceAdditionalMinuteCharge.Clone() : null; InternationalFirstMinuteCharge = other.internationalFirstMinuteCharge_ != null ? other.InternationalFirstMinuteCharge.Clone() : null; InternationalAdditionalMinuteCharge = other.internationalAdditionalMinuteCharge_ != null ? other.InternationalAdditionalMinuteCharge.Clone() : null; TollFreeFlatRate = other.tollFreeFlatRate_ != null ? other.TollFreeFlatRate.Clone() : null; DirectoryAssistanceFlatRate = other.directoryAssistanceFlatRate_ != null ? other.DirectoryAssistanceFlatRate.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomCallBillingRates Clone() { return new RoomCallBillingRates(this); } /// <summary>Field number for the "free_call_grace_period" field.</summary> public const int FreeCallGracePeriodFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Duration freeCallGracePeriod_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration FreeCallGracePeriod { get { return freeCallGracePeriod_; } set { freeCallGracePeriod_ = value; } } /// <summary>Field number for the "local_area_code" field.</summary> public const int LocalAreaCodeFieldNumber = 2; private string localAreaCode_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string LocalAreaCode { get { return localAreaCode_; } set { localAreaCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "local_first_minute_charge" field.</summary> public const int LocalFirstMinuteChargeFieldNumber = 3; private global::HOLMS.Types.Primitive.MonetaryAmount localFirstMinuteCharge_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount LocalFirstMinuteCharge { get { return localFirstMinuteCharge_; } set { localFirstMinuteCharge_ = value; } } /// <summary>Field number for the "local_additional_minute_charge" field.</summary> public const int LocalAdditionalMinuteChargeFieldNumber = 4; private global::HOLMS.Types.Primitive.MonetaryAmount localAdditionalMinuteCharge_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount LocalAdditionalMinuteCharge { get { return localAdditionalMinuteCharge_; } set { localAdditionalMinuteCharge_ = value; } } /// <summary>Field number for the "long_distance_first_minute_charge" field.</summary> public const int LongDistanceFirstMinuteChargeFieldNumber = 5; private global::HOLMS.Types.Primitive.MonetaryAmount longDistanceFirstMinuteCharge_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount LongDistanceFirstMinuteCharge { get { return longDistanceFirstMinuteCharge_; } set { longDistanceFirstMinuteCharge_ = value; } } /// <summary>Field number for the "long_distance_additional_minute_charge" field.</summary> public const int LongDistanceAdditionalMinuteChargeFieldNumber = 6; private global::HOLMS.Types.Primitive.MonetaryAmount longDistanceAdditionalMinuteCharge_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount LongDistanceAdditionalMinuteCharge { get { return longDistanceAdditionalMinuteCharge_; } set { longDistanceAdditionalMinuteCharge_ = value; } } /// <summary>Field number for the "international_first_minute_charge" field.</summary> public const int InternationalFirstMinuteChargeFieldNumber = 7; private global::HOLMS.Types.Primitive.MonetaryAmount internationalFirstMinuteCharge_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount InternationalFirstMinuteCharge { get { return internationalFirstMinuteCharge_; } set { internationalFirstMinuteCharge_ = value; } } /// <summary>Field number for the "international_additional_minute_charge" field.</summary> public const int InternationalAdditionalMinuteChargeFieldNumber = 8; private global::HOLMS.Types.Primitive.MonetaryAmount internationalAdditionalMinuteCharge_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount InternationalAdditionalMinuteCharge { get { return internationalAdditionalMinuteCharge_; } set { internationalAdditionalMinuteCharge_ = value; } } /// <summary>Field number for the "toll_free_flat_rate" field.</summary> public const int TollFreeFlatRateFieldNumber = 9; private global::HOLMS.Types.Primitive.MonetaryAmount tollFreeFlatRate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount TollFreeFlatRate { get { return tollFreeFlatRate_; } set { tollFreeFlatRate_ = value; } } /// <summary>Field number for the "directory_assistance_flat_rate" field.</summary> public const int DirectoryAssistanceFlatRateFieldNumber = 10; private global::HOLMS.Types.Primitive.MonetaryAmount directoryAssistanceFlatRate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount DirectoryAssistanceFlatRate { get { return directoryAssistanceFlatRate_; } set { directoryAssistanceFlatRate_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RoomCallBillingRates); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RoomCallBillingRates other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(FreeCallGracePeriod, other.FreeCallGracePeriod)) return false; if (LocalAreaCode != other.LocalAreaCode) return false; if (!object.Equals(LocalFirstMinuteCharge, other.LocalFirstMinuteCharge)) return false; if (!object.Equals(LocalAdditionalMinuteCharge, other.LocalAdditionalMinuteCharge)) return false; if (!object.Equals(LongDistanceFirstMinuteCharge, other.LongDistanceFirstMinuteCharge)) return false; if (!object.Equals(LongDistanceAdditionalMinuteCharge, other.LongDistanceAdditionalMinuteCharge)) return false; if (!object.Equals(InternationalFirstMinuteCharge, other.InternationalFirstMinuteCharge)) return false; if (!object.Equals(InternationalAdditionalMinuteCharge, other.InternationalAdditionalMinuteCharge)) return false; if (!object.Equals(TollFreeFlatRate, other.TollFreeFlatRate)) return false; if (!object.Equals(DirectoryAssistanceFlatRate, other.DirectoryAssistanceFlatRate)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (freeCallGracePeriod_ != null) hash ^= FreeCallGracePeriod.GetHashCode(); if (LocalAreaCode.Length != 0) hash ^= LocalAreaCode.GetHashCode(); if (localFirstMinuteCharge_ != null) hash ^= LocalFirstMinuteCharge.GetHashCode(); if (localAdditionalMinuteCharge_ != null) hash ^= LocalAdditionalMinuteCharge.GetHashCode(); if (longDistanceFirstMinuteCharge_ != null) hash ^= LongDistanceFirstMinuteCharge.GetHashCode(); if (longDistanceAdditionalMinuteCharge_ != null) hash ^= LongDistanceAdditionalMinuteCharge.GetHashCode(); if (internationalFirstMinuteCharge_ != null) hash ^= InternationalFirstMinuteCharge.GetHashCode(); if (internationalAdditionalMinuteCharge_ != null) hash ^= InternationalAdditionalMinuteCharge.GetHashCode(); if (tollFreeFlatRate_ != null) hash ^= TollFreeFlatRate.GetHashCode(); if (directoryAssistanceFlatRate_ != null) hash ^= DirectoryAssistanceFlatRate.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (freeCallGracePeriod_ != null) { output.WriteRawTag(10); output.WriteMessage(FreeCallGracePeriod); } if (LocalAreaCode.Length != 0) { output.WriteRawTag(18); output.WriteString(LocalAreaCode); } if (localFirstMinuteCharge_ != null) { output.WriteRawTag(26); output.WriteMessage(LocalFirstMinuteCharge); } if (localAdditionalMinuteCharge_ != null) { output.WriteRawTag(34); output.WriteMessage(LocalAdditionalMinuteCharge); } if (longDistanceFirstMinuteCharge_ != null) { output.WriteRawTag(42); output.WriteMessage(LongDistanceFirstMinuteCharge); } if (longDistanceAdditionalMinuteCharge_ != null) { output.WriteRawTag(50); output.WriteMessage(LongDistanceAdditionalMinuteCharge); } if (internationalFirstMinuteCharge_ != null) { output.WriteRawTag(58); output.WriteMessage(InternationalFirstMinuteCharge); } if (internationalAdditionalMinuteCharge_ != null) { output.WriteRawTag(66); output.WriteMessage(InternationalAdditionalMinuteCharge); } if (tollFreeFlatRate_ != null) { output.WriteRawTag(74); output.WriteMessage(TollFreeFlatRate); } if (directoryAssistanceFlatRate_ != null) { output.WriteRawTag(82); output.WriteMessage(DirectoryAssistanceFlatRate); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (freeCallGracePeriod_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(FreeCallGracePeriod); } if (LocalAreaCode.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(LocalAreaCode); } if (localFirstMinuteCharge_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(LocalFirstMinuteCharge); } if (localAdditionalMinuteCharge_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(LocalAdditionalMinuteCharge); } if (longDistanceFirstMinuteCharge_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(LongDistanceFirstMinuteCharge); } if (longDistanceAdditionalMinuteCharge_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(LongDistanceAdditionalMinuteCharge); } if (internationalFirstMinuteCharge_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(InternationalFirstMinuteCharge); } if (internationalAdditionalMinuteCharge_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(InternationalAdditionalMinuteCharge); } if (tollFreeFlatRate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(TollFreeFlatRate); } if (directoryAssistanceFlatRate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(DirectoryAssistanceFlatRate); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RoomCallBillingRates other) { if (other == null) { return; } if (other.freeCallGracePeriod_ != null) { if (freeCallGracePeriod_ == null) { freeCallGracePeriod_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } FreeCallGracePeriod.MergeFrom(other.FreeCallGracePeriod); } if (other.LocalAreaCode.Length != 0) { LocalAreaCode = other.LocalAreaCode; } if (other.localFirstMinuteCharge_ != null) { if (localFirstMinuteCharge_ == null) { localFirstMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } LocalFirstMinuteCharge.MergeFrom(other.LocalFirstMinuteCharge); } if (other.localAdditionalMinuteCharge_ != null) { if (localAdditionalMinuteCharge_ == null) { localAdditionalMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } LocalAdditionalMinuteCharge.MergeFrom(other.LocalAdditionalMinuteCharge); } if (other.longDistanceFirstMinuteCharge_ != null) { if (longDistanceFirstMinuteCharge_ == null) { longDistanceFirstMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } LongDistanceFirstMinuteCharge.MergeFrom(other.LongDistanceFirstMinuteCharge); } if (other.longDistanceAdditionalMinuteCharge_ != null) { if (longDistanceAdditionalMinuteCharge_ == null) { longDistanceAdditionalMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } LongDistanceAdditionalMinuteCharge.MergeFrom(other.LongDistanceAdditionalMinuteCharge); } if (other.internationalFirstMinuteCharge_ != null) { if (internationalFirstMinuteCharge_ == null) { internationalFirstMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } InternationalFirstMinuteCharge.MergeFrom(other.InternationalFirstMinuteCharge); } if (other.internationalAdditionalMinuteCharge_ != null) { if (internationalAdditionalMinuteCharge_ == null) { internationalAdditionalMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } InternationalAdditionalMinuteCharge.MergeFrom(other.InternationalAdditionalMinuteCharge); } if (other.tollFreeFlatRate_ != null) { if (tollFreeFlatRate_ == null) { tollFreeFlatRate_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } TollFreeFlatRate.MergeFrom(other.TollFreeFlatRate); } if (other.directoryAssistanceFlatRate_ != null) { if (directoryAssistanceFlatRate_ == null) { directoryAssistanceFlatRate_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } DirectoryAssistanceFlatRate.MergeFrom(other.DirectoryAssistanceFlatRate); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (freeCallGracePeriod_ == null) { freeCallGracePeriod_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(freeCallGracePeriod_); break; } case 18: { LocalAreaCode = input.ReadString(); break; } case 26: { if (localFirstMinuteCharge_ == null) { localFirstMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(localFirstMinuteCharge_); break; } case 34: { if (localAdditionalMinuteCharge_ == null) { localAdditionalMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(localAdditionalMinuteCharge_); break; } case 42: { if (longDistanceFirstMinuteCharge_ == null) { longDistanceFirstMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(longDistanceFirstMinuteCharge_); break; } case 50: { if (longDistanceAdditionalMinuteCharge_ == null) { longDistanceAdditionalMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(longDistanceAdditionalMinuteCharge_); break; } case 58: { if (internationalFirstMinuteCharge_ == null) { internationalFirstMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(internationalFirstMinuteCharge_); break; } case 66: { if (internationalAdditionalMinuteCharge_ == null) { internationalAdditionalMinuteCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(internationalAdditionalMinuteCharge_); break; } case 74: { if (tollFreeFlatRate_ == null) { tollFreeFlatRate_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(tollFreeFlatRate_); break; } case 82: { if (directoryAssistanceFlatRate_ == null) { directoryAssistanceFlatRate_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(directoryAssistanceFlatRate_); break; } } } } } #endregion } #endregion Designer generated code
namespace java.nio.charset { [global::MonoJavaBridge.JavaClass(typeof(global::java.nio.charset.Charset_))] public abstract partial class Charset : java.lang.Object, java.lang.Comparable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Charset() { InitJNI(); } protected Charset(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _name14672; public virtual global::java.lang.String name() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.charset.Charset._name14672)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._name14672)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _forName14673; public static global::java.nio.charset.Charset forName(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._forName14673, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.charset.Charset; } internal static global::MonoJavaBridge.MethodId _equals14674; public sealed override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.charset.Charset._equals14674, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._equals14674, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString14675; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.charset.Charset._toString14675)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._toString14675)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode14676; public sealed override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.charset.Charset._hashCode14676); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._hashCode14676); } internal static global::MonoJavaBridge.MethodId _compareTo14677; public virtual int compareTo(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.charset.Charset._compareTo14677, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._compareTo14677, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _compareTo14678; public virtual int compareTo(java.nio.charset.Charset arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.charset.Charset._compareTo14678, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._compareTo14678, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _contains14679; public abstract bool contains(java.nio.charset.Charset arg0); internal static global::MonoJavaBridge.MethodId _decode14680; public virtual global::java.nio.CharBuffer decode(java.nio.ByteBuffer arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.charset.Charset._decode14680, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.CharBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._decode14680, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.CharBuffer; } internal static global::MonoJavaBridge.MethodId _encode14681; public virtual global::java.nio.ByteBuffer encode(java.nio.CharBuffer arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.charset.Charset._encode14681, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._encode14681, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _encode14682; public virtual global::java.nio.ByteBuffer encode(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.charset.Charset._encode14682, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._encode14682, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _isSupported14683; public static bool isSupported(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticBooleanMethod(java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._isSupported14683, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _defaultCharset14684; public static global::java.nio.charset.Charset defaultCharset() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._defaultCharset14684)) as java.nio.charset.Charset; } internal static global::MonoJavaBridge.MethodId _aliases14685; public virtual global::java.util.Set aliases() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.charset.Charset._aliases14685)) as java.util.Set; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._aliases14685)) as java.util.Set; } internal static global::MonoJavaBridge.MethodId _availableCharsets14686; public static global::java.util.SortedMap availableCharsets() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.SortedMap>(@__env.CallStaticObjectMethod(java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._availableCharsets14686)) as java.util.SortedMap; } internal static global::MonoJavaBridge.MethodId _displayName14687; public virtual global::java.lang.String displayName() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.charset.Charset._displayName14687)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._displayName14687)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _displayName14688; public virtual global::java.lang.String displayName(java.util.Locale arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.charset.Charset._displayName14688, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._displayName14688, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _isRegistered14689; public virtual bool isRegistered() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.charset.Charset._isRegistered14689); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._isRegistered14689); } internal static global::MonoJavaBridge.MethodId _newDecoder14690; public abstract global::java.nio.charset.CharsetDecoder newDecoder(); internal static global::MonoJavaBridge.MethodId _newEncoder14691; public abstract global::java.nio.charset.CharsetEncoder newEncoder(); internal static global::MonoJavaBridge.MethodId _canEncode14692; public virtual bool canEncode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.charset.Charset._canEncode14692); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._canEncode14692); } internal static global::MonoJavaBridge.MethodId _Charset14693; protected Charset(java.lang.String arg0, java.lang.String[] arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.nio.charset.Charset.staticClass, global::java.nio.charset.Charset._Charset14693, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.nio.charset.Charset.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/charset/Charset")); global::java.nio.charset.Charset._name14672 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "name", "()Ljava/lang/String;"); global::java.nio.charset.Charset._forName14673 = @__env.GetStaticMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "forName", "(Ljava/lang/String;)Ljava/nio/charset/Charset;"); global::java.nio.charset.Charset._equals14674 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::java.nio.charset.Charset._toString14675 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "toString", "()Ljava/lang/String;"); global::java.nio.charset.Charset._hashCode14676 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "hashCode", "()I"); global::java.nio.charset.Charset._compareTo14677 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "compareTo", "(Ljava/lang/Object;)I"); global::java.nio.charset.Charset._compareTo14678 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "compareTo", "(Ljava/nio/charset/Charset;)I"); global::java.nio.charset.Charset._contains14679 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "contains", "(Ljava/nio/charset/Charset;)Z"); global::java.nio.charset.Charset._decode14680 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "decode", "(Ljava/nio/ByteBuffer;)Ljava/nio/CharBuffer;"); global::java.nio.charset.Charset._encode14681 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "encode", "(Ljava/nio/CharBuffer;)Ljava/nio/ByteBuffer;"); global::java.nio.charset.Charset._encode14682 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "encode", "(Ljava/lang/String;)Ljava/nio/ByteBuffer;"); global::java.nio.charset.Charset._isSupported14683 = @__env.GetStaticMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "isSupported", "(Ljava/lang/String;)Z"); global::java.nio.charset.Charset._defaultCharset14684 = @__env.GetStaticMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "defaultCharset", "()Ljava/nio/charset/Charset;"); global::java.nio.charset.Charset._aliases14685 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "aliases", "()Ljava/util/Set;"); global::java.nio.charset.Charset._availableCharsets14686 = @__env.GetStaticMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "availableCharsets", "()Ljava/util/SortedMap;"); global::java.nio.charset.Charset._displayName14687 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "displayName", "()Ljava/lang/String;"); global::java.nio.charset.Charset._displayName14688 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "displayName", "(Ljava/util/Locale;)Ljava/lang/String;"); global::java.nio.charset.Charset._isRegistered14689 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "isRegistered", "()Z"); global::java.nio.charset.Charset._newDecoder14690 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "newDecoder", "()Ljava/nio/charset/CharsetDecoder;"); global::java.nio.charset.Charset._newEncoder14691 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "newEncoder", "()Ljava/nio/charset/CharsetEncoder;"); global::java.nio.charset.Charset._canEncode14692 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "canEncode", "()Z"); global::java.nio.charset.Charset._Charset14693 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset.staticClass, "<init>", "(Ljava/lang/String;[Ljava/lang/String;)V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.nio.charset.Charset))] public sealed partial class Charset_ : java.nio.charset.Charset { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Charset_() { InitJNI(); } internal Charset_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _contains14694; public override bool contains(java.nio.charset.Charset arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.charset.Charset_._contains14694, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.charset.Charset_.staticClass, global::java.nio.charset.Charset_._contains14694, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _newDecoder14695; public override global::java.nio.charset.CharsetDecoder newDecoder() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.charset.Charset_._newDecoder14695)) as java.nio.charset.CharsetDecoder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.charset.Charset_.staticClass, global::java.nio.charset.Charset_._newDecoder14695)) as java.nio.charset.CharsetDecoder; } internal static global::MonoJavaBridge.MethodId _newEncoder14696; public override global::java.nio.charset.CharsetEncoder newEncoder() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.charset.Charset_._newEncoder14696)) as java.nio.charset.CharsetEncoder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.charset.Charset_.staticClass, global::java.nio.charset.Charset_._newEncoder14696)) as java.nio.charset.CharsetEncoder; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.nio.charset.Charset_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/charset/Charset")); global::java.nio.charset.Charset_._contains14694 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset_.staticClass, "contains", "(Ljava/nio/charset/Charset;)Z"); global::java.nio.charset.Charset_._newDecoder14695 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset_.staticClass, "newDecoder", "()Ljava/nio/charset/CharsetDecoder;"); global::java.nio.charset.Charset_._newEncoder14696 = @__env.GetMethodIDNoThrow(global::java.nio.charset.Charset_.staticClass, "newEncoder", "()Ljava/nio/charset/CharsetEncoder;"); } } }
//------------------------------------------------------------------------------ // <copyright file="KnownColorTable.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Drawing { using System.Runtime.InteropServices; using System.Diagnostics; using System; using Microsoft.Win32; #if !FEATURE_PAL using System.Drawing.Internal; #endif static internal class KnownColorTable { private static int[] colorTable; private static string[] colorNameTable; /** * Shift count and bit mask for A, R, G, B components */ private const int AlphaShift = 24; private const int RedShift = 16; private const int GreenShift = 8; private const int BlueShift = 0; private const int Win32RedShift = 0; private const int Win32GreenShift = 8; private const int Win32BlueShift = 16; public static Color ArgbToKnownColor(int targetARGB) { EnsureColorTable(); for(int index = 0; index < colorTable.Length; ++index) { int argb = colorTable[index]; if (argb == targetARGB) { Color color = Color.FromKnownColor((KnownColor)index); if (!color.IsSystemColor) return color; } } return Color.FromArgb(targetARGB); } private static void EnsureColorTable() { // no need to lock... worse case is a double create of the table... // if (colorTable == null) { InitColorTable(); } } private static void InitColorTable() { int[] values = new int[(unchecked((int)KnownColor.MenuHighlight)) + 1]; // system // #if !FEATURE_PAL SystemEvents.UserPreferenceChanging += new UserPreferenceChangingEventHandler(OnUserPreferenceChanging); #endif UpdateSystemColors(values); // just consts... // values[(int)KnownColor.Transparent] = 0x00FFFFFF; values[(int)KnownColor.AliceBlue] = unchecked((int)0xFFF0F8FF); values[(int)KnownColor.AntiqueWhite] = unchecked((int)0xFFFAEBD7); values[(int)KnownColor.Aqua] = unchecked((int)0xFF00FFFF); values[(int)KnownColor.Aquamarine] = unchecked((int)0xFF7FFFD4); values[(int)KnownColor.Azure] = unchecked((int)0xFFF0FFFF); values[(int)KnownColor.Beige] = unchecked((int)0xFFF5F5DC); values[(int)KnownColor.Bisque] = unchecked(unchecked((int)0xFFFFE4C4)); values[(int)KnownColor.Black] = unchecked((int)0xFF000000); values[(int)KnownColor.BlanchedAlmond] = unchecked((int)0xFFFFEBCD); values[(int)KnownColor.Blue] = unchecked((int)0xFF0000FF); values[(int)KnownColor.BlueViolet] = unchecked((int)0xFF8A2BE2); values[(int)KnownColor.Brown] = unchecked((int)0xFFA52A2A); values[(int)KnownColor.BurlyWood] = unchecked((int)0xFFDEB887); values[(int)KnownColor.CadetBlue] = unchecked((int)0xFF5F9EA0); values[(int)KnownColor.Chartreuse] = unchecked((int)0xFF7FFF00); values[(int)KnownColor.Chocolate] = unchecked((int)0xFFD2691E); values[(int)KnownColor.Coral] = unchecked((int)0xFFFF7F50); values[(int)KnownColor.CornflowerBlue] = unchecked((int)0xFF6495ED); values[(int)KnownColor.Cornsilk] = unchecked((int)0xFFFFF8DC); values[(int)KnownColor.Crimson] = unchecked((int)0xFFDC143C); values[(int)KnownColor.Cyan] = unchecked((int)0xFF00FFFF); values[(int)KnownColor.DarkBlue] = unchecked((int)0xFF00008B); values[(int)KnownColor.DarkCyan] = unchecked((int)0xFF008B8B); values[(int)KnownColor.DarkGoldenrod] = unchecked((int)0xFFB8860B); values[(int)KnownColor.DarkGray] = unchecked((int)0xFFA9A9A9); values[(int)KnownColor.DarkGreen] = unchecked((int)0xFF006400); values[(int)KnownColor.DarkKhaki] = unchecked((int)0xFFBDB76B); values[(int)KnownColor.DarkMagenta] = unchecked((int)0xFF8B008B); values[(int)KnownColor.DarkOliveGreen] = unchecked((int)0xFF556B2F); values[(int)KnownColor.DarkOrange] = unchecked((int)0xFFFF8C00); values[(int)KnownColor.DarkOrchid] = unchecked((int)0xFF9932CC); values[(int)KnownColor.DarkRed] = unchecked((int)0xFF8B0000); values[(int)KnownColor.DarkSalmon] = unchecked((int)0xFFE9967A); values[(int)KnownColor.DarkSeaGreen] = unchecked((int)0xFF8FBC8B); values[(int)KnownColor.DarkSlateBlue] = unchecked((int)0xFF483D8B); values[(int)KnownColor.DarkSlateGray] = unchecked((int)0xFF2F4F4F); values[(int)KnownColor.DarkTurquoise] = unchecked((int)0xFF00CED1); values[(int)KnownColor.DarkViolet] = unchecked((int)0xFF9400D3); values[(int)KnownColor.DeepPink] = unchecked((int)0xFFFF1493); values[(int)KnownColor.DeepSkyBlue] = unchecked((int)0xFF00BFFF); values[(int)KnownColor.DimGray] = unchecked((int)0xFF696969); values[(int)KnownColor.DodgerBlue] = unchecked((int)0xFF1E90FF); values[(int)KnownColor.Firebrick] = unchecked((int)0xFFB22222); values[(int)KnownColor.FloralWhite] = unchecked((int)0xFFFFFAF0); values[(int)KnownColor.ForestGreen] = unchecked((int)0xFF228B22); values[(int)KnownColor.Fuchsia] = unchecked((int)0xFFFF00FF); values[(int)KnownColor.Gainsboro] = unchecked((int)0xFFDCDCDC); values[(int)KnownColor.GhostWhite] = unchecked((int)0xFFF8F8FF); values[(int)KnownColor.Gold] = unchecked((int)0xFFFFD700); values[(int)KnownColor.Goldenrod] = unchecked((int)0xFFDAA520); values[(int)KnownColor.Gray] = unchecked((int)0xFF808080); values[(int)KnownColor.Green] = unchecked((int)0xFF008000); values[(int)KnownColor.GreenYellow] = unchecked((int)0xFFADFF2F); values[(int)KnownColor.Honeydew] = unchecked((int)0xFFF0FFF0); values[(int)KnownColor.HotPink] = unchecked((int)0xFFFF69B4); values[(int)KnownColor.IndianRed] = unchecked((int)0xFFCD5C5C); values[(int)KnownColor.Indigo] = unchecked((int)0xFF4B0082); values[(int)KnownColor.Ivory] = unchecked((int)0xFFFFFFF0); values[(int)KnownColor.Khaki] = unchecked((int)0xFFF0E68C); values[(int)KnownColor.Lavender] = unchecked((int)0xFFE6E6FA); values[(int)KnownColor.LavenderBlush] = unchecked((int)0xFFFFF0F5); values[(int)KnownColor.LawnGreen] = unchecked((int)0xFF7CFC00); values[(int)KnownColor.LemonChiffon] = unchecked((int)0xFFFFFACD); values[(int)KnownColor.LightBlue] = unchecked((int)0xFFADD8E6); values[(int)KnownColor.LightCoral] = unchecked((int)0xFFF08080); values[(int)KnownColor.LightCyan] = unchecked((int)0xFFE0FFFF); values[(int)KnownColor.LightGoldenrodYellow] = unchecked((int)0xFFFAFAD2); values[(int)KnownColor.LightGray] = unchecked((int)0xFFD3D3D3); values[(int)KnownColor.LightGreen] = unchecked((int)0xFF90EE90); values[(int)KnownColor.LightPink] = unchecked((int)0xFFFFB6C1); values[(int)KnownColor.LightSalmon] = unchecked((int)0xFFFFA07A); values[(int)KnownColor.LightSeaGreen] = unchecked((int)0xFF20B2AA); values[(int)KnownColor.LightSkyBlue] = unchecked((int)0xFF87CEFA); values[(int)KnownColor.LightSlateGray] = unchecked((int)0xFF778899); values[(int)KnownColor.LightSteelBlue] = unchecked((int)0xFFB0C4DE); values[(int)KnownColor.LightYellow] = unchecked((int)0xFFFFFFE0); values[(int)KnownColor.Lime] = unchecked((int)0xFF00FF00); values[(int)KnownColor.LimeGreen] = unchecked((int)0xFF32CD32); values[(int)KnownColor.Linen] = unchecked((int)0xFFFAF0E6); values[(int)KnownColor.Magenta] = unchecked((int)0xFFFF00FF); values[(int)KnownColor.Maroon] = unchecked((int)0xFF800000); values[(int)KnownColor.MediumAquamarine] = unchecked((int)0xFF66CDAA); values[(int)KnownColor.MediumBlue] = unchecked((int)0xFF0000CD); values[(int)KnownColor.MediumOrchid] = unchecked((int)0xFFBA55D3); values[(int)KnownColor.MediumPurple] = unchecked((int)0xFF9370DB); values[(int)KnownColor.MediumSeaGreen] = unchecked((int)0xFF3CB371); values[(int)KnownColor.MediumSlateBlue] = unchecked((int)0xFF7B68EE); values[(int)KnownColor.MediumSpringGreen] = unchecked((int)0xFF00FA9A); values[(int)KnownColor.MediumTurquoise] = unchecked((int)0xFF48D1CC); values[(int)KnownColor.MediumVioletRed] = unchecked((int)0xFFC71585); values[(int)KnownColor.MidnightBlue] = unchecked((int)0xFF191970); values[(int)KnownColor.MintCream] = unchecked((int)0xFFF5FFFA); values[(int)KnownColor.MistyRose] = unchecked((int)0xFFFFE4E1); values[(int)KnownColor.Moccasin] = unchecked((int)0xFFFFE4B5); values[(int)KnownColor.NavajoWhite] = unchecked((int)0xFFFFDEAD); values[(int)KnownColor.Navy] = unchecked((int)0xFF000080); values[(int)KnownColor.OldLace] = unchecked((int)0xFFFDF5E6); values[(int)KnownColor.Olive] = unchecked((int)0xFF808000); values[(int)KnownColor.OliveDrab] = unchecked((int)0xFF6B8E23); values[(int)KnownColor.Orange] = unchecked((int)0xFFFFA500); values[(int)KnownColor.OrangeRed] = unchecked((int)0xFFFF4500); values[(int)KnownColor.Orchid] = unchecked((int)0xFFDA70D6); values[(int)KnownColor.PaleGoldenrod] = unchecked((int)0xFFEEE8AA); values[(int)KnownColor.PaleGreen] = unchecked((int)0xFF98FB98); values[(int)KnownColor.PaleTurquoise] = unchecked((int)0xFFAFEEEE); values[(int)KnownColor.PaleVioletRed] = unchecked((int)0xFFDB7093); values[(int)KnownColor.PapayaWhip] = unchecked((int)0xFFFFEFD5); values[(int)KnownColor.PeachPuff] = unchecked((int)0xFFFFDAB9); values[(int)KnownColor.Peru] = unchecked((int)0xFFCD853F); values[(int)KnownColor.Pink] = unchecked((int)0xFFFFC0CB); values[(int)KnownColor.Plum] = unchecked((int)0xFFDDA0DD); values[(int)KnownColor.PowderBlue] = unchecked((int)0xFFB0E0E6); values[(int)KnownColor.Purple] = unchecked((int)0xFF800080); values[(int)KnownColor.Red] = unchecked((int)0xFFFF0000); values[(int)KnownColor.RosyBrown] = unchecked((int)0xFFBC8F8F); values[(int)KnownColor.RoyalBlue] = unchecked((int)0xFF4169E1); values[(int)KnownColor.SaddleBrown] = unchecked((int)0xFF8B4513); values[(int)KnownColor.Salmon] = unchecked((int)0xFFFA8072); values[(int)KnownColor.SandyBrown] = unchecked((int)0xFFF4A460); values[(int)KnownColor.SeaGreen] = unchecked((int)0xFF2E8B57); values[(int)KnownColor.SeaShell] = unchecked((int)0xFFFFF5EE); values[(int)KnownColor.Sienna] = unchecked((int)0xFFA0522D); values[(int)KnownColor.Silver] = unchecked((int)0xFFC0C0C0); values[(int)KnownColor.SkyBlue] = unchecked((int)0xFF87CEEB); values[(int)KnownColor.SlateBlue] = unchecked((int)0xFF6A5ACD); values[(int)KnownColor.SlateGray] = unchecked((int)0xFF708090); values[(int)KnownColor.Snow] = unchecked((int)0xFFFFFAFA); values[(int)KnownColor.SpringGreen] = unchecked((int)0xFF00FF7F); values[(int)KnownColor.SteelBlue] = unchecked((int)0xFF4682B4); values[(int)KnownColor.Tan] = unchecked((int)0xFFD2B48C); values[(int)KnownColor.Teal] = unchecked((int)0xFF008080); values[(int)KnownColor.Thistle] = unchecked((int)0xFFD8BFD8); values[(int)KnownColor.Tomato] = unchecked((int)0xFFFF6347); values[(int)KnownColor.Turquoise] = unchecked((int)0xFF40E0D0); values[(int)KnownColor.Violet] = unchecked((int)0xFFEE82EE); values[(int)KnownColor.Wheat] = unchecked((int)0xFFF5DEB3); values[(int)KnownColor.White] = unchecked((int)0xFFFFFFFF); values[(int)KnownColor.WhiteSmoke] = unchecked((int)0xFFF5F5F5); values[(int)KnownColor.Yellow] = unchecked((int)0xFFFFFF00); values[(int)KnownColor.YellowGreen] = unchecked((int)0xFF9ACD32); colorTable = values; } private static void EnsureColorNameTable() { // no need to lock... worse case is a double create of the table... // if (colorNameTable == null) { InitColorNameTable(); } } private static void InitColorNameTable() { string[] values = new string[((int)KnownColor.MenuHighlight) + 1]; // just consts... // values[(int)KnownColor.ActiveBorder] = "ActiveBorder"; values[(int)KnownColor.ActiveCaption] = "ActiveCaption"; values[(int)KnownColor.ActiveCaptionText] = "ActiveCaptionText"; values[(int)KnownColor.AppWorkspace] = "AppWorkspace"; values[(int)KnownColor.ButtonFace] = "ButtonFace"; values[(int)KnownColor.ButtonHighlight] = "ButtonHighlight"; values[(int)KnownColor.ButtonShadow] = "ButtonShadow"; values[(int)KnownColor.Control] = "Control"; values[(int)KnownColor.ControlDark] = "ControlDark"; values[(int)KnownColor.ControlDarkDark] = "ControlDarkDark"; values[(int)KnownColor.ControlLight] = "ControlLight"; values[(int)KnownColor.ControlLightLight] = "ControlLightLight"; values[(int)KnownColor.ControlText] = "ControlText"; values[(int)KnownColor.Desktop] = "Desktop"; values[(int)KnownColor.GradientActiveCaption] = "GradientActiveCaption"; values[(int)KnownColor.GradientInactiveCaption] = "GradientInactiveCaption"; values[(int)KnownColor.GrayText] = "GrayText"; values[(int)KnownColor.Highlight] = "Highlight"; values[(int)KnownColor.HighlightText] = "HighlightText"; values[(int)KnownColor.HotTrack] = "HotTrack"; values[(int)KnownColor.InactiveBorder] = "InactiveBorder"; values[(int)KnownColor.InactiveCaption] = "InactiveCaption"; values[(int)KnownColor.InactiveCaptionText] = "InactiveCaptionText"; values[(int)KnownColor.Info] = "Info"; values[(int)KnownColor.InfoText] = "InfoText"; values[(int)KnownColor.Menu] = "Menu"; values[(int)KnownColor.MenuBar] = "MenuBar"; values[(int)KnownColor.MenuHighlight] = "MenuHighlight"; values[(int)KnownColor.MenuText] = "MenuText"; values[(int)KnownColor.ScrollBar] = "ScrollBar"; values[(int)KnownColor.Window] = "Window"; values[(int)KnownColor.WindowFrame] = "WindowFrame"; values[(int)KnownColor.WindowText] = "WindowText"; values[(int)KnownColor.Transparent] = "Transparent"; values[(int)KnownColor.AliceBlue] = "AliceBlue"; values[(int)KnownColor.AntiqueWhite] = "AntiqueWhite"; values[(int)KnownColor.Aqua] = "Aqua"; values[(int)KnownColor.Aquamarine] = "Aquamarine"; values[(int)KnownColor.Azure] = "Azure"; values[(int)KnownColor.Beige] = "Beige"; values[(int)KnownColor.Bisque] = "Bisque"; values[(int)KnownColor.Black] = "Black"; values[(int)KnownColor.BlanchedAlmond] = "BlanchedAlmond"; values[(int)KnownColor.Blue] = "Blue"; values[(int)KnownColor.BlueViolet] = "BlueViolet"; values[(int)KnownColor.Brown] = "Brown"; values[(int)KnownColor.BurlyWood] = "BurlyWood"; values[(int)KnownColor.CadetBlue] = "CadetBlue"; values[(int)KnownColor.Chartreuse] = "Chartreuse"; values[(int)KnownColor.Chocolate] = "Chocolate"; values[(int)KnownColor.Coral] = "Coral"; values[(int)KnownColor.CornflowerBlue] = "CornflowerBlue"; values[(int)KnownColor.Cornsilk] = "Cornsilk"; values[(int)KnownColor.Crimson] = "Crimson"; values[(int)KnownColor.Cyan] = "Cyan"; values[(int)KnownColor.DarkBlue] = "DarkBlue"; values[(int)KnownColor.DarkCyan] = "DarkCyan"; values[(int)KnownColor.DarkGoldenrod] = "DarkGoldenrod"; values[(int)KnownColor.DarkGray] = "DarkGray"; values[(int)KnownColor.DarkGreen] = "DarkGreen"; values[(int)KnownColor.DarkKhaki] = "DarkKhaki"; values[(int)KnownColor.DarkMagenta] = "DarkMagenta"; values[(int)KnownColor.DarkOliveGreen] = "DarkOliveGreen"; values[(int)KnownColor.DarkOrange] = "DarkOrange"; values[(int)KnownColor.DarkOrchid] = "DarkOrchid"; values[(int)KnownColor.DarkRed] = "DarkRed"; values[(int)KnownColor.DarkSalmon] = "DarkSalmon"; values[(int)KnownColor.DarkSeaGreen] = "DarkSeaGreen"; values[(int)KnownColor.DarkSlateBlue] = "DarkSlateBlue"; values[(int)KnownColor.DarkSlateGray] = "DarkSlateGray"; values[(int)KnownColor.DarkTurquoise] = "DarkTurquoise"; values[(int)KnownColor.DarkViolet] = "DarkViolet"; values[(int)KnownColor.DeepPink] = "DeepPink"; values[(int)KnownColor.DeepSkyBlue] = "DeepSkyBlue"; values[(int)KnownColor.DimGray] = "DimGray"; values[(int)KnownColor.DodgerBlue] = "DodgerBlue"; values[(int)KnownColor.Firebrick] = "Firebrick"; values[(int)KnownColor.FloralWhite] = "FloralWhite"; values[(int)KnownColor.ForestGreen] = "ForestGreen"; values[(int)KnownColor.Fuchsia] = "Fuchsia"; values[(int)KnownColor.Gainsboro] = "Gainsboro"; values[(int)KnownColor.GhostWhite] = "GhostWhite"; values[(int)KnownColor.Gold] = "Gold"; values[(int)KnownColor.Goldenrod] = "Goldenrod"; values[(int)KnownColor.Gray] = "Gray"; values[(int)KnownColor.Green] = "Green"; values[(int)KnownColor.GreenYellow] = "GreenYellow"; values[(int)KnownColor.Honeydew] = "Honeydew"; values[(int)KnownColor.HotPink] = "HotPink"; values[(int)KnownColor.IndianRed] = "IndianRed"; values[(int)KnownColor.Indigo] = "Indigo"; values[(int)KnownColor.Ivory] = "Ivory"; values[(int)KnownColor.Khaki] = "Khaki"; values[(int)KnownColor.Lavender] = "Lavender"; values[(int)KnownColor.LavenderBlush] = "LavenderBlush"; values[(int)KnownColor.LawnGreen] = "LawnGreen"; values[(int)KnownColor.LemonChiffon] = "LemonChiffon"; values[(int)KnownColor.LightBlue] = "LightBlue"; values[(int)KnownColor.LightCoral] = "LightCoral"; values[(int)KnownColor.LightCyan] = "LightCyan"; values[(int)KnownColor.LightGoldenrodYellow] = "LightGoldenrodYellow"; values[(int)KnownColor.LightGray] = "LightGray"; values[(int)KnownColor.LightGreen] = "LightGreen"; values[(int)KnownColor.LightPink] = "LightPink"; values[(int)KnownColor.LightSalmon] = "LightSalmon"; values[(int)KnownColor.LightSeaGreen] = "LightSeaGreen"; values[(int)KnownColor.LightSkyBlue] = "LightSkyBlue"; values[(int)KnownColor.LightSlateGray] = "LightSlateGray"; values[(int)KnownColor.LightSteelBlue] = "LightSteelBlue"; values[(int)KnownColor.LightYellow] = "LightYellow"; values[(int)KnownColor.Lime] = "Lime"; values[(int)KnownColor.LimeGreen] = "LimeGreen"; values[(int)KnownColor.Linen] = "Linen"; values[(int)KnownColor.Magenta] = "Magenta"; values[(int)KnownColor.Maroon] = "Maroon"; values[(int)KnownColor.MediumAquamarine] = "MediumAquamarine"; values[(int)KnownColor.MediumBlue] = "MediumBlue"; values[(int)KnownColor.MediumOrchid] = "MediumOrchid"; values[(int)KnownColor.MediumPurple] = "MediumPurple"; values[(int)KnownColor.MediumSeaGreen] = "MediumSeaGreen"; values[(int)KnownColor.MediumSlateBlue] = "MediumSlateBlue"; values[(int)KnownColor.MediumSpringGreen] = "MediumSpringGreen"; values[(int)KnownColor.MediumTurquoise] = "MediumTurquoise"; values[(int)KnownColor.MediumVioletRed] = "MediumVioletRed"; values[(int)KnownColor.MidnightBlue] = "MidnightBlue"; values[(int)KnownColor.MintCream] = "MintCream"; values[(int)KnownColor.MistyRose] = "MistyRose"; values[(int)KnownColor.Moccasin] = "Moccasin"; values[(int)KnownColor.NavajoWhite] = "NavajoWhite"; values[(int)KnownColor.Navy] = "Navy"; values[(int)KnownColor.OldLace] = "OldLace"; values[(int)KnownColor.Olive] = "Olive"; values[(int)KnownColor.OliveDrab] = "OliveDrab"; values[(int)KnownColor.Orange] = "Orange"; values[(int)KnownColor.OrangeRed] = "OrangeRed"; values[(int)KnownColor.Orchid] = "Orchid"; values[(int)KnownColor.PaleGoldenrod] = "PaleGoldenrod"; values[(int)KnownColor.PaleGreen] = "PaleGreen"; values[(int)KnownColor.PaleTurquoise] = "PaleTurquoise"; values[(int)KnownColor.PaleVioletRed] = "PaleVioletRed"; values[(int)KnownColor.PapayaWhip] = "PapayaWhip"; values[(int)KnownColor.PeachPuff] = "PeachPuff"; values[(int)KnownColor.Peru] = "Peru"; values[(int)KnownColor.Pink] = "Pink"; values[(int)KnownColor.Plum] = "Plum"; values[(int)KnownColor.PowderBlue] = "PowderBlue"; values[(int)KnownColor.Purple] = "Purple"; values[(int)KnownColor.Red] = "Red"; values[(int)KnownColor.RosyBrown] = "RosyBrown"; values[(int)KnownColor.RoyalBlue] = "RoyalBlue"; values[(int)KnownColor.SaddleBrown] = "SaddleBrown"; values[(int)KnownColor.Salmon] = "Salmon"; values[(int)KnownColor.SandyBrown] = "SandyBrown"; values[(int)KnownColor.SeaGreen] = "SeaGreen"; values[(int)KnownColor.SeaShell] = "SeaShell"; values[(int)KnownColor.Sienna] = "Sienna"; values[(int)KnownColor.Silver] = "Silver"; values[(int)KnownColor.SkyBlue] = "SkyBlue"; values[(int)KnownColor.SlateBlue] = "SlateBlue"; values[(int)KnownColor.SlateGray] = "SlateGray"; values[(int)KnownColor.Snow] = "Snow"; values[(int)KnownColor.SpringGreen] = "SpringGreen"; values[(int)KnownColor.SteelBlue] = "SteelBlue"; values[(int)KnownColor.Tan] = "Tan"; values[(int)KnownColor.Teal] = "Teal"; values[(int)KnownColor.Thistle] = "Thistle"; values[(int)KnownColor.Tomato] = "Tomato"; values[(int)KnownColor.Turquoise] = "Turquoise"; values[(int)KnownColor.Violet] = "Violet"; values[(int)KnownColor.Wheat] = "Wheat"; values[(int)KnownColor.White] = "White"; values[(int)KnownColor.WhiteSmoke] = "WhiteSmoke"; values[(int)KnownColor.Yellow] = "Yellow"; values[(int)KnownColor.YellowGreen] = "YellowGreen"; colorNameTable = values; } public static int KnownColorToArgb(KnownColor color) { EnsureColorTable(); if (color <= KnownColor.MenuHighlight) { return colorTable[unchecked((int)color)]; } else { return 0; } } public static string KnownColorToName(KnownColor color) { EnsureColorNameTable(); if (color <= KnownColor.MenuHighlight) { return colorNameTable[unchecked((int)color)]; } else { return null; } } #if !FEATURE_PAL private static int SystemColorToArgb(int index) { return FromWin32Value(SafeNativeMethods.GetSysColor(index)); } private static int Encode(int alpha, int red, int green, int blue) { return red << RedShift | green << GreenShift | blue << BlueShift | alpha << AlphaShift; } private static int FromWin32Value(int value) { return Encode(255, (value >> Win32RedShift) & 0xFF, (value >> Win32GreenShift) & 0xFF, (value >> Win32BlueShift) & 0xFF); } private static void OnUserPreferenceChanging(object sender, UserPreferenceChangingEventArgs e) { if (e.Category == UserPreferenceCategory.Color && colorTable != null) { UpdateSystemColors(colorTable); } } #endif // !FEATURE_PAL private static void UpdateSystemColors(int[] colorTable) { #if !FEATURE_PAL colorTable[(int)KnownColor.ActiveBorder] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ActiveBorder); colorTable[(int)KnownColor.ActiveCaption] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ActiveCaption); colorTable[(int)KnownColor.ActiveCaptionText] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ActiveCaptionText); colorTable[(int)KnownColor.AppWorkspace] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.AppWorkspace); colorTable[(int)KnownColor.ButtonFace] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ButtonFace); colorTable[(int)KnownColor.ButtonHighlight] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ButtonHighlight); colorTable[(int)KnownColor.ButtonShadow] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ButtonShadow); colorTable[(int)KnownColor.Control] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.Control); colorTable[(int)KnownColor.ControlDark] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ControlDark); colorTable[(int)KnownColor.ControlDarkDark] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ControlDarkDark); colorTable[(int)KnownColor.ControlLight] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ControlLight); colorTable[(int)KnownColor.ControlLightLight] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ControlLightLight); colorTable[(int)KnownColor.ControlText] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ControlText); colorTable[(int)KnownColor.Desktop] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.Desktop); colorTable[(int)KnownColor.GradientActiveCaption] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.GradientActiveCaption); colorTable[(int)KnownColor.GradientInactiveCaption] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.GradientInactiveCaption); colorTable[(int)KnownColor.GrayText] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.GrayText); colorTable[(int)KnownColor.Highlight] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.Highlight); colorTable[(int)KnownColor.HighlightText] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.HighlightText); colorTable[(int)KnownColor.HotTrack] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.HotTrack); colorTable[(int)KnownColor.InactiveBorder] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.InactiveBorder); colorTable[(int)KnownColor.InactiveCaption] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.InactiveCaption); colorTable[(int)KnownColor.InactiveCaptionText] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.InactiveCaptionText); colorTable[(int)KnownColor.Info] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.Info); colorTable[(int)KnownColor.InfoText] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.InfoText); colorTable[(int)KnownColor.Menu] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.Menu); colorTable[(int)KnownColor.MenuBar] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.MenuBar); colorTable[(int)KnownColor.MenuHighlight] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.MenuHighlight); colorTable[(int)KnownColor.MenuText] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.MenuText); colorTable[(int)KnownColor.ScrollBar] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.ScrollBar); colorTable[(int)KnownColor.Window] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.Window); colorTable[(int)KnownColor.WindowFrame] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.WindowFrame); colorTable[(int)KnownColor.WindowText] = SystemColorToArgb((int)SafeNativeMethods.Win32SystemColors.WindowText); #else // Colors from a default XP desktop for use by UI designers in ASP.NET: <EMAIL>[....]</EMAIL> colorTable[(int)KnownColor.ActiveBorder] = unchecked((int)0xffd4d0c8); colorTable[(int)KnownColor.ActiveCaption] = unchecked((int)0xff0054e3); colorTable[(int)KnownColor.ActiveCaptionText] = unchecked((int)0xffffffff); colorTable[(int)KnownColor.AppWorkspace] = unchecked((int)0xff808080); colorTable[(int)KnownColor.ButtonFace] = unchecked((int)0x0); colorTable[(int)KnownColor.ButtonHighlight] = unchecked((int)0x0); colorTable[(int)KnownColor.ButtonShadow] = unchecked((int)0x0); colorTable[(int)KnownColor.Control] = unchecked((int)0xffece9d8); colorTable[(int)KnownColor.ControlDark] = unchecked((int)0xffaca899); colorTable[(int)KnownColor.ControlDarkDark] = unchecked((int)0xff716f64); colorTable[(int)KnownColor.ControlLight] = unchecked((int)0xfff1efe2); colorTable[(int)KnownColor.ControlLightLight] = unchecked((int)0xffffffff); colorTable[(int)KnownColor.ControlText] = unchecked((int)0xff000000); colorTable[(int)KnownColor.Desktop] = unchecked((int)0xff004e98); colorTable[(int)KnownColor.GradientActiveCaption] = unchecked((int)0x0); colorTable[(int)KnownColor.GradientInactiveCaption] = unchecked((int)0x0); colorTable[(int)KnownColor.GrayText] = unchecked((int)0xffaca899); colorTable[(int)KnownColor.Highlight] = unchecked((int)0xff316ac5); colorTable[(int)KnownColor.HighlightText] = unchecked((int)0xffffffff); colorTable[(int)KnownColor.HotTrack] = unchecked((int)0xff000080); colorTable[(int)KnownColor.InactiveBorder] = unchecked((int)0xffd4d0c8); colorTable[(int)KnownColor.InactiveCaption] = unchecked((int)0xff7a96df); colorTable[(int)KnownColor.InactiveCaptionText] = unchecked((int)0xffd8e4f8); colorTable[(int)KnownColor.Info] = unchecked((int)0xffffffe1); colorTable[(int)KnownColor.InfoText] = unchecked((int)0xff000000); colorTable[(int)KnownColor.Menu] = unchecked((int)0xffffffff); colorTable[(int)KnownColor.MenuBar] = unchecked((int)0x0); colorTable[(int)KnownColor.MenuHighlight] = unchecked((int)0x0); colorTable[(int)KnownColor.MenuText] = unchecked((int)0xff000000); colorTable[(int)KnownColor.ScrollBar] = unchecked((int)0xffd4d0c8); colorTable[(int)KnownColor.Window] = unchecked((int)0xffffffff); colorTable[(int)KnownColor.WindowFrame] = unchecked((int)0xff000000); colorTable[(int)KnownColor.WindowText] = unchecked((int)0xff000000); #endif // !FEATURE_PAL } } }
using System; using System.Globalization; using HtmlRenderer.Entities; using HtmlRenderer.Parse; namespace HtmlRenderer.Dom { /// <summary> /// Represents and gets info about a CSS Length /// </summary> /// <remarks> /// http://www.w3.org/TR/CSS21/syndata.html#length-units /// </remarks> internal sealed class CssLength { #region Fields private readonly float _number; private readonly bool _isRelative; private readonly CssUnit _unit; private readonly string _length; private readonly bool _isPercentage; private readonly bool _hasError; #endregion #region Ctor /// <summary> /// Creates a new CssLength from a length specified on a CSS style sheet or fragment /// </summary> /// <param name="length">Length as specified in the Style Sheet or style fragment</param> public CssLength(string length) { _length = length; _number = 0f; _unit = CssUnit.None; _isPercentage = false; //Return zero if no length specified, zero specified if (string.IsNullOrEmpty(length) || length == "0") return; //If percentage, use ParseNumber if (length.EndsWith("%")) { _number = CssValueParser.ParseNumber(length, 1); _isPercentage = true; return; } //If no units, has error if (length.Length < 3) { float.TryParse(length, out _number); _hasError = true; return; } //Get units of the length string u = length.Substring(length.Length - 2, 2); //Number of the length string number = length.Substring(0, length.Length - 2); //TODO: Units behave different in paper and in screen! switch (u) { case CssConstants.Em: _unit = CssUnit.Ems; _isRelative = true; break; case CssConstants.Ex: _unit = CssUnit.Ex; _isRelative = true; break; case CssConstants.Px: _unit = CssUnit.Pixels; _isRelative = true; break; case CssConstants.Mm: _unit = CssUnit.Milimeters; break; case CssConstants.Cm: _unit = CssUnit.Centimeters; break; case CssConstants.In: _unit = CssUnit.Inches; break; case CssConstants.Pt: _unit = CssUnit.Points; break; case CssConstants.Pc: _unit = CssUnit.Picas; break; default: _hasError = true; return; } if (!float.TryParse(number, System.Globalization.NumberStyles.Number, NumberFormatInfo.InvariantInfo, out _number)) { _hasError = true; } } #endregion #region Props /// <summary> /// Gets the number in the length /// </summary> public float Number { get { return _number; } } /// <summary> /// Gets if the length has some parsing error /// </summary> public bool HasError { get { return _hasError; } } /// <summary> /// Gets if the length represents a precentage (not actually a length) /// </summary> public bool IsPercentage { get { return _isPercentage; } } /// <summary> /// Gets if the length is specified in relative units /// </summary> public bool IsRelative { get { return _isRelative; } } /// <summary> /// Gets the unit of the length /// </summary> public CssUnit Unit { get { return _unit; } } /// <summary> /// Gets the length as specified in the string /// </summary> public string Length { get { return _length; } } #endregion #region Methods /// <summary> /// If length is in Ems, returns its value in points /// </summary> /// <param name="emSize">Em size factor to multiply</param> /// <returns>Points size of this em</returns> /// <exception cref="InvalidOperationException">If length has an error or isn't in ems</exception> public CssLength ConvertEmToPoints(float emSize) { if (HasError) throw new InvalidOperationException("Invalid length"); if (Unit != CssUnit.Ems) throw new InvalidOperationException("Length is not in ems"); return new CssLength(string.Format("{0}pt", Convert.ToSingle(Number * emSize).ToString("0.0", NumberFormatInfo.InvariantInfo))); } /// <summary> /// If length is in Ems, returns its value in pixels /// </summary> /// <param name="pixelFactor">Pixel size factor to multiply</param> /// <returns>Pixels size of this em</returns> /// <exception cref="InvalidOperationException">If length has an error or isn't in ems</exception> public CssLength ConvertEmToPixels(float pixelFactor) { if (HasError) throw new InvalidOperationException("Invalid length"); if (Unit != CssUnit.Ems) throw new InvalidOperationException("Length is not in ems"); return new CssLength(string.Format("{0}px", Convert.ToSingle(Number * pixelFactor).ToString("0.0", NumberFormatInfo.InvariantInfo))); } /// <summary> /// Returns the length formatted ready for CSS interpreting. /// </summary> /// <returns></returns> public override string ToString() { if (HasError) { return string.Empty; } else if (IsPercentage) { return string.Format(NumberFormatInfo.InvariantInfo, "{0}%", Number); } else { string u = string.Empty; switch (Unit) { case CssUnit.None: break; case CssUnit.Ems: u = "em"; break; case CssUnit.Pixels: u = "px"; break; case CssUnit.Ex: u = "ex"; break; case CssUnit.Inches: u = "in"; break; case CssUnit.Centimeters: u = "cm"; break; case CssUnit.Milimeters: u = "mm"; break; case CssUnit.Points: u = "pt"; break; case CssUnit.Picas: u = "pc"; break; } return string.Format(NumberFormatInfo.InvariantInfo, "{0}{1}", Number, u); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using System; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; // for Tuple (can't define alias for open generic types so we "use" the whole namespace) #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { // New in CLR4.0 internal enum ControllerCommand { // Strictly Positive numbers are for provider-specific commands, negative number are for 'shared' commands. 256 // The first 256 negative numbers are reserved for the framework. Update = 0, // Not used by EventPrividerBase. SendManifest = -1, Enable = -2, Disable = -3, }; /// <summary> /// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a /// controller callback) /// </summary> [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] internal partial class EventProvider : IDisposable { // This is the windows EVENT_DATA_DESCRIPTOR structure. We expose it because this is what // subclasses of EventProvider use when creating efficient (but unsafe) version of // EventWrite. We do make it a nested type because we really don't expect anyone to use // it except subclasses (and then only rarely). public struct EventData { internal unsafe ulong Ptr; internal uint Size; internal uint Reserved; } /// <summary> /// A struct characterizing ETW sessions (identified by the etwSessionId) as /// activity-tracing-aware or legacy. A session that's activity-tracing-aware /// has specified one non-zero bit in the reserved range 44-47 in the /// 'allKeywords' value it passed in for a specific EventProvider. /// </summary> public struct SessionInfo { internal int sessionIdBit; // the index of the bit used for tracing in the "reserved" field of AllKeywords internal int etwSessionId; // the machine-wide ETW session ID internal SessionInfo(int sessionIdBit_, int etwSessionId_) { sessionIdBit = sessionIdBit_; etwSessionId = etwSessionId_; } } private static bool m_setInformationMissing; [SecurityCritical] UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function private long m_regHandle; // Trace Registration Handle private byte m_level; // Tracing Level private long m_anyKeywordMask; // Trace Enable Flags private long m_allKeywordMask; // Match all keyword private List<SessionInfo> m_liveSessions; // current live sessions (Tuple<sessionIdBit, etwSessionId>) private bool m_enabled; // Enabled flag from Trace callback private Guid m_providerId; // Control Guid internal bool m_disposed; // when true provider has unregistered [ThreadStatic] private static WriteEventErrorCode s_returnCode; // The last return code private const int s_basicTypeAllocationBufferSize = 16; private const int s_etwMaxNumberArguments = 128; private const int s_etwAPIMaxRefObjCount = 8; private const int s_maxEventDataDescriptors = 128; private const int s_traceEventMaximumSize = 65482; private const int s_traceEventMaximumStringSize = 32724; [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public enum WriteEventErrorCode : int { //check mapping to runtime codes NoError = 0, NoFreeBuffers = 1, EventTooBig = 2, NullInput = 3, TooManyArgs = 4, Other = 5, }; // Because callbacks happen on registration, and we need the callbacks for those setup // we can't call Register in the constructor. // // Note that EventProvider should ONLY be used by EventSource. In particular because // it registers a callback from native code you MUST dispose it BEFORE shutdown, otherwise // you may get native callbacks during shutdown when we have destroyed the delegate. // EventSource has special logic to do this, no one else should be calling EventProvider. internal EventProvider() { } /// <summary> /// This method registers the controlGuid of this class with ETW. We need to be running on /// Vista or above. If not a PlatformNotSupported exception will be thrown. If for some /// reason the ETW Register call failed a NotSupported exception will be thrown. /// </summary> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventRegister(System.Guid&,Microsoft.Win32.UnsafeNativeMethods.ManifestEtw+EtwEnableCallback,System.Void*,System.Int64&):System.UInt32" /> // <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" /> // <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal unsafe void Register(Guid providerGuid) { m_providerId = providerGuid; uint status; m_etwCallback = new UnsafeNativeMethods.ManifestEtw.EtwEnableCallback(EtwEnableCallBack); status = EventRegister(ref m_providerId, m_etwCallback); if (status != 0) { throw new ArgumentException(Win32Native.GetMessage(unchecked((int)status))); } } // // implement Dispose Pattern to early deregister from ETW insted of waiting for // the finalizer to call deregistration. // Once the user is done with the provider it needs to call Close() or Dispose() // If neither are called the finalizer will unregister the provider anyway // public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1"> // <ReferencesCritical Name="Method: Deregister():Void" Ring="1" /> // </SecurityKernel> [System.Security.SecuritySafeCritical] protected virtual void Dispose(bool disposing) { // // explicit cleanup is done by calling Dispose with true from // Dispose() or Close(). The disposing arguement is ignored because there // are no unmanaged resources. // The finalizer calls Dispose with false. // // // check if the object has been allready disposed // if (m_disposed) return; // Disable the provider. m_enabled = false; // Do most of the work under a lock to avoid shutdown race. lock (EventListener.EventListenersLock) { // Double check if (m_disposed) return; Deregister(); m_disposed = true; } } /// <summary> /// This method deregisters the controlGuid of this class with ETW. /// /// </summary> public virtual void Close() { Dispose(); } ~EventProvider() { Dispose(false); } /// <summary> /// This method un-registers from ETW. /// </summary> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64):System.Int32" /> // </SecurityKernel> // TODO Check return code from UnsafeNativeMethods.ManifestEtw.EventUnregister [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Win32.UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64)"), System.Security.SecurityCritical] private unsafe void Deregister() { // // Unregister from ETW using the RegHandle saved from // the register call. // if (m_regHandle != 0) { EventUnregister(); m_regHandle = 0; } } // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Parameter filterData of type: Void*" /> // <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" /> // </SecurityKernel> [System.Security.SecurityCritical] unsafe void EtwEnableCallBack( [In] ref System.Guid sourceId, [In] int controlCode, [In] byte setLevel, [In] long anyKeyword, [In] long allKeyword, [In] UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, [In] void* callbackContext ) { // This is an optional callback API. We will therefore ignore any failures that happen as a // result of turning on this provider as to not crash the app. // EventSource has code to validate whether initialization it expected to occur actually occurred try { ControllerCommand command = ControllerCommand.Update; IDictionary<string, string> args = null; bool skipFinalOnControllerCommand = false; if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_ENABLE_PROVIDER) { m_enabled = true; m_level = setLevel; m_anyKeywordMask = anyKeyword; m_allKeywordMask = allKeyword; // ES_SESSION_INFO is a marker for additional places we #ifdeffed out to remove // references to EnumerateTraceGuidsEx. This symbol is actually not used because // today we use FEATURE_ACTIVITYSAMPLING to determine if this code is there or not. // However we put it in the #if so that we don't lose the fact that this feature // switch is at least partially independent of FEATURE_ACTIVITYSAMPLING List<Tuple<SessionInfo, bool>> sessionsChanged = GetSessions(); foreach (var session in sessionsChanged) { int sessionChanged = session.Item1.sessionIdBit; int etwSessionId = session.Item1.etwSessionId; bool bEnabling = session.Item2; skipFinalOnControllerCommand = true; args = null; // reinitialize args for every session... // if we get more than one session changed we have no way // of knowing which one "filterData" belongs to if (sessionsChanged.Count > 1) filterData = null; // read filter data only when a session is being *added* byte[] data; int keyIndex; if (bEnabling && GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex)) { args = new Dictionary<string, string>(4); while (keyIndex < data.Length) { int keyEnd = FindNull(data, keyIndex); int valueIdx = keyEnd + 1; int valueEnd = FindNull(data, valueIdx); if (valueEnd < data.Length) { string key = System.Text.Encoding.UTF8.GetString(data, keyIndex, keyEnd - keyIndex); string value = System.Text.Encoding.UTF8.GetString(data, valueIdx, valueEnd - valueIdx); args[key] = value; } keyIndex = valueEnd + 1; } } // execute OnControllerCommand once for every session that has changed. OnControllerCommand(command, args, (bEnabling ? sessionChanged : -sessionChanged), etwSessionId); } } else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_DISABLE_PROVIDER) { m_enabled = false; m_level = 0; m_anyKeywordMask = 0; m_allKeywordMask = 0; m_liveSessions = null; } else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_CAPTURE_STATE) { command = ControllerCommand.SendManifest; } else return; // per spec you ignore commands you don't recognize. if (!skipFinalOnControllerCommand) OnControllerCommand(command, args, 0, 0); } catch (Exception) { // We want to ignore any failures that happen as a result of turning on this provider as to // not crash the app. } } // New in CLR4.0 protected virtual void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments, int sessionId, int etwSessionId) { } protected EventLevel Level { get { return (EventLevel)m_level; } set { m_level = (byte)value; } } protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = unchecked((long)value); } } protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = unchecked((long)value); } } static private int FindNull(byte[] buffer, int idx) { while (idx < buffer.Length && buffer[idx] != 0) idx++; return idx; } /// <summary> /// Determines the ETW sessions that have been added and/or removed to the set of /// sessions interested in the current provider. It does so by (1) enumerating over all /// ETW sessions that enabled 'this.m_Guid' for the current process ID, and (2) /// comparing the current list with a list it cached on the previous invocation. /// /// The return value is a list of tuples, where the SessionInfo specifies the /// ETW session that was added or remove, and the bool specifies whether the /// session was added or whether it was removed from the set. /// </summary> [System.Security.SecuritySafeCritical] private List<Tuple<SessionInfo, bool>> GetSessions() { List<SessionInfo> liveSessionList = null; GetSessionInfo((Action<int, long>) ((etwSessionId, matchAllKeywords) => GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref liveSessionList))); List<Tuple<SessionInfo, bool>> changedSessionList = new List<Tuple<SessionInfo, bool>>(); // first look for sessions that have gone away (or have changed) // (present in the m_liveSessions but not in the new liveSessionList) if (m_liveSessions != null) { foreach (SessionInfo s in m_liveSessions) { int idx; if ((idx = IndexOfSessionInList(liveSessionList, s.etwSessionId)) < 0 || (liveSessionList[idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, false)); } } // next look for sessions that were created since the last callback (or have changed) // (present in the new liveSessionList but not in m_liveSessions) if (liveSessionList != null) { foreach (SessionInfo s in liveSessionList) { int idx; if ((idx = IndexOfSessionInList(m_liveSessions, s.etwSessionId)) < 0 || (m_liveSessions[idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, true)); } } m_liveSessions = liveSessionList; return changedSessionList; } /// <summary> /// This method is the callback used by GetSessions() when it calls into GetSessionInfo(). /// It updates a List{SessionInfo} based on the etwSessionId and matchAllKeywords that /// GetSessionInfo() passes in. /// </summary> private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywords, ref List<SessionInfo> sessionList) { uint sessionIdBitMask = (uint)SessionMask.FromEventKeywords(unchecked((ulong)matchAllKeywords)); // an ETW controller that specifies more than the mandated bit for our EventSource // will be ignored... if (bitcount(sessionIdBitMask) > 1) return; if (sessionList == null) sessionList = new List<SessionInfo>(8); if (bitcount(sessionIdBitMask) == 1) { // activity-tracing-aware etw session sessionList.Add(new SessionInfo(bitindex(sessionIdBitMask) + 1, etwSessionId)); } else { // legacy etw session sessionList.Add(new SessionInfo(bitcount((uint)SessionMask.All) + 1, etwSessionId)); } } /// <summary> /// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid' /// for the current process ID, calling 'action' for each session, and passing it the /// ETW session and the 'AllKeywords' the session enabled for the current provider. /// </summary> [System.Security.SecurityCritical] private unsafe void GetSessionInfo(Action<int, long> action) { // We wish the EventSource package to be legal for Windows Store applications. // Currently EnumerateTraceGuidsEx is not an allowed API, so we avoid its use here // and use the information in the registry instead. This means that ETW controllers // that do not publish their intent to the registry (basically all controllers EXCEPT // TraceEventSesion) will not work properly // However the framework version of EventSource DOES have ES_SESSION_INFO defined and thus // does not have this issue. #if ES_SESSION_INFO || !ES_BUILD_STANDALONE int buffSize = 256; // An initial guess that probably works most of the time. byte* buffer; for (; ; ) { var space = stackalloc byte[buffSize]; buffer = space; var hr = 0; fixed (Guid* provider = &m_providerId) { hr = UnsafeNativeMethods.ManifestEtw.EnumerateTraceGuidsEx(UnsafeNativeMethods.ManifestEtw.TRACE_QUERY_INFO_CLASS.TraceGuidQueryInfo, provider, sizeof(Guid), buffer, buffSize, ref buffSize); } if (hr == 0) break; if (hr != 122 /* ERROR_INSUFFICIENT_BUFFER */) return; } var providerInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_GUID_INFO*)buffer; var providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&providerInfos[1]; int processId = unchecked((int)Win32Native.GetCurrentProcessId()); // iterate over the instances of the EventProvider in all processes for (int i = 0; i < providerInfos->InstanceCount; i++) { if (providerInstance->Pid == processId) { var enabledInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_ENABLE_INFO*)&providerInstance[1]; // iterate over the list of active ETW sessions "listening" to the current provider for (int j = 0; j < providerInstance->EnableCount; j++) action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword); } if (providerInstance->NextOffset == 0) break; Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize); var structBase = (byte*)providerInstance; providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset]; } #else #if !ES_BUILD_PCL && !FEATURE_PAL // TODO command arguments don't work on PCL builds... // This code is only used in the Nuget Package Version of EventSource. because // the code above is using APIs baned from UWP apps. // // TODO: In addition to only working when TraceEventSession enables the provider, this code // also has a problem because TraceEvent does not clean up if the registry is stale // It is unclear if it is worth keeping, but for now we leave it as it does work // at least some of the time. // Determine our session from what is in the registry. string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}"; if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8) regKey = @"Software" + @"\Wow6432Node" + regKey; else regKey = @"Software" + regKey; var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regKey); if (key != null) { foreach (string valueName in key.GetValueNames()) { if (valueName.StartsWith("ControllerData_Session_", StringComparison.Ordinal)) { string strId = valueName.Substring(23); // strip of the ControllerData_Session_ int etwSessionId; if (int.TryParse(strId, out etwSessionId)) { // we need to assert this permission for partial trust scenarios (new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert(); var data = key.GetValue(valueName) as byte[]; if (data != null) { var dataAsString = System.Text.Encoding.UTF8.GetString(data); int keywordIdx = dataAsString.IndexOf("EtwSessionKeyword", StringComparison.Ordinal); if (0 <= keywordIdx) { int startIdx = keywordIdx + 18; int endIdx = dataAsString.IndexOf('\0', startIdx); string keywordBitString = dataAsString.Substring(startIdx, endIdx-startIdx); int keywordBit; if (0 < endIdx && int.TryParse(keywordBitString, out keywordBit)) action(etwSessionId, 1L << keywordBit); } } } } } } #endif #endif } /// <summary> /// Returns the index of the SesisonInfo from 'sessions' that has the specified 'etwSessionId' /// or -1 if the value is not present. /// </summary> private static int IndexOfSessionInList(List<SessionInfo> sessions, int etwSessionId) { if (sessions == null) return -1; // for non-coreclr code we could use List<T>.FindIndex(Predicate<T>), but we need this to compile // on coreclr as well for (int i = 0; i < sessions.Count; ++i) if (sessions[i].etwSessionId == etwSessionId) return i; return -1; } /// <summary> /// Gets any data to be passed from the controller to the provider. It starts with what is passed /// into the callback, but unfortunately this data is only present for when the provider is active /// at the time the controller issues the command. To allow for providers to activate after the /// controller issued a command, we also check the registry and use that to get the data. The function /// returns an array of bytes representing the data, the index into that byte array where the data /// starts, and the command being issued associated with that data. /// </summary> [System.Security.SecurityCritical] private unsafe bool GetDataFromController(int etwSessionId, UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart) { data = null; dataStart = 0; if (filterData == null) { #if (!ES_BUILD_PCL && !PROJECTN && !FEATURE_PAL) string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}"; if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8) regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey; else regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey; string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture); // we need to assert this permission for partial trust scenarios (new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert(); data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[]; if (data != null) { // We only used the persisted data from the registry for updates. command = ControllerCommand.Update; return true; } #endif } else { if (filterData->Ptr != 0 && 0 < filterData->Size && filterData->Size <= 1024) { data = new byte[filterData->Size]; Marshal.Copy((IntPtr)filterData->Ptr, data, 0, data.Length); } command = (ControllerCommand)filterData->Type; return true; } command = ControllerCommand.Update; return false; } /// <summary> /// IsEnabled, method used to test if provider is enabled /// </summary> public bool IsEnabled() { return m_enabled; } /// <summary> /// IsEnabled, method used to test if event is enabled /// </summary> /// <param name="level"> /// Level to test /// </param> /// <param name="keywords"> /// Keyword to test /// </param> public bool IsEnabled(byte level, long keywords) { // // If not enabled at all, return false. // if (!m_enabled) { return false; } // This also covers the case of Level == 0. if ((level <= m_level) || (m_level == 0)) { // // Check if Keyword is enabled // if ((keywords == 0) || (((keywords & m_anyKeywordMask) != 0) && ((keywords & m_allKeywordMask) == m_allKeywordMask))) { return true; } } return false; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public static WriteEventErrorCode GetLastWriteEventError() { return s_returnCode; } // // Helper function to set the last error on the thread // private static void SetLastError(int error) { switch (error) { case UnsafeNativeMethods.ManifestEtw.ERROR_ARITHMETIC_OVERFLOW: case UnsafeNativeMethods.ManifestEtw.ERROR_MORE_DATA: s_returnCode = WriteEventErrorCode.EventTooBig; break; case UnsafeNativeMethods.ManifestEtw.ERROR_NOT_ENOUGH_MEMORY: s_returnCode = WriteEventErrorCode.NoFreeBuffers; break; } } // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" /> // <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" /> // <UsesUnsafeCode Name="Local longptr of type: Int64*" /> // <UsesUnsafeCode Name="Local uintptr of type: UInt32*" /> // <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" /> // <UsesUnsafeCode Name="Local charptr of type: Char*" /> // <UsesUnsafeCode Name="Local byteptr of type: Byte*" /> // <UsesUnsafeCode Name="Local shortptr of type: Int16*" /> // <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" /> // <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" /> // <UsesUnsafeCode Name="Local floatptr of type: Single*" /> // <UsesUnsafeCode Name="Local doubleptr of type: Double*" /> // <UsesUnsafeCode Name="Local boolptr of type: Boolean*" /> // <UsesUnsafeCode Name="Local guidptr of type: Guid*" /> // <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" /> // <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" /> // <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" /> // <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" /> // </SecurityKernel> [System.Security.SecurityCritical] private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize) /*++ Routine Description: This routine is used by WriteEvent to unbox the object type and to fill the passed in ETW data descriptor. Arguments: data - argument to be decoded dataDescriptor - pointer to the descriptor to be filled (updated to point to the next empty entry) dataBuffer - storage buffer for storing user data, needed because cant get the address of the object (updated to point to the next empty entry) Return Value: null if the object is a basic type other than string or byte[]. String otherwise --*/ { Again: dataDescriptor->Reserved = 0; string sRet = data as string; byte[] blobRet = null; if (sRet != null) { dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } else if ((blobRet = data as byte[]) != null) { // first store array length *(int*)dataBuffer = blobRet.Length; dataDescriptor->Ptr = (ulong)dataBuffer; dataDescriptor->Size = 4; totalEventSize += dataDescriptor->Size; // then the array parameters dataDescriptor++; dataBuffer += s_basicTypeAllocationBufferSize; dataDescriptor->Size = (uint)blobRet.Length; } else if (data is IntPtr) { dataDescriptor->Size = (uint)sizeof(IntPtr); IntPtr* intptrPtr = (IntPtr*)dataBuffer; *intptrPtr = (IntPtr)data; dataDescriptor->Ptr = (ulong)intptrPtr; } else if (data is int) { dataDescriptor->Size = (uint)sizeof(int); int* intptr = (int*)dataBuffer; *intptr = (int)data; dataDescriptor->Ptr = (ulong)intptr; } else if (data is long) { dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = (long)data; dataDescriptor->Ptr = (ulong)longptr; } else if (data is uint) { dataDescriptor->Size = (uint)sizeof(uint); uint* uintptr = (uint*)dataBuffer; *uintptr = (uint)data; dataDescriptor->Ptr = (ulong)uintptr; } else if (data is UInt64) { dataDescriptor->Size = (uint)sizeof(ulong); UInt64* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->Ptr = (ulong)ulongptr; } else if (data is char) { dataDescriptor->Size = (uint)sizeof(char); char* charptr = (char*)dataBuffer; *charptr = (char)data; dataDescriptor->Ptr = (ulong)charptr; } else if (data is byte) { dataDescriptor->Size = (uint)sizeof(byte); byte* byteptr = (byte*)dataBuffer; *byteptr = (byte)data; dataDescriptor->Ptr = (ulong)byteptr; } else if (data is short) { dataDescriptor->Size = (uint)sizeof(short); short* shortptr = (short*)dataBuffer; *shortptr = (short)data; dataDescriptor->Ptr = (ulong)shortptr; } else if (data is sbyte) { dataDescriptor->Size = (uint)sizeof(sbyte); sbyte* sbyteptr = (sbyte*)dataBuffer; *sbyteptr = (sbyte)data; dataDescriptor->Ptr = (ulong)sbyteptr; } else if (data is ushort) { dataDescriptor->Size = (uint)sizeof(ushort); ushort* ushortptr = (ushort*)dataBuffer; *ushortptr = (ushort)data; dataDescriptor->Ptr = (ulong)ushortptr; } else if (data is float) { dataDescriptor->Size = (uint)sizeof(float); float* floatptr = (float*)dataBuffer; *floatptr = (float)data; dataDescriptor->Ptr = (ulong)floatptr; } else if (data is double) { dataDescriptor->Size = (uint)sizeof(double); double* doubleptr = (double*)dataBuffer; *doubleptr = (double)data; dataDescriptor->Ptr = (ulong)doubleptr; } else if (data is bool) { // WIN32 Bool is 4 bytes dataDescriptor->Size = 4; int* intptr = (int*)dataBuffer; if (((bool)data)) { *intptr = 1; } else { *intptr = 0; } dataDescriptor->Ptr = (ulong)intptr; } else if (data is Guid) { dataDescriptor->Size = (uint)sizeof(Guid); Guid* guidptr = (Guid*)dataBuffer; *guidptr = (Guid)data; dataDescriptor->Ptr = (ulong)guidptr; } else if (data is decimal) { dataDescriptor->Size = (uint)sizeof(decimal); decimal* decimalptr = (decimal*)dataBuffer; *decimalptr = (decimal)data; dataDescriptor->Ptr = (ulong)decimalptr; } else if (data is DateTime) { const long UTCMinTicks = 504911232000000000; long dateTimeTicks = 0; // We cannot translate dates sooner than 1/1/1601 in UTC. // To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks if (((DateTime)data).Ticks > UTCMinTicks) dateTimeTicks = ((DateTime)data).ToFileTimeUtc(); dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = dateTimeTicks; dataDescriptor->Ptr = (ulong)longptr; } else { if (data is System.Enum) { Type underlyingType = Enum.GetUnderlyingType(data.GetType()); if (underlyingType == typeof(int)) { #if !ES_BUILD_PCL data = ((IConvertible)data).ToInt32(null); #else data = (int)data; #endif goto Again; } else if (underlyingType == typeof(long)) { #if !ES_BUILD_PCL data = ((IConvertible)data).ToInt64(null); #else data = (long)data; #endif goto Again; } } // To our eyes, everything else is a just a string if (data == null) sRet = ""; else sRet = data.ToString(); dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } totalEventSize += dataDescriptor->Size; // advance buffers dataDescriptor++; dataBuffer += s_basicTypeAllocationBufferSize; return (object)sRet ?? (object)blobRet; } /// <summary> /// WriteEvent, method to write a parameters with event schema properties /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// childActivityID is marked as 'related' to the current activity ID. /// </param> /// <param name="eventPayload"> /// Payload for the ETW event. /// </param> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" /> // <UsesUnsafeCode Name="Local dataBuffer of type: Byte*" /> // <UsesUnsafeCode Name="Local pdata of type: Char*" /> // <UsesUnsafeCode Name="Local userData of type: EventData*" /> // <UsesUnsafeCode Name="Local userDataPtr of type: EventData*" /> // <UsesUnsafeCode Name="Local currentBuffer of type: Byte*" /> // <UsesUnsafeCode Name="Local v0 of type: Char*" /> // <UsesUnsafeCode Name="Local v1 of type: Char*" /> // <UsesUnsafeCode Name="Local v2 of type: Char*" /> // <UsesUnsafeCode Name="Local v3 of type: Char*" /> // <UsesUnsafeCode Name="Local v4 of type: Char*" /> // <UsesUnsafeCode Name="Local v5 of type: Char*" /> // <UsesUnsafeCode Name="Local v6 of type: Char*" /> // <UsesUnsafeCode Name="Local v7 of type: Char*" /> // <ReferencesCritical Name="Method: EncodeObject(Object&, EventData*, Byte*):String" Ring="1" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload) { int status = 0; if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { int argCount = 0; unsafe { argCount = eventPayload.Length; if (argCount > s_etwMaxNumberArguments) { s_returnCode = WriteEventErrorCode.TooManyArgs; return false; } uint totalEventSize = 0; int index; int refObjIndex = 0; List<int> refObjPosition = new List<int>(s_etwAPIMaxRefObjCount); List<object> dataRefObj = new List<object>(s_etwAPIMaxRefObjCount); EventData* userData = stackalloc EventData[2 * argCount]; EventData* userDataPtr = (EventData*)userData; byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * 2 * argCount]; // Assume 16 chars for non-string argument byte* currentBuffer = dataBuffer; // // The loop below goes through all the arguments and fills in the data // descriptors. For strings save the location in the dataString array. // Calculates the total size of the event by adding the data descriptor // size value set in EncodeObject method. // bool hasNonStringRefArgs = false; for (index = 0; index < eventPayload.Length; index++) { if (eventPayload[index] != null) { object supportedRefObj; supportedRefObj = EncodeObject(ref eventPayload[index], ref userDataPtr, ref currentBuffer, ref totalEventSize); if (supportedRefObj != null) { // EncodeObject advanced userDataPtr to the next empty slot int idx = (int)(userDataPtr - userData - 1); if (!(supportedRefObj is string)) { if (eventPayload.Length + idx + 1 - index > s_etwMaxNumberArguments) { s_returnCode = WriteEventErrorCode.TooManyArgs; return false; } hasNonStringRefArgs = true; } dataRefObj.Add(supportedRefObj); refObjPosition.Add(idx); refObjIndex++; } } else { s_returnCode = WriteEventErrorCode.NullInput; return false; } } // update argCount based on actual number of arguments written to 'userData' argCount = (int)(userDataPtr - userData); if (totalEventSize > s_traceEventMaximumSize) { s_returnCode = WriteEventErrorCode.EventTooBig; return false; } // the optimized path (using "fixed" instead of allocating pinned GCHandles if (!hasNonStringRefArgs && (refObjIndex < s_etwAPIMaxRefObjCount)) { // Fast path: at most 8 string arguments // ensure we have at least s_etwAPIMaxStringCount in dataString, so that // the "fixed" statement below works while (refObjIndex < s_etwAPIMaxRefObjCount) { dataRefObj.Add(null); ++refObjIndex; } // // now fix any string arguments and set the pointer on the data descriptor // fixed (char* v0 = (string)dataRefObj[0], v1 = (string)dataRefObj[1], v2 = (string)dataRefObj[2], v3 = (string)dataRefObj[3], v4 = (string)dataRefObj[4], v5 = (string)dataRefObj[5], v6 = (string)dataRefObj[6], v7 = (string)dataRefObj[7]) { userDataPtr = (EventData*)userData; if (dataRefObj[0] != null) { userDataPtr[refObjPosition[0]].Ptr = (ulong)v0; } if (dataRefObj[1] != null) { userDataPtr[refObjPosition[1]].Ptr = (ulong)v1; } if (dataRefObj[2] != null) { userDataPtr[refObjPosition[2]].Ptr = (ulong)v2; } if (dataRefObj[3] != null) { userDataPtr[refObjPosition[3]].Ptr = (ulong)v3; } if (dataRefObj[4] != null) { userDataPtr[refObjPosition[4]].Ptr = (ulong)v4; } if (dataRefObj[5] != null) { userDataPtr[refObjPosition[5]].Ptr = (ulong)v5; } if (dataRefObj[6] != null) { userDataPtr[refObjPosition[6]].Ptr = (ulong)v6; } if (dataRefObj[7] != null) { userDataPtr[refObjPosition[7]].Ptr = (ulong)v7; } status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData); } } else { // Slow path: use pinned handles userDataPtr = (EventData*)userData; GCHandle[] rgGCHandle = new GCHandle[refObjIndex]; for (int i = 0; i < refObjIndex; ++i) { // below we still use "fixed" to avoid taking dependency on the offset of the first field // in the object (the way we would need to if we used GCHandle.AddrOfPinnedObject) rgGCHandle[i] = GCHandle.Alloc(dataRefObj[i], GCHandleType.Pinned); if (dataRefObj[i] is string) { fixed (char* p = (string)dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } else { fixed (byte* p = (byte[])dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } } status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData); for (int i = 0; i < refObjIndex; ++i) { rgGCHandle[i].Free(); } } } } if (status != 0) { SetLastError((int)status); return false; } return true; } /// <summary> /// WriteEvent, method to be used by generated code on a derived class /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID to log /// </param> /// <param name="childActivityID"> /// If this event is generating a child activity (WriteEventTransfer related activity) this is child activity /// This can be null for events that do not generate a child activity. /// </param> /// <param name="dataCount"> /// number of event descriptors /// </param> /// <param name="data"> /// pointer do the event data /// </param> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data) { if (childActivityID != null) { // activity transfers are supported only for events that specify the Send or Receive opcode Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Start || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop); } int status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, dataCount, (EventData*)data); if (status != 0) { SetLastError(status); return false; } return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe bool WriteEventRaw( ref EventDescriptor eventDescriptor, Guid* activityID, Guid* relatedActivityID, int dataCount, IntPtr data) { int status; status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper( m_regHandle, ref eventDescriptor, activityID, relatedActivityID, dataCount, (EventData*)data); if (status != 0) { SetLastError(status); return false; } return true; } // These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work // either with Manifest ETW or Classic ETW (if Manifest based ETW is not available). [SecurityCritical] private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback) { m_providerId = providerId; m_etwCallback = enableCallback; return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle); } [SecurityCritical] private uint EventUnregister() { uint status = UnsafeNativeMethods.ManifestEtw.EventUnregister(m_regHandle); m_regHandle = 0; return status; } static int[] nibblebits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; private static int bitcount(uint n) { int count = 0; for (; n != 0; n = n >> 4) count += nibblebits[n & 0x0f]; return count; } private static int bitindex(uint n) { Contract.Assert(bitcount(n) == 1); int idx = 0; while ((n & (1 << idx)) == 0) idx++; return idx; } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Risk.Algo File: RiskRule.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Risk { using System; using System.Collections.Generic; using System.ComponentModel; using Ecng.Common; using Ecng.ComponentModel; using Ecng.Serialization; using Ecng.Collections; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// Base risk-rule. /// </summary> public abstract class RiskRule : NotifiableObject, IRiskRule { /// <summary> /// Initialize <see cref="RiskRule"/>. /// </summary> protected RiskRule() { } private string _title; /// <summary> /// Header. /// </summary> [Browsable(false)] public string Title { get { return _title; } protected set { _title = value; NotifyChanged("Title"); } } /// <summary> /// Action that needs to be taken in case of rule activation. /// </summary> [DisplayNameLoc(LocalizedStrings.Str722Key)] [DescriptionLoc(LocalizedStrings.Str859Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public RiskActions Action { get; set; } /// <summary> /// To reset the state. /// </summary> public virtual void Reset() { } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public abstract bool ProcessMessage(Message message); /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public virtual void Load(SettingsStorage storage) { Action = storage.GetValue<RiskActions>(nameof(Action)); } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public virtual void Save(SettingsStorage storage) { storage.SetValue(nameof(Action), Action.To<string>()); } } /// <summary> /// Risk-rule, tracking profit-loss. /// </summary> [DisplayNameLoc(LocalizedStrings.PnLKey)] [DescriptionLoc(LocalizedStrings.Str860Key)] public class RiskPnLRule : RiskRule { private decimal _pnL; /// <summary> /// Profit-loss. /// </summary> [DisplayNameLoc(LocalizedStrings.PnLKey)] [DescriptionLoc(LocalizedStrings.Str861Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public decimal PnL { get { return _pnL; } set { _pnL = value; Title = value.To<string>(); } } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public override bool ProcessMessage(Message message) { if (message.Type != MessageTypes.PortfolioChange) return false; var pfMsg = (PortfolioChangeMessage)message; var currValue = (decimal?)pfMsg.Changes.TryGetValue(PositionChangeTypes.CurrentValue); if (currValue == null) return false; if (PnL > 0) return currValue >= PnL; else return currValue <= PnL; } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(PnL), PnL); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); PnL = storage.GetValue<decimal>(nameof(PnL)); } } /// <summary> /// Risk-rule, tracking position size. /// </summary> [DisplayNameLoc(LocalizedStrings.Str862Key)] [DescriptionLoc(LocalizedStrings.Str863Key)] public class RiskPositionSizeRule : RiskRule { private decimal _position; /// <summary> /// Position size. /// </summary> [DisplayNameLoc(LocalizedStrings.Str862Key)] [DescriptionLoc(LocalizedStrings.Str864Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public decimal Position { get { return _position; } set { _position = value; Title = value.To<string>(); } } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public override bool ProcessMessage(Message message) { if (message.Type != MessageTypes.PositionChange) return false; var posMsg = (PositionChangeMessage)message; var currValue = (decimal?)posMsg.Changes.TryGetValue(PositionChangeTypes.CurrentValue); if (currValue == null) return false; if (Position > 0) return currValue >= Position; else return currValue <= Position; } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(Position), Position); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); Position = storage.GetValue<decimal>(nameof(Position)); } } /// <summary> /// Risk-rule, tracking position lifetime. /// </summary> [DisplayNameLoc(LocalizedStrings.Str865Key)] [DescriptionLoc(LocalizedStrings.Str866Key)] public class RiskPositionTimeRule : RiskRule { private readonly Dictionary<Tuple<SecurityId, string>, DateTimeOffset> _posOpenTime = new Dictionary<Tuple<SecurityId, string>, DateTimeOffset>(); private TimeSpan _time; /// <summary> /// Position lifetime. /// </summary> [DisplayNameLoc(LocalizedStrings.TimeKey)] [DescriptionLoc(LocalizedStrings.Str867Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public TimeSpan Time { get { return _time; } set { _time = value; Title = value.To<string>(); } } /// <summary> /// To reset the state. /// </summary> public override void Reset() { base.Reset(); _posOpenTime.Clear(); } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public override bool ProcessMessage(Message message) { switch (message.Type) { case MessageTypes.PositionChange: { var posMsg = (PositionChangeMessage)message; var currValue = (decimal?)posMsg.Changes.TryGetValue(PositionChangeTypes.CurrentValue); if (currValue == null) return false; var key = Tuple.Create(posMsg.SecurityId, posMsg.PortfolioName); if (currValue == 0) { _posOpenTime.Remove(key); return false; } var openTime = _posOpenTime.TryGetValue2(key); if (openTime == null) { _posOpenTime.Add(key, posMsg.LocalTime); return false; } var diff = posMsg.LocalTime - openTime; if (diff < Time) return false; _posOpenTime.Remove(key); return true; } case MessageTypes.Time: { List<Tuple<SecurityId, string>> removingPos = null; foreach (var pair in _posOpenTime) { var diff = message.LocalTime - pair.Value; if (diff < Time) continue; if (removingPos == null) removingPos = new List<Tuple<SecurityId, string>>(); removingPos.Add(pair.Key); } if (removingPos != null) removingPos.ForEach(t => _posOpenTime.Remove(t)); return removingPos != null; } } return false; } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(Time), Time); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); Time = storage.GetValue<TimeSpan>(nameof(Time)); } } /// <summary> /// Risk-rule, tracking commission size. /// </summary> [DisplayNameLoc(LocalizedStrings.Str159Key)] [DescriptionLoc(LocalizedStrings.Str868Key)] public class RiskCommissionRule : RiskRule { private decimal _commission; /// <summary> /// Commission size. /// </summary> [DisplayNameLoc(LocalizedStrings.Str159Key)] [DescriptionLoc(LocalizedStrings.Str869Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public decimal Commission { get { return _commission; } set { _commission = value; Title = value.To<string>(); } } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public override bool ProcessMessage(Message message) { if (message.Type != MessageTypes.PortfolioChange) return false; var pfMsg = (PortfolioChangeMessage)message; var currValue = (decimal?)pfMsg.Changes.TryGetValue(PositionChangeTypes.Commission); if (currValue == null) return false; return currValue >= Commission; } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(Commission), Commission); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); Commission = storage.GetValue<decimal>(nameof(Commission)); } } /// <summary> /// Risk-rule, tracking slippage size. /// </summary> [DisplayNameLoc(LocalizedStrings.Str163Key)] [DescriptionLoc(LocalizedStrings.Str870Key)] public class RiskSlippageRule : RiskRule { private decimal _slippage; /// <summary> /// Sllippage size. /// </summary> [DisplayNameLoc(LocalizedStrings.Str163Key)] [DescriptionLoc(LocalizedStrings.Str871Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public decimal Slippage { get { return _slippage; } set { _slippage = value; Title = value.To<string>(); } } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public override bool ProcessMessage(Message message) { if (message.Type != MessageTypes.Execution) return false; var execMsg = (ExecutionMessage)message; var currValue = execMsg.Slippage; if (currValue == null) return false; if (Slippage > 0) return currValue > Slippage; else return currValue < Slippage; } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(Slippage), Slippage); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); Slippage = storage.GetValue<decimal>(nameof(Slippage)); } } /// <summary> /// Risk-rule, tracking order price. /// </summary> [DisplayNameLoc(LocalizedStrings.Str872Key)] [DescriptionLoc(LocalizedStrings.Str873Key)] public class RiskOrderPriceRule : RiskRule { private decimal _price; /// <summary> /// Order price. /// </summary> [DisplayNameLoc(LocalizedStrings.PriceKey)] [DescriptionLoc(LocalizedStrings.OrderPriceKey)] [CategoryLoc(LocalizedStrings.GeneralKey)] public decimal Price { get { return _price; } set { _price = value; Title = value.To<string>(); } } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public override bool ProcessMessage(Message message) { switch (message.Type) { case MessageTypes.OrderRegister: { var orderReg = (OrderRegisterMessage)message; return orderReg.Price >= Price; } case MessageTypes.OrderReplace: { var orderReplace = (OrderReplaceMessage)message; return orderReplace.Price > 0 && orderReplace.Price >= Price; } default: return false; } } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(Price), Price); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); Price = storage.GetValue<decimal>(nameof(Price)); } } /// <summary> /// Risk-rule, tracking order volume. /// </summary> [DisplayNameLoc(LocalizedStrings.Str662Key)] [DescriptionLoc(LocalizedStrings.Str874Key)] public class RiskOrderVolumeRule : RiskRule { private decimal _volume; /// <summary> /// Order volume. /// </summary> [DisplayNameLoc(LocalizedStrings.VolumeKey)] [DescriptionLoc(LocalizedStrings.Str875Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public decimal Volume { get { return _volume; } set { _volume = value; Title = value.To<string>(); } } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public override bool ProcessMessage(Message message) { switch (message.Type) { case MessageTypes.OrderRegister: { var orderReg = (OrderRegisterMessage)message; return orderReg.Volume >= Volume; } case MessageTypes.OrderReplace: { var orderReplace = (OrderReplaceMessage)message; return orderReplace.Volume > 0 && orderReplace.Volume >= Volume; } default: return false; } } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(Volume), Volume); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); Volume = storage.GetValue<decimal>(nameof(Volume)); } } /// <summary> /// Risk-rule, tracking orders placing frequency. /// </summary> [DisplayNameLoc(LocalizedStrings.Str876Key)] [DescriptionLoc(LocalizedStrings.Str877Key)] public class RiskOrderFreqRule : RiskRule { private DateTimeOffset? _endTime; private int _current; private int _count; /// <summary> /// Order count. /// </summary> [DisplayNameLoc(LocalizedStrings.Str878Key)] [DescriptionLoc(LocalizedStrings.Str669Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public int Count { get { return _count; } set { _count = value; Title = value.To<string>(); } } private TimeSpan _interval; /// <summary> /// Interval, during which orders quantity will be monitored. /// </summary> [DisplayNameLoc(LocalizedStrings.Str175Key)] [DescriptionLoc(LocalizedStrings.Str879Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public TimeSpan Interval { get { return _interval; } set { _interval = value; Title = value.To<string>(); } } /// <summary> /// To reset the state. /// </summary> public override void Reset() { base.Reset(); _current = 0; _endTime = null; } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public override bool ProcessMessage(Message message) { switch (message.Type) { case MessageTypes.OrderRegister: case MessageTypes.OrderReplace: case MessageTypes.OrderPairReplace: { if (_endTime == null) { _endTime = message.LocalTime + Interval; _current = 1; return false; } if (message.LocalTime < _endTime) { _current++; if (_current >= Count) { _endTime = message.LocalTime + Interval; _current = 0; return true; } return false; } _endTime = message.LocalTime + Interval; _current = 0; return false; } } return false; } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(Count), Count); storage.SetValue(nameof(Interval), Interval); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); Count = storage.GetValue<int>(nameof(Count)); Interval = storage.GetValue<TimeSpan>(nameof(Interval)); } } /// <summary> /// Risk-rule, tracking trade price. /// </summary> [DisplayNameLoc(LocalizedStrings.Str672Key)] [DescriptionLoc(LocalizedStrings.Str880Key)] public class RiskTradePriceRule : RiskRule { private decimal _price; /// <summary> /// Trade price. /// </summary> [DisplayNameLoc(LocalizedStrings.PriceKey)] [DescriptionLoc(LocalizedStrings.Str147Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public decimal Price { get { return _price; } set { _price = value; Title = value.To<string>(); } } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public override bool ProcessMessage(Message message) { if (message.Type != MessageTypes.Execution) return false; var execMsg = (ExecutionMessage)message; if (!execMsg.HasTradeInfo()) return false; return execMsg.TradePrice >= Price; } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(Price), Price); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); Price = storage.GetValue<decimal>(nameof(Price)); } } /// <summary> /// Risk-rule, tracking trade volume. /// </summary> [DisplayNameLoc(LocalizedStrings.Str664Key)] [DescriptionLoc(LocalizedStrings.Str881Key)] public class RiskTradeVolumeRule : RiskRule { private decimal _volume; /// <summary> /// Trade volume. /// </summary> [DisplayNameLoc(LocalizedStrings.VolumeKey)] [DescriptionLoc(LocalizedStrings.Str882Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public decimal Volume { get { return _volume; } set { _volume = value; Title = value.To<string>(); } } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public override bool ProcessMessage(Message message) { if (message.Type != MessageTypes.Execution) return false; var execMsg = (ExecutionMessage)message; if (!execMsg.HasTradeInfo()) return false; return execMsg.TradeVolume >= Volume; } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(Volume), Volume); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); Volume = storage.GetValue<decimal>(nameof(Volume)); } } /// <summary> /// Risk-rule, tracking orders execution frequency. /// </summary> [DisplayNameLoc(LocalizedStrings.Str883Key)] [DescriptionLoc(LocalizedStrings.Str884Key)] public class RiskTradeFreqRule : RiskRule { private DateTimeOffset? _endTime; private int _current; private int _count; /// <summary> /// Number of trades. /// </summary> [DisplayNameLoc(LocalizedStrings.Str878Key)] [DescriptionLoc(LocalizedStrings.Str232Key, true)] [CategoryLoc(LocalizedStrings.GeneralKey)] public int Count { get { return _count; } set { _count = value; Title = value.To<string>(); } } private TimeSpan _interval; /// <summary> /// Interval, during which trades quantity will be monitored. /// </summary> [DisplayNameLoc(LocalizedStrings.Str175Key)] [DescriptionLoc(LocalizedStrings.Str885Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public TimeSpan Interval { get { return _interval; } set { _interval = value; Title = value.To<string>(); } } /// <summary> /// To reset the state. /// </summary> public override void Reset() { base.Reset(); _current = 0; _endTime = null; } /// <summary> /// To process the trade message. /// </summary> /// <param name="message">The trade message.</param> /// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns> public override bool ProcessMessage(Message message) { if (message.Type != MessageTypes.Execution) return false; var execMsg = (ExecutionMessage)message; if (!execMsg.HasTradeInfo()) return false; if (_endTime == null) { _endTime = message.LocalTime + Interval; _current = 1; return false; } if (message.LocalTime < _endTime) { _current++; if (_current >= Count) { _endTime = message.LocalTime + Interval; _current = 0; return true; } return false; } _endTime = message.LocalTime + Interval; _current = 0; return false; } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(Count), Count); storage.SetValue(nameof(Interval), Interval); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); Count = storage.GetValue<int>(nameof(Count)); Interval = storage.GetValue<TimeSpan>(nameof(Interval)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class HttpRedirectsExtensions { /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Head300(this IHttpRedirects operations) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Head300Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Head300Async( this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Head300WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IList<string> Get300(this IHttpRedirects operations) { return Task.Factory.StartNew(s => ((IHttpRedirects)s).Get300Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<string>> Get300Async( this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<IList<string>> result = await operations.Get300WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Head301(this IHttpRedirects operations) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Head301Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Head301Async( this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Head301WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Get301(this IHttpRedirects operations) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Get301Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Get301Async( this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get301WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put true Boolean value in request returns 301. This request should not be /// automatically redirected, but should return the received 301 to the /// caller for evaluation /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Put301(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Put301Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put true Boolean value in request returns 301. This request should not be /// automatically redirected, but should return the received 301 to the /// caller for evaluation /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Put301Async( this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Put301WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Head302(this IHttpRedirects operations) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Head302Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Head302Async( this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Head302WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Get302(this IHttpRedirects operations) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Get302Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Get302Async( this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get302WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Patch true Boolean value in request returns 302. This request should not /// be automatically redirected, but should return the received 302 to the /// caller for evaluation /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Patch302(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Patch302Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Patch true Boolean value in request returns 302. This request should not /// be automatically redirected, but should return the received 302 to the /// caller for evaluation /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Patch302Async( this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Patch302WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Post true Boolean value in request returns 303. This request should be /// automatically redirected usign a get, ultimately returning a 200 status /// code /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Post303(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Post303Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Post true Boolean value in request returns 303. This request should be /// automatically redirected usign a get, ultimately returning a 200 status /// code /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Post303Async( this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Post303WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Redirect with 307, resulting in a 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Head307(this IHttpRedirects operations) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Head307Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Redirect with 307, resulting in a 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Head307Async( this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Head307WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Redirect get with 307, resulting in a 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Get307(this IHttpRedirects operations) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Get307Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Redirect get with 307, resulting in a 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Get307Async( this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get307WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Put307(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Put307Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Put307Async( this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Put307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Patch redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Patch307(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Patch307Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Patch redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Patch307Async( this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Patch307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Post redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Post307(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Post307Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Post redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Post307Async( this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Post307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Delete307(this IHttpRedirects operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRedirects)s).Delete307Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Delete307Async( this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Delete307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } } }
/* Copyright (c) 2012, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ // [AUTO_HEADER] namespace TakaoPreference { partial class PanelPhonetic { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PanelPhonetic)); this.u_smartPhoneticGroup = new System.Windows.Forms.GroupBox(); this.u_invisibleSmartLabel = new System.Windows.Forms.Label(); this.u_smartPhonetickeyboardLayoutComboBox = new System.Windows.Forms.ComboBox(); this.u_buferSizeNotelabel = new System.Windows.Forms.Label(); this.u_bufferSizeUnitLabel = new System.Windows.Forms.Label(); this.u_bufferSizeLabel = new System.Windows.Forms.Label(); this.u_bufferSizeNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.u_selectionKeyComboBox = new System.Windows.Forms.ComboBox(); this.u_selectionKeyLabel = new System.Windows.Forms.Label(); this.u_smartPhoneticExtraSettinglabel = new System.Windows.Forms.Label(); this.u_smartPhoneticTypingLabel = new System.Windows.Forms.Label(); this.u_clearWithEscCheckBox = new System.Windows.Forms.CheckBox(); this.u_showCandidateWithSpaceCheckBox = new System.Windows.Forms.CheckBox(); this.u_smartPhoneticKeyboardLayoutLabel = new System.Windows.Forms.Label(); this.u_smartPhoneticNonBig5CheckBox = new System.Windows.Forms.CheckBox(); this.u_titleLabel = new System.Windows.Forms.Label(); this.u_traditionalPhoneticGroup = new System.Windows.Forms.GroupBox(); this.u_invisibleTraditionalLabel = new System.Windows.Forms.Label(); this.u_traditionalPhoneticKeyboardLayoutComboBox = new System.Windows.Forms.ComboBox(); this.u_traditionalPhoneticExtraSettingLabel = new System.Windows.Forms.Label(); this.u_traditionalPhoneticKeyboardLayoutLabel = new System.Windows.Forms.Label(); this.u_traditionalPhoneticNonBig5CheckBox = new System.Windows.Forms.CheckBox(); this.u_smartPhoneticGroup.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.u_bufferSizeNumericUpDown)).BeginInit(); this.u_traditionalPhoneticGroup.SuspendLayout(); this.SuspendLayout(); // // u_smartPhoneticGroup // this.u_smartPhoneticGroup.AccessibleDescription = null; this.u_smartPhoneticGroup.AccessibleName = null; resources.ApplyResources(this.u_smartPhoneticGroup, "u_smartPhoneticGroup"); this.u_smartPhoneticGroup.BackgroundImage = null; this.u_smartPhoneticGroup.Controls.Add(this.u_invisibleSmartLabel); this.u_smartPhoneticGroup.Controls.Add(this.u_smartPhonetickeyboardLayoutComboBox); this.u_smartPhoneticGroup.Controls.Add(this.u_buferSizeNotelabel); this.u_smartPhoneticGroup.Controls.Add(this.u_bufferSizeUnitLabel); this.u_smartPhoneticGroup.Controls.Add(this.u_bufferSizeLabel); this.u_smartPhoneticGroup.Controls.Add(this.u_bufferSizeNumericUpDown); this.u_smartPhoneticGroup.Controls.Add(this.u_selectionKeyComboBox); this.u_smartPhoneticGroup.Controls.Add(this.u_selectionKeyLabel); this.u_smartPhoneticGroup.Controls.Add(this.u_smartPhoneticExtraSettinglabel); this.u_smartPhoneticGroup.Controls.Add(this.u_smartPhoneticTypingLabel); this.u_smartPhoneticGroup.Controls.Add(this.u_clearWithEscCheckBox); this.u_smartPhoneticGroup.Controls.Add(this.u_showCandidateWithSpaceCheckBox); this.u_smartPhoneticGroup.Controls.Add(this.u_smartPhoneticKeyboardLayoutLabel); this.u_smartPhoneticGroup.Controls.Add(this.u_smartPhoneticNonBig5CheckBox); this.u_smartPhoneticGroup.Font = null; this.u_smartPhoneticGroup.Name = "u_smartPhoneticGroup"; this.u_smartPhoneticGroup.TabStop = false; // // u_invisibleSmartLabel // this.u_invisibleSmartLabel.AccessibleDescription = null; this.u_invisibleSmartLabel.AccessibleName = null; resources.ApplyResources(this.u_invisibleSmartLabel, "u_invisibleSmartLabel"); this.u_invisibleSmartLabel.Font = null; this.u_invisibleSmartLabel.Name = "u_invisibleSmartLabel"; this.u_invisibleSmartLabel.Click += new System.EventHandler(this.ShowExtraKeyboardLayouts); // // u_smartPhonetickeyboardLayoutComboBox // this.u_smartPhonetickeyboardLayoutComboBox.AccessibleDescription = null; this.u_smartPhonetickeyboardLayoutComboBox.AccessibleName = null; resources.ApplyResources(this.u_smartPhonetickeyboardLayoutComboBox, "u_smartPhonetickeyboardLayoutComboBox"); this.u_smartPhonetickeyboardLayoutComboBox.BackgroundImage = null; this.u_smartPhonetickeyboardLayoutComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_smartPhonetickeyboardLayoutComboBox.Font = null; this.u_smartPhonetickeyboardLayoutComboBox.FormattingEnabled = true; this.u_smartPhonetickeyboardLayoutComboBox.Items.AddRange(new object[] { resources.GetString("u_smartPhonetickeyboardLayoutComboBox.Items"), resources.GetString("u_smartPhonetickeyboardLayoutComboBox.Items1"), resources.GetString("u_smartPhonetickeyboardLayoutComboBox.Items2")}); this.u_smartPhonetickeyboardLayoutComboBox.Name = "u_smartPhonetickeyboardLayoutComboBox"; this.u_smartPhonetickeyboardLayoutComboBox.SelectedIndexChanged += new System.EventHandler(this.ChangeSmartPhoneticKeyboardLayout); // // u_buferSizeNotelabel // this.u_buferSizeNotelabel.AccessibleDescription = null; this.u_buferSizeNotelabel.AccessibleName = null; resources.ApplyResources(this.u_buferSizeNotelabel, "u_buferSizeNotelabel"); this.u_buferSizeNotelabel.Font = null; this.u_buferSizeNotelabel.Name = "u_buferSizeNotelabel"; // // u_bufferSizeUnitLabel // this.u_bufferSizeUnitLabel.AccessibleDescription = null; this.u_bufferSizeUnitLabel.AccessibleName = null; resources.ApplyResources(this.u_bufferSizeUnitLabel, "u_bufferSizeUnitLabel"); this.u_bufferSizeUnitLabel.Font = null; this.u_bufferSizeUnitLabel.Name = "u_bufferSizeUnitLabel"; // // u_bufferSizeLabel // this.u_bufferSizeLabel.AccessibleDescription = null; this.u_bufferSizeLabel.AccessibleName = null; resources.ApplyResources(this.u_bufferSizeLabel, "u_bufferSizeLabel"); this.u_bufferSizeLabel.Font = null; this.u_bufferSizeLabel.Name = "u_bufferSizeLabel"; // // u_bufferSizeNumericUpDown // this.u_bufferSizeNumericUpDown.AccessibleDescription = null; this.u_bufferSizeNumericUpDown.AccessibleName = null; resources.ApplyResources(this.u_bufferSizeNumericUpDown, "u_bufferSizeNumericUpDown"); this.u_bufferSizeNumericUpDown.Font = null; this.u_bufferSizeNumericUpDown.Maximum = new decimal(new int[] { 20, 0, 0, 0}); this.u_bufferSizeNumericUpDown.Minimum = new decimal(new int[] { 10, 0, 0, 0}); this.u_bufferSizeNumericUpDown.Name = "u_bufferSizeNumericUpDown"; this.u_bufferSizeNumericUpDown.Value = new decimal(new int[] { 10, 0, 0, 0}); this.u_bufferSizeNumericUpDown.ValueChanged += new System.EventHandler(this.ChangeBufferSize); // // u_selectionKeyComboBox // this.u_selectionKeyComboBox.AccessibleDescription = null; this.u_selectionKeyComboBox.AccessibleName = null; resources.ApplyResources(this.u_selectionKeyComboBox, "u_selectionKeyComboBox"); this.u_selectionKeyComboBox.AutoCompleteCustomSource.AddRange(new string[] { resources.GetString("u_selectionKeyComboBox.AutoCompleteCustomSource"), resources.GetString("u_selectionKeyComboBox.AutoCompleteCustomSource1"), resources.GetString("u_selectionKeyComboBox.AutoCompleteCustomSource2")}); this.u_selectionKeyComboBox.BackgroundImage = null; this.u_selectionKeyComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_selectionKeyComboBox.Font = null; this.u_selectionKeyComboBox.FormattingEnabled = true; this.u_selectionKeyComboBox.Items.AddRange(new object[] { resources.GetString("u_selectionKeyComboBox.Items"), resources.GetString("u_selectionKeyComboBox.Items1"), resources.GetString("u_selectionKeyComboBox.Items2")}); this.u_selectionKeyComboBox.Name = "u_selectionKeyComboBox"; this.u_selectionKeyComboBox.SelectedIndexChanged += new System.EventHandler(this.ChangeSelectionKey); this.u_selectionKeyComboBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.KeyInNewSelectionKey); // // u_selectionKeyLabel // this.u_selectionKeyLabel.AccessibleDescription = null; this.u_selectionKeyLabel.AccessibleName = null; resources.ApplyResources(this.u_selectionKeyLabel, "u_selectionKeyLabel"); this.u_selectionKeyLabel.Font = null; this.u_selectionKeyLabel.Name = "u_selectionKeyLabel"; this.u_selectionKeyLabel.MouseClick += new System.Windows.Forms.MouseEventHandler(this.ShowExtraSelectionKeySets); // // u_smartPhoneticExtraSettinglabel // this.u_smartPhoneticExtraSettinglabel.AccessibleDescription = null; this.u_smartPhoneticExtraSettinglabel.AccessibleName = null; resources.ApplyResources(this.u_smartPhoneticExtraSettinglabel, "u_smartPhoneticExtraSettinglabel"); this.u_smartPhoneticExtraSettinglabel.Font = null; this.u_smartPhoneticExtraSettinglabel.Name = "u_smartPhoneticExtraSettinglabel"; // // u_smartPhoneticTypingLabel // this.u_smartPhoneticTypingLabel.AccessibleDescription = null; this.u_smartPhoneticTypingLabel.AccessibleName = null; resources.ApplyResources(this.u_smartPhoneticTypingLabel, "u_smartPhoneticTypingLabel"); this.u_smartPhoneticTypingLabel.Font = null; this.u_smartPhoneticTypingLabel.Name = "u_smartPhoneticTypingLabel"; // // u_clearWithEscCheckBox // this.u_clearWithEscCheckBox.AccessibleDescription = null; this.u_clearWithEscCheckBox.AccessibleName = null; resources.ApplyResources(this.u_clearWithEscCheckBox, "u_clearWithEscCheckBox"); this.u_clearWithEscCheckBox.BackgroundImage = null; this.u_clearWithEscCheckBox.Font = null; this.u_clearWithEscCheckBox.Name = "u_clearWithEscCheckBox"; this.u_clearWithEscCheckBox.UseVisualStyleBackColor = true; this.u_clearWithEscCheckBox.CheckedChanged += new System.EventHandler(this.ChangeClearWithEscCheckBox); // // u_showCandidateWithSpaceCheckBox // this.u_showCandidateWithSpaceCheckBox.AccessibleDescription = null; this.u_showCandidateWithSpaceCheckBox.AccessibleName = null; resources.ApplyResources(this.u_showCandidateWithSpaceCheckBox, "u_showCandidateWithSpaceCheckBox"); this.u_showCandidateWithSpaceCheckBox.BackgroundImage = null; this.u_showCandidateWithSpaceCheckBox.Font = null; this.u_showCandidateWithSpaceCheckBox.Name = "u_showCandidateWithSpaceCheckBox"; this.u_showCandidateWithSpaceCheckBox.UseVisualStyleBackColor = true; this.u_showCandidateWithSpaceCheckBox.CheckedChanged += new System.EventHandler(this.ChangeShowCandidateWithSpaceCheckBox); // // u_smartPhoneticKeyboardLayoutLabel // this.u_smartPhoneticKeyboardLayoutLabel.AccessibleDescription = null; this.u_smartPhoneticKeyboardLayoutLabel.AccessibleName = null; resources.ApplyResources(this.u_smartPhoneticKeyboardLayoutLabel, "u_smartPhoneticKeyboardLayoutLabel"); this.u_smartPhoneticKeyboardLayoutLabel.Font = null; this.u_smartPhoneticKeyboardLayoutLabel.Name = "u_smartPhoneticKeyboardLayoutLabel"; // // u_smartPhoneticNonBig5CheckBox // this.u_smartPhoneticNonBig5CheckBox.AccessibleDescription = null; this.u_smartPhoneticNonBig5CheckBox.AccessibleName = null; resources.ApplyResources(this.u_smartPhoneticNonBig5CheckBox, "u_smartPhoneticNonBig5CheckBox"); this.u_smartPhoneticNonBig5CheckBox.BackgroundImage = null; this.u_smartPhoneticNonBig5CheckBox.Font = null; this.u_smartPhoneticNonBig5CheckBox.Name = "u_smartPhoneticNonBig5CheckBox"; this.u_smartPhoneticNonBig5CheckBox.UseVisualStyleBackColor = true; this.u_smartPhoneticNonBig5CheckBox.CheckedChanged += new System.EventHandler(this.ChangeSmartPhoneticUseNonBig5); // // u_titleLabel // this.u_titleLabel.AccessibleDescription = null; this.u_titleLabel.AccessibleName = null; resources.ApplyResources(this.u_titleLabel, "u_titleLabel"); this.u_titleLabel.Font = null; this.u_titleLabel.Name = "u_titleLabel"; // // u_traditionalPhoneticGroup // this.u_traditionalPhoneticGroup.AccessibleDescription = null; this.u_traditionalPhoneticGroup.AccessibleName = null; resources.ApplyResources(this.u_traditionalPhoneticGroup, "u_traditionalPhoneticGroup"); this.u_traditionalPhoneticGroup.BackgroundImage = null; this.u_traditionalPhoneticGroup.Controls.Add(this.u_invisibleTraditionalLabel); this.u_traditionalPhoneticGroup.Controls.Add(this.u_traditionalPhoneticKeyboardLayoutComboBox); this.u_traditionalPhoneticGroup.Controls.Add(this.u_traditionalPhoneticExtraSettingLabel); this.u_traditionalPhoneticGroup.Controls.Add(this.u_traditionalPhoneticKeyboardLayoutLabel); this.u_traditionalPhoneticGroup.Controls.Add(this.u_traditionalPhoneticNonBig5CheckBox); this.u_traditionalPhoneticGroup.Font = null; this.u_traditionalPhoneticGroup.Name = "u_traditionalPhoneticGroup"; this.u_traditionalPhoneticGroup.TabStop = false; // // u_invisibleTraditionalLabel // this.u_invisibleTraditionalLabel.AccessibleDescription = null; this.u_invisibleTraditionalLabel.AccessibleName = null; resources.ApplyResources(this.u_invisibleTraditionalLabel, "u_invisibleTraditionalLabel"); this.u_invisibleTraditionalLabel.Font = null; this.u_invisibleTraditionalLabel.Name = "u_invisibleTraditionalLabel"; this.u_invisibleTraditionalLabel.Click += new System.EventHandler(this.ShowExtraKeyboardLayouts); // // u_traditionalPhoneticKeyboardLayoutComboBox // this.u_traditionalPhoneticKeyboardLayoutComboBox.AccessibleDescription = null; this.u_traditionalPhoneticKeyboardLayoutComboBox.AccessibleName = null; resources.ApplyResources(this.u_traditionalPhoneticKeyboardLayoutComboBox, "u_traditionalPhoneticKeyboardLayoutComboBox"); this.u_traditionalPhoneticKeyboardLayoutComboBox.BackgroundImage = null; this.u_traditionalPhoneticKeyboardLayoutComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_traditionalPhoneticKeyboardLayoutComboBox.Font = null; this.u_traditionalPhoneticKeyboardLayoutComboBox.FormattingEnabled = true; this.u_traditionalPhoneticKeyboardLayoutComboBox.Items.AddRange(new object[] { resources.GetString("u_traditionalPhoneticKeyboardLayoutComboBox.Items"), resources.GetString("u_traditionalPhoneticKeyboardLayoutComboBox.Items1"), resources.GetString("u_traditionalPhoneticKeyboardLayoutComboBox.Items2")}); this.u_traditionalPhoneticKeyboardLayoutComboBox.Name = "u_traditionalPhoneticKeyboardLayoutComboBox"; this.u_traditionalPhoneticKeyboardLayoutComboBox.SelectedIndexChanged += new System.EventHandler(this.ChangeTraditionalPhoneticKeyboardLayout); // // u_traditionalPhoneticExtraSettingLabel // this.u_traditionalPhoneticExtraSettingLabel.AccessibleDescription = null; this.u_traditionalPhoneticExtraSettingLabel.AccessibleName = null; resources.ApplyResources(this.u_traditionalPhoneticExtraSettingLabel, "u_traditionalPhoneticExtraSettingLabel"); this.u_traditionalPhoneticExtraSettingLabel.Font = null; this.u_traditionalPhoneticExtraSettingLabel.Name = "u_traditionalPhoneticExtraSettingLabel"; // // u_traditionalPhoneticKeyboardLayoutLabel // this.u_traditionalPhoneticKeyboardLayoutLabel.AccessibleDescription = null; this.u_traditionalPhoneticKeyboardLayoutLabel.AccessibleName = null; resources.ApplyResources(this.u_traditionalPhoneticKeyboardLayoutLabel, "u_traditionalPhoneticKeyboardLayoutLabel"); this.u_traditionalPhoneticKeyboardLayoutLabel.Font = null; this.u_traditionalPhoneticKeyboardLayoutLabel.Name = "u_traditionalPhoneticKeyboardLayoutLabel"; // // u_traditionalPhoneticNonBig5CheckBox // this.u_traditionalPhoneticNonBig5CheckBox.AccessibleDescription = null; this.u_traditionalPhoneticNonBig5CheckBox.AccessibleName = null; resources.ApplyResources(this.u_traditionalPhoneticNonBig5CheckBox, "u_traditionalPhoneticNonBig5CheckBox"); this.u_traditionalPhoneticNonBig5CheckBox.BackgroundImage = null; this.u_traditionalPhoneticNonBig5CheckBox.Font = null; this.u_traditionalPhoneticNonBig5CheckBox.Name = "u_traditionalPhoneticNonBig5CheckBox"; this.u_traditionalPhoneticNonBig5CheckBox.UseVisualStyleBackColor = true; this.u_traditionalPhoneticNonBig5CheckBox.CheckedChanged += new System.EventHandler(this.ChangeTraditionalPhoneticUseNonBig5); // // PanelPhonetic // this.AccessibleDescription = null; this.AccessibleName = null; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; resources.ApplyResources(this, "$this"); this.BackgroundImage = null; this.Controls.Add(this.u_traditionalPhoneticGroup); this.Controls.Add(this.u_titleLabel); this.Controls.Add(this.u_smartPhoneticGroup); this.Font = null; this.Name = "PanelPhonetic"; this.u_smartPhoneticGroup.ResumeLayout(false); this.u_smartPhoneticGroup.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.u_bufferSizeNumericUpDown)).EndInit(); this.u_traditionalPhoneticGroup.ResumeLayout(false); this.u_traditionalPhoneticGroup.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox u_smartPhoneticGroup; private System.Windows.Forms.Label u_titleLabel; private System.Windows.Forms.GroupBox u_traditionalPhoneticGroup; private System.Windows.Forms.CheckBox u_smartPhoneticNonBig5CheckBox; private System.Windows.Forms.CheckBox u_traditionalPhoneticNonBig5CheckBox; private System.Windows.Forms.Label u_smartPhoneticKeyboardLayoutLabel; private System.Windows.Forms.Label u_traditionalPhoneticKeyboardLayoutLabel; private System.Windows.Forms.CheckBox u_showCandidateWithSpaceCheckBox; private System.Windows.Forms.CheckBox u_clearWithEscCheckBox; private System.Windows.Forms.Label u_smartPhoneticExtraSettinglabel; private System.Windows.Forms.Label u_smartPhoneticTypingLabel; private System.Windows.Forms.Label u_traditionalPhoneticExtraSettingLabel; private System.Windows.Forms.Label u_selectionKeyLabel; private System.Windows.Forms.ComboBox u_selectionKeyComboBox; private System.Windows.Forms.Label u_bufferSizeLabel; private System.Windows.Forms.NumericUpDown u_bufferSizeNumericUpDown; private System.Windows.Forms.Label u_bufferSizeUnitLabel; private System.Windows.Forms.Label u_buferSizeNotelabel; private System.Windows.Forms.ComboBox u_smartPhonetickeyboardLayoutComboBox; private System.Windows.Forms.ComboBox u_traditionalPhoneticKeyboardLayoutComboBox; private System.Windows.Forms.Label u_invisibleSmartLabel; private System.Windows.Forms.Label u_invisibleTraditionalLabel; } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using System.IO; using System.Linq; using Commands.Storage.ScenarioTest.Common; using Commands.Storage.ScenarioTest.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage.Blob; using MS.Test.Common.MsTestLib; using StorageTestLib; namespace Commands.Storage.ScenarioTest.Functional.Blob { /// <summary> /// functional tests for Set-ContainerAcl /// </summary> [TestClass] class GetBlobContent: TestBase { //TODO add invalid md5sum for page blob private static string downloadDirRoot; private string ContainerName = string.Empty; private string BlobName = string.Empty; private ICloudBlob Blob = null; private CloudBlobContainer Container = null; [ClassInitialize()] public static void ClassInit(TestContext testContext) { TestBase.TestClassInitialize(testContext); downloadDirRoot = Test.Data.Get("DownloadDir"); SetupDownloadDir(); } [ClassCleanup()] public static void GetBlobContentClassCleanup() { TestBase.TestClassCleanup(); } public override void OnTestSetup() { FileUtil.CleanDirectory(downloadDirRoot); } /// <summary> /// create download dir /// </summary> private static void SetupDownloadDir() { if (!Directory.Exists(downloadDirRoot)) { Directory.CreateDirectory(downloadDirRoot); } FileUtil.CleanDirectory(downloadDirRoot); } /// <summary> /// create a random container with a random blob /// </summary> private void SetupTestContainerAndBlob() { string fileName = Utility.GenNameString("download"); string filePath = Path.Combine(downloadDirRoot, fileName); int minFileSize = 1; int maxFileSize = 5; int fileSize = random.Next(minFileSize, maxFileSize); Helper.GenerateRandomTestFile(filePath, fileSize); ContainerName = Utility.GenNameString("container"); BlobName = Utility.GenNameString("blob"); CloudBlobContainer container = blobUtil.CreateContainer(ContainerName); CloudBlockBlob blockBlob = container.GetBlockBlobReference(BlobName); // Create or overwrite the "myblob" blob with contents from a local file. using (var fileStream = System.IO.File.OpenRead(filePath)) { blockBlob.UploadFromStream(fileStream); } File.Delete(filePath); blockBlob.FetchAttributes(); Blob = blockBlob; Container = container; } /// <summary> /// clean test container and blob /// </summary> private void CleanupTestContainerAndBlob() { blobUtil.RemoveContainer(ContainerName); FileUtil.CleanDirectory(downloadDirRoot); ContainerName = string.Empty; BlobName = string.Empty; Blob = null; Container = null; } /// <summary> /// get blob content by container name and blob name /// 8.15 Get-AzureStorageBlobContent positive function cases /// 3. Download an existing blob file using the container name specified by the param /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlobContent)] public void GetBlobContentByName() { SetupTestContainerAndBlob(); try { string destFileName = Utility.GenNameString("download"); string destFilePath = Path.Combine(downloadDirRoot, destFileName); Test.Assert(agent.GetAzureStorageBlobContent(BlobName, destFilePath, ContainerName, true), "download blob should be successful"); string localMd5 = Helper.GetFileContentMD5(destFilePath); Test.Assert(localMd5 == Blob.Properties.ContentMD5, string.Format("blob content md5 should be {0}, and actualy it's {1}", localMd5, Blob.Properties.ContentMD5)); } finally { CleanupTestContainerAndBlob(); } } /// <summary> /// get blob content by container pipeline /// 8.15 Get-AzureStorageBlobContent positive function cases /// 4. Download an existing blob file using the container object retrieved by Get-AzureContainer /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlobContent)] public void GetBlobContentByContainerPipeline() { SetupTestContainerAndBlob(); try { string destFileName = Utility.GenNameString("download"); string destFilePath = Path.Combine(downloadDirRoot, destFileName); ((PowerShellAgent)agent).AddPipelineScript(string.Format("Get-AzureStorageContainer {0}", ContainerName)); Test.Assert(agent.GetAzureStorageBlobContent(BlobName, destFilePath, string.Empty, true), "download blob should be successful"); string localMd5 = Helper.GetFileContentMD5(destFilePath); Test.Assert(localMd5 == Blob.Properties.ContentMD5, string.Format("blob content md5 should be {0}, and actualy it's {1}", localMd5, Blob.Properties.ContentMD5)); } finally { CleanupTestContainerAndBlob(); } } /// <summary> /// get blob content by container pipeline /// 8.15 Get-AzureStorageBlobContent positive function cases /// 5. Download a block blob file and a page blob file with a subdirectory /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlobContent)] public void GetBlobContentInSubDirectory() { string ContainerName = Utility.GenNameString("container"); FileUtil.CleanDirectory(downloadDirRoot); List<string> files = FileUtil.GenerateTempFiles(downloadDirRoot, 2); files.Sort(); CloudBlobContainer Container = blobUtil.CreateContainer(ContainerName); try { foreach (string file in files) { string filePath = Path.Combine(downloadDirRoot, file); string blobName = string.Empty; using (var fileStream = System.IO.File.OpenRead(filePath)) { blobName = file; CloudBlockBlob blockBlob = Container.GetBlockBlobReference(blobName); blockBlob.UploadFromStream(fileStream); } } List<IListBlobItem> blobLists = Container.ListBlobs(string.Empty, true, BlobListingDetails.All).ToList(); Test.Assert(blobLists.Count == files.Count, string.Format("container {0} should contain {1} blobs, and actually it contain {2} blobs", ContainerName, files.Count, blobLists.Count)); FileUtil.CleanDirectory(downloadDirRoot); ((PowerShellAgent)agent).AddPipelineScript(string.Format("Get-AzureStorageContainer {0}", ContainerName)); ((PowerShellAgent)agent).AddPipelineScript("Get-AzureStorageBlob"); Test.Assert(agent.GetAzureStorageBlobContent(string.Empty, downloadDirRoot, string.Empty, true), "download blob should be successful"); Test.Assert(agent.Output.Count == files.Count, "Get-AzureStroageBlobContent should download {0} blobs, and actully it's {1}", files.Count, agent.Output.Count); for (int i = 0, count = files.Count(); i < count; i++) { string path = Path.Combine(downloadDirRoot, files[i]); ICloudBlob blob = blobLists[i] as ICloudBlob; if (!File.Exists(path)) { Test.AssertFail(string.Format("local file '{0}' doesn't exist.", path)); } string localMd5 = Helper.GetFileContentMD5(path); string convertedName = blobUtil.ConvertBlobNameToFileName(blob.Name, string.Empty); Test.Assert(files[i] == convertedName, string.Format("converted blob name should be {0}, actually it's {1}", files[i], convertedName)); Test.Assert(localMd5 == blob.Properties.ContentMD5, string.Format("blob content md5 should be {0}, and actualy it's {1}", localMd5, blob.Properties.ContentMD5)); } } finally { FileUtil.CleanDirectory(downloadDirRoot); blobUtil.RemoveContainer(ContainerName); } } /// <summary> /// get blob content by container pipeline /// 8.15 Get-AzureStorageBlobContent positive function cases /// 6. Validate that all the blob snapshots can be downloaded /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlobContent)] public void GetBlobContentFromSnapshot() { SetupTestContainerAndBlob(); try { List<ICloudBlob> blobs = new List<ICloudBlob>(); int minSnapshot = 1; int maxSnapshot = 5; int snapshotCount = random.Next(minSnapshot, maxSnapshot); for (int i = 0; i < snapshotCount; i++) { ICloudBlob blob = ((CloudBlockBlob)Blob).CreateSnapshot(); blobs.Add(blob); } blobs.Add(Blob); List<IListBlobItem> blobLists = Container.ListBlobs(string.Empty, true, BlobListingDetails.All).ToList(); Test.Assert(blobLists.Count == blobs.Count, string.Format("container {0} should contain {1} blobs, and actually it contain {2} blobs", ContainerName, blobs.Count, blobLists.Count)); FileUtil.CleanDirectory(downloadDirRoot); ((PowerShellAgent)agent).AddPipelineScript(string.Format("Get-AzureStorageContainer {0}", ContainerName)); ((PowerShellAgent)agent).AddPipelineScript("Get-AzureStorageBlob"); Test.Assert(agent.GetAzureStorageBlobContent(string.Empty, downloadDirRoot, string.Empty, true), "download blob should be successful"); Test.Assert(agent.Output.Count == blobs.Count, "Get-AzureStroageBlobContent should download {0} blobs, and actully it's {1}", blobs.Count, agent.Output.Count); for (int i = 0, count = blobs.Count(); i < count; i++) { ICloudBlob blob = blobLists[i] as ICloudBlob; string path = Path.Combine(downloadDirRoot, blobUtil.ConvertBlobNameToFileName(blob.Name, string.Empty, blob.SnapshotTime)); Test.Assert(File.Exists(path), string.Format("local file '{0}' should exists after downloading.", path)); string localMd5 = Helper.GetFileContentMD5(path); string convertedName = blobUtil.ConvertBlobNameToFileName(blob.Name, string.Empty); Test.Assert(localMd5 == blob.Properties.ContentMD5, string.Format("blob content md5 should be {0}, and actualy it's {1}", localMd5, blob.Properties.ContentMD5)); } } finally { FileUtil.CleanDirectory(downloadDirRoot); CleanupTestContainerAndBlob(); } } /// <summary> /// download a not existing blob /// </summary> /// 8.15 Get-AzureStorageBlobContent negative function cases /// 1. Download a non-existing blob file /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlobContent)] public void GetBlobContentWithNotExistsBlob() { SetupTestContainerAndBlob(); try { string notExistingBlobName = Utility.GenNameString("notexisting"); DirectoryInfo dir = new DirectoryInfo(downloadDirRoot); int filesCountBeforeDowloading = dir.GetFiles().Count(); Test.Assert(!agent.GetAzureStorageBlobContent(notExistingBlobName, downloadDirRoot, ContainerName, true), "download not existing blob should be failed"); string expectedErrorMessage = string.Format("Can not find blob '{0}' in container '{1}'.", notExistingBlobName, ContainerName); Test.Assert(agent.ErrorMessages[0] == expectedErrorMessage, agent.ErrorMessages[0]); int filesCountAfterDowloading = dir.GetFiles().Count(); Test.Assert(filesCountBeforeDowloading == filesCountAfterDowloading, "the files count should be equal after a failed downloading"); } finally { CleanupTestContainerAndBlob(); } } /// <summary> /// download a not existing blob /// </summary> /// 8.15 Get-AzureStorageBlobContent negative function cases /// 3. Download a blob file with an invalid container name or container object /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.GetBlobContent)] public void GetBlobContentWithNotExistsContainer() { string containerName = Utility.GenNameString("notexistingcontainer"); string blobName = Utility.GenNameString("blob"); DirectoryInfo dir = new DirectoryInfo(downloadDirRoot); int filesCountBeforeDowloading = dir.GetFiles().Count(); Test.Assert(!agent.GetAzureStorageBlobContent(blobName, downloadDirRoot, containerName, true), "download blob from not existing container should be failed"); //TODO seems the error is not our expected string expectedErrorMessage = string.Format("Can not find blob '{0}' in container '{1}'.", blobName, containerName); Test.Assert(agent.ErrorMessages[0] == expectedErrorMessage, agent.ErrorMessages[0]); int filesCountAfterDowloading = dir.GetFiles().Count(); Test.Assert(filesCountBeforeDowloading == filesCountAfterDowloading, "the files count should be equal after a failed downloading"); } } }
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime { using System.Collections.Generic; using ArgumentException = System.ArgumentException; using DebuggerDisplay = System.Diagnostics.DebuggerDisplayAttribute; using Exception = System.Exception; using StringBuilder = System.Text.StringBuilder; using Type = System.Type; /** Useful for dumping out the input stream after doing some * augmentation or other manipulations. * * You can insert stuff, replace, and delete chunks. Note that the * operations are done lazily--only if you convert the buffer to a * String. This is very efficient because you are not moving data around * all the time. As the buffer of tokens is converted to strings, the * toString() method(s) check to see if there is an operation at the * current index. If so, the operation is done and then normal String * rendering continues on the buffer. This is like having multiple Turing * machine instruction streams (programs) operating on a single input tape. :) * * Since the operations are done lazily at toString-time, operations do not * screw up the token index values. That is, an insert operation at token * index i does not change the index values for tokens i+1..n-1. * * Because operations never actually alter the buffer, you may always get * the original token stream back without undoing anything. Since * the instructions are queued up, you can easily simulate transactions and * roll back any changes if there is an error just by removing instructions. * For example, * * CharStream input = new ANTLRFileStream("input"); * TLexer lex = new TLexer(input); * TokenRewriteStream tokens = new TokenRewriteStream(lex); * T parser = new T(tokens); * parser.startRule(); * * Then in the rules, you can execute * Token t,u; * ... * input.insertAfter(t, "text to put after t");} * input.insertAfter(u, "text after u");} * System.out.println(tokens.toString()); * * Actually, you have to cast the 'input' to a TokenRewriteStream. :( * * You can also have multiple "instruction streams" and get multiple * rewrites from a single pass over the input. Just name the instruction * streams and use that name again when printing the buffer. This could be * useful for generating a C file and also its header file--all from the * same buffer: * * tokens.insertAfter("pass1", t, "text to put after t");} * tokens.insertAfter("pass2", u, "text after u");} * System.out.println(tokens.toString("pass1")); * System.out.println(tokens.toString("pass2")); * * If you don't use named rewrite streams, a "default" stream is used as * the first example shows. */ [System.Serializable] [DebuggerDisplay("TODO: TokenRewriteStream debugger display")] public class TokenRewriteStream : CommonTokenStream { public const string DEFAULT_PROGRAM_NAME = "default"; public const int PROGRAM_INIT_SIZE = 100; public const int MIN_TOKEN_INDEX = 0; // Define the rewrite operation hierarchy protected class RewriteOperation { /** <summary>What index into rewrites List are we?</summary> */ public int instructionIndex; /** <summary>Token buffer index.</summary> */ public int index; public object text; // outer protected TokenRewriteStream stream; protected RewriteOperation(TokenRewriteStream stream, int index, object text) { this.index = index; this.text = text; this.stream = stream; } /** <summary> * Execute the rewrite operation by possibly adding to the buffer. * Return the index of the next token to operate on. * </summary> */ public virtual int Execute(StringBuilder buf) { return index; } public override string ToString() { string opName = this.GetType().Name; int index = opName.IndexOf('$'); opName = opName.Substring(index + 1); return "<" + opName + "@" + this.index + ":\"" + text + "\">"; } } class InsertBeforeOp : RewriteOperation { public InsertBeforeOp(TokenRewriteStream stream, int index, object text) : base(stream, index, text) { } public override int Execute(StringBuilder buf) { buf.Append(text); if (stream._tokens[index].Type != CharStreamConstants.EndOfFile) buf.Append(stream._tokens[index].Text); return index + 1; } } /** <summary> * I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp * instructions. * </summary> */ class ReplaceOp : RewriteOperation { public int lastIndex; public ReplaceOp(TokenRewriteStream stream, int from, int to, object text) : base(stream, from, text) { lastIndex = to; } public override int Execute(StringBuilder buf) { if (text != null) { buf.Append(text); } return lastIndex + 1; } public override string ToString() { return "<ReplaceOp@" + index + ".." + lastIndex + ":\"" + text + "\">"; } } class DeleteOp : ReplaceOp { public DeleteOp(TokenRewriteStream stream, int from, int to) : base(stream, from, to, null) { } public override string ToString() { return "<DeleteOp@" + index + ".." + lastIndex + ">"; } } /** <summary> * You may have multiple, named streams of rewrite operations. * I'm calling these things "programs." * Maps String (name) -> rewrite (List) * </summary> */ protected IDictionary<string, IList<RewriteOperation>> programs = null; /** <summary>Map String (program name) -> Integer index</summary> */ protected IDictionary<string, int> lastRewriteTokenIndexes = null; public TokenRewriteStream() { Init(); } protected void Init() { programs = new Dictionary<string, IList<RewriteOperation>>(); programs[DEFAULT_PROGRAM_NAME] = new List<RewriteOperation>(PROGRAM_INIT_SIZE); lastRewriteTokenIndexes = new Dictionary<string, int>(); } public TokenRewriteStream(ITokenSource tokenSource) : base(tokenSource) { Init(); } public TokenRewriteStream(ITokenSource tokenSource, int channel) : base(tokenSource, channel) { Init(); } public virtual void Rollback(int instructionIndex) { Rollback(DEFAULT_PROGRAM_NAME, instructionIndex); } /** <summary> * Rollback the instruction stream for a program so that * the indicated instruction (via instructionIndex) is no * longer in the stream. UNTESTED! * </summary> */ public virtual void Rollback(string programName, int instructionIndex) { IList<RewriteOperation> @is; if (programs.TryGetValue(programName, out @is) && @is != null) { List<RewriteOperation> sublist = new List<RewriteOperation>(); for (int i = MIN_TOKEN_INDEX; i <= instructionIndex; i++) sublist.Add(@is[i]); programs[programName] = sublist; } } public virtual void DeleteProgram() { DeleteProgram(DEFAULT_PROGRAM_NAME); } /** <summary>Reset the program so that no instructions exist</summary> */ public virtual void DeleteProgram(string programName) { Rollback(programName, MIN_TOKEN_INDEX); } public virtual void InsertAfter(IToken t, object text) { InsertAfter(DEFAULT_PROGRAM_NAME, t, text); } public virtual void InsertAfter(int index, object text) { InsertAfter(DEFAULT_PROGRAM_NAME, index, text); } public virtual void InsertAfter(string programName, IToken t, object text) { InsertAfter(programName, t.TokenIndex, text); } public virtual void InsertAfter(string programName, int index, object text) { // to insert after, just insert before next index (even if past end) InsertBefore(programName, index + 1, text); //addToSortedRewriteList(programName, new InsertAfterOp(index,text)); } public virtual void InsertBefore(IToken t, object text) { InsertBefore(DEFAULT_PROGRAM_NAME, t, text); } public virtual void InsertBefore(int index, object text) { InsertBefore(DEFAULT_PROGRAM_NAME, index, text); } public virtual void InsertBefore(string programName, IToken t, object text) { InsertBefore(programName, t.TokenIndex, text); } public virtual void InsertBefore(string programName, int index, object text) { //addToSortedRewriteList(programName, new InsertBeforeOp(index,text)); RewriteOperation op = new InsertBeforeOp(this, index, text); IList<RewriteOperation> rewrites = GetProgram(programName); op.instructionIndex = rewrites.Count; rewrites.Add(op); } public virtual void Replace(int index, object text) { Replace(DEFAULT_PROGRAM_NAME, index, index, text); } public virtual void Replace(int from, int to, object text) { Replace(DEFAULT_PROGRAM_NAME, from, to, text); } public virtual void Replace(IToken indexT, object text) { Replace(DEFAULT_PROGRAM_NAME, indexT, indexT, text); } public virtual void Replace(IToken from, IToken to, object text) { Replace(DEFAULT_PROGRAM_NAME, from, to, text); } public virtual void Replace(string programName, int from, int to, object text) { if (from > to || from < 0 || to < 0 || to >= _tokens.Count) { throw new ArgumentException("replace: range invalid: " + from + ".." + to + "(size=" + _tokens.Count + ")"); } RewriteOperation op = new ReplaceOp(this, from, to, text); IList<RewriteOperation> rewrites = GetProgram(programName); op.instructionIndex = rewrites.Count; rewrites.Add(op); } public virtual void Replace(string programName, IToken from, IToken to, object text) { Replace(programName, from.TokenIndex, to.TokenIndex, text); } public virtual void Delete(int index) { Delete(DEFAULT_PROGRAM_NAME, index, index); } public virtual void Delete(int from, int to) { Delete(DEFAULT_PROGRAM_NAME, from, to); } public virtual void Delete(IToken indexT) { Delete(DEFAULT_PROGRAM_NAME, indexT, indexT); } public virtual void Delete(IToken from, IToken to) { Delete(DEFAULT_PROGRAM_NAME, from, to); } public virtual void Delete(string programName, int from, int to) { Replace(programName, from, to, null); } public virtual void Delete(string programName, IToken from, IToken to) { Replace(programName, from, to, null); } public virtual int GetLastRewriteTokenIndex() { return GetLastRewriteTokenIndex(DEFAULT_PROGRAM_NAME); } protected virtual int GetLastRewriteTokenIndex(string programName) { int value; if (lastRewriteTokenIndexes.TryGetValue(programName, out value)) return value; return -1; } protected virtual void SetLastRewriteTokenIndex(string programName, int i) { lastRewriteTokenIndexes[programName] = i; } protected virtual IList<RewriteOperation> GetProgram(string name) { IList<RewriteOperation> @is; if (!programs.TryGetValue(name, out @is) || @is == null) { @is = InitializeProgram(name); } return @is; } private IList<RewriteOperation> InitializeProgram(string name) { IList<RewriteOperation> @is = new List<RewriteOperation>(PROGRAM_INIT_SIZE); programs[name] = @is; return @is; } public virtual string ToOriginalString() { Fill(); return ToOriginalString(MIN_TOKEN_INDEX, Count - 1); } public virtual string ToOriginalString(int start, int end) { StringBuilder buf = new StringBuilder(); for (int i = start; i >= MIN_TOKEN_INDEX && i <= end && i < _tokens.Count; i++) { if (Get(i).Type != CharStreamConstants.EndOfFile) buf.Append(Get(i).Text); } return buf.ToString(); } public override string ToString() { Fill(); return ToString(MIN_TOKEN_INDEX, Count - 1); } public virtual string ToString(string programName) { Fill(); return ToString(programName, MIN_TOKEN_INDEX, Count - 1); } public override string ToString(int start, int end) { return ToString(DEFAULT_PROGRAM_NAME, start, end); } public virtual string ToString(string programName, int start, int end) { IList<RewriteOperation> rewrites; if (!programs.TryGetValue(programName, out rewrites)) rewrites = null; // ensure start/end are in range if (end > _tokens.Count - 1) end = _tokens.Count - 1; if (start < 0) start = 0; if (rewrites == null || rewrites.Count == 0) { return ToOriginalString(start, end); // no instructions to execute } StringBuilder buf = new StringBuilder(); // First, optimize instruction stream IDictionary<int, RewriteOperation> indexToOp = ReduceToSingleOperationPerIndex(rewrites); // Walk buffer, executing instructions and emitting tokens int i = start; while (i <= end && i < _tokens.Count) { RewriteOperation op; bool exists = indexToOp.TryGetValue(i, out op); if (exists) { // remove so any left have index size-1 indexToOp.Remove(i); } if (!exists || op == null) { IToken t = _tokens[i]; // no operation at that index, just dump token if (t.Type != CharStreamConstants.EndOfFile) buf.Append(t.Text); i++; // move to next token } else { i = op.Execute(buf); // execute operation and skip } } // include stuff after end if it's last index in buffer // So, if they did an insertAfter(lastValidIndex, "foo"), include // foo if end==lastValidIndex. if (end == _tokens.Count - 1) { // Scan any remaining operations after last token // should be included (they will be inserts). foreach (RewriteOperation op in indexToOp.Values) { if (op.index >= _tokens.Count - 1) buf.Append(op.text); } } return buf.ToString(); } /** We need to combine operations and report invalid operations (like * overlapping replaces that are not completed nested). Inserts to * same index need to be combined etc... Here are the cases: * * I.i.u I.j.v leave alone, nonoverlapping * I.i.u I.i.v combine: Iivu * * R.i-j.u R.x-y.v | i-j in x-y delete first R * R.i-j.u R.i-j.v delete first R * R.i-j.u R.x-y.v | x-y in i-j ERROR * R.i-j.u R.x-y.v | boundaries overlap ERROR * * I.i.u R.x-y.v | i in x-y delete I * I.i.u R.x-y.v | i not in x-y leave alone, nonoverlapping * R.x-y.v I.i.u | i in x-y ERROR * R.x-y.v I.x.u R.x-y.uv (combine, delete I) * R.x-y.v I.i.u | i not in x-y leave alone, nonoverlapping * * I.i.u = insert u before op @ index i * R.x-y.u = replace x-y indexed tokens with u * * First we need to examine replaces. For any replace op: * * 1. wipe out any insertions before op within that range. * 2. Drop any replace op before that is contained completely within * that range. * 3. Throw exception upon boundary overlap with any previous replace. * * Then we can deal with inserts: * * 1. for any inserts to same index, combine even if not adjacent. * 2. for any prior replace with same left boundary, combine this * insert with replace and delete this replace. * 3. throw exception if index in same range as previous replace * * Don't actually delete; make op null in list. Easier to walk list. * Later we can throw as we add to index -> op map. * * Note that I.2 R.2-2 will wipe out I.2 even though, technically, the * inserted stuff would be before the replace range. But, if you * add tokens in front of a method body '{' and then delete the method * body, I think the stuff before the '{' you added should disappear too. * * Return a map from token index to operation. */ protected virtual IDictionary<int, RewriteOperation> ReduceToSingleOperationPerIndex(IList<RewriteOperation> rewrites) { //System.out.println("rewrites="+rewrites); // WALK REPLACES for (int i = 0; i < rewrites.Count; i++) { RewriteOperation op = rewrites[i]; if (op == null) continue; if (!(op is ReplaceOp)) continue; ReplaceOp rop = (ReplaceOp)rewrites[i]; // Wipe prior inserts within range var inserts = GetKindOfOps(rewrites, typeof(InsertBeforeOp), i); for (int j = 0; j < inserts.Count; j++) { InsertBeforeOp iop = (InsertBeforeOp)inserts[j]; if (iop.index >= rop.index && iop.index <= rop.lastIndex) { // delete insert as it's a no-op. rewrites[iop.instructionIndex] = null; } } // Drop any prior replaces contained within var prevReplaces = GetKindOfOps(rewrites, typeof(ReplaceOp), i); for (int j = 0; j < prevReplaces.Count; j++) { ReplaceOp prevRop = (ReplaceOp)prevReplaces[j]; if (prevRop.index >= rop.index && prevRop.lastIndex <= rop.lastIndex) { // delete replace as it's a no-op. rewrites[prevRop.instructionIndex] = null; continue; } // throw exception unless disjoint or identical bool disjoint = prevRop.lastIndex < rop.index || prevRop.index > rop.lastIndex; bool same = prevRop.index == rop.index && prevRop.lastIndex == rop.lastIndex; if (!disjoint && !same) { throw new ArgumentException("replace op boundaries of " + rop + " overlap with previous " + prevRop); } } } // WALK INSERTS for (int i = 0; i < rewrites.Count; i++) { RewriteOperation op = (RewriteOperation)rewrites[i]; if (op == null) continue; if (!(op is InsertBeforeOp)) continue; InsertBeforeOp iop = (InsertBeforeOp)rewrites[i]; // combine current insert with prior if any at same index var prevInserts = GetKindOfOps(rewrites, typeof(InsertBeforeOp), i); for (int j = 0; j < prevInserts.Count; j++) { InsertBeforeOp prevIop = (InsertBeforeOp)prevInserts[j]; if (prevIop.index == iop.index) { // combine objects // convert to strings...we're in process of toString'ing // whole token buffer so no lazy eval issue with any templates iop.text = CatOpText(iop.text, prevIop.text); // delete redundant prior insert rewrites[prevIop.instructionIndex] = null; } } // look for replaces where iop.index is in range; error var prevReplaces = GetKindOfOps(rewrites, typeof(ReplaceOp), i); for (int j = 0; j < prevReplaces.Count; j++) { ReplaceOp rop = (ReplaceOp)prevReplaces[j]; if (iop.index == rop.index) { rop.text = CatOpText(iop.text, rop.text); rewrites[i] = null; // delete current insert continue; } if (iop.index >= rop.index && iop.index <= rop.lastIndex) { throw new ArgumentException("insert op " + iop + " within boundaries of previous " + rop); } } } // System.out.println("rewrites after="+rewrites); IDictionary<int, RewriteOperation> m = new Dictionary<int, RewriteOperation>(); for (int i = 0; i < rewrites.Count; i++) { RewriteOperation op = (RewriteOperation)rewrites[i]; if (op == null) continue; // ignore deleted ops RewriteOperation existing; if (m.TryGetValue(op.index, out existing) && existing != null) { throw new Exception("should only be one op per index"); } m[op.index] = op; } //System.out.println("index to op: "+m); return m; } protected virtual string CatOpText(object a, object b) { return string.Concat(a, b); } protected virtual IList<RewriteOperation> GetKindOfOps(IList<RewriteOperation> rewrites, Type kind) { return GetKindOfOps(rewrites, kind, rewrites.Count); } /** <summary>Get all operations before an index of a particular kind</summary> */ protected virtual IList<RewriteOperation> GetKindOfOps(IList<RewriteOperation> rewrites, Type kind, int before) { IList<RewriteOperation> ops = new List<RewriteOperation>(); for (int i = 0; i < before && i < rewrites.Count; i++) { RewriteOperation op = rewrites[i]; if (op == null) continue; // ignore deleted if (op.GetType() == kind) ops.Add(op); } return ops; } public virtual string ToDebugString() { return ToDebugString(MIN_TOKEN_INDEX, Count - 1); } public virtual string ToDebugString(int start, int end) { StringBuilder buf = new StringBuilder(); for (int i = start; i >= MIN_TOKEN_INDEX && i <= end && i < _tokens.Count; i++) { buf.Append(Get(i)); } return buf.ToString(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace TripCalculator.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
/* Josip Medved <jmedved@jmedved.com> * www.medo64.com * MIT License */ //2021-11-25: Refactored to use pattern matching //2021-09-28: Added constructor for empty instance //2021-09-26: Initial version namespace Medo.Configuration; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; /// <summary> /// Provides read-only access for to a configuration file. /// File should follow Microsoft's INI file format but other variations are supported too. /// </summary> /// <example> /// <code> /// var ini = new IniFile("Test.ini"); /// var value = ini.Read("Section", "Key"); /// </code> /// </example> public class IniFile { /// <summary> /// Creates a new empty instance. /// </summary> public IniFile() { ParserObject = new Parser(""); } /// <summary> /// Creates a new instance. /// </summary> /// <param name="path">File path.</param> /// <exception cref="ArgumentNullException">File path cannot be null.</exception> /// <exception cref="FileNotFoundException">File not found.</exception> public IniFile(string path) : this(File.OpenRead(path ?? throw new ArgumentNullException(nameof(path), "File path cannot be null."))) { } /// <summary> /// Creates a new instance. /// </summary> /// <param name="stream">Stream.</param> /// <exception cref="ArgumentNullException">Stream cannot be null.</exception> public IniFile(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream), "Stream cannot be null."); } using var reader = new StreamReader(stream, Encoding.UTF8); ParserObject = new Parser(reader.ReadToEnd()); // just read the whole darn thing } #region Read /// <summary> /// Returns all the values for the specified key. /// </summary> /// <param name="section">Section name.</param> /// <param name="key">Key name.</param> /// <exception cref="ArgumentNullException">Section cannot be null. -or- Key cannot be null.</exception> public IReadOnlyList<string> ReadAll(string section, string key) { if (section == null) { throw new ArgumentNullException(nameof(section), "Section cannot be null."); } if (key == null) { throw new ArgumentNullException(nameof(key), "Key cannot be null."); } return ParserObject.GetValue(section, key); } /// <summary> /// Returns the value for the specified section and key or null if value is not found. /// </summary> /// <param name="section">Section name.</param> /// <param name="key">Key name.</param> /// <exception cref="ArgumentNullException">Section cannot be null. -or- Key cannot be null.</exception> public string? Read(string section, string key) { var results = ReadAll(section, key); return (results.Count > 0) ? results[^1] : null; } /// <summary> /// Returns string value for the specified key. /// </summary> /// <param name="section">Section name.</param> /// <param name="key">Key name.</param> /// <param name="defaultValue">The value to return if the entry does not exist.</param> /// <exception cref="ArgumentNullException">Section cannot be null. -or- Key cannot be null. -or- Default value cannot be null.</exception> public string Read(string section, string key, string defaultValue) { if (defaultValue == null) { throw new ArgumentNullException(nameof(defaultValue), "Default value cannot be null."); } return Read(section, key) ?? defaultValue; } /// <summary> /// Returns boolean value for the specified key. /// </summary> /// <param name="section">Section name.</param> /// <param name="key">Key name.</param> /// <param name="defaultValue">The value to return if the entry does not exist or cannot be converted.</param> /// <exception cref="ArgumentNullException">Section cannot be null. -or- Key cannot be null.</exception> public bool Read(string section, string key, bool defaultValue) { return GetValue(Read(section, key), defaultValue); } /// <summary> /// Returns integer value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="section">Section name.</param> /// <param name="key">Key name.</param> /// <param name="defaultValue">The value to return if the entry does not exist or cannot be converted.</param> /// <exception cref="ArgumentNullException">Section cannot be null. -or- Key cannot be null.</exception> public int Read(string section, string key, int defaultValue) { return GetValue(Read(section, key), defaultValue); } /// <summary> /// Returns integer value for the specified key. /// </summary> /// <param name="section">Section name.</param> /// <param name="key">Key name.</param> /// <param name="defaultValue">The value to return if the entry does not exist or cannot be converted.</param> /// <exception cref="ArgumentNullException">Section cannot be null. -or- Key cannot be null.</exception> public long Read(string section, string key, long defaultValue) { return GetValue(Read(section, key), defaultValue); } /// <summary> /// Returns floating point value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="section">Section name.</param> /// <param name="key">Key name.</param> /// <param name="defaultValue">The value to return if the entry does not exist or cannot be converted.</param> /// <exception cref="ArgumentNullException">Section cannot be null. -or- Key cannot be null.</exception> public float Read(string section, string key, float defaultValue) { return GetValue(Read(section, key), defaultValue); } /// <summary> /// Returns floating point value for the specified key. /// </summary> /// <param name="key">Key.</param> /// <param name="section">Section name.</param> /// <param name="key">Key name.</param> /// <param name="defaultValue">The value to return if the entry does not exist or cannot be converted.</param> public double Read(string section, string key, double defaultValue) { return GetValue(Read(section, key), defaultValue); } #endregion Read #region Parsing private readonly Parser ParserObject; private class Parser { internal Parser(string text) { Text = text; } private readonly string Text; private enum State { Normal, Single, Double, Done } private readonly object SyncParse = new(); private Dictionary<string, Dictionary<string, List<string>>>? CachedResult; private int CachedResultCount; private Dictionary<string, Dictionary<string, List<string>>> Parse() { // key without name is a section lock (SyncParse) { if (CachedResult == null) { var rawEntries = new List<(string section, string key, string value)>(); var nonEmptyLines = Text.Split(new String[] { "\r\n", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); var lines = new List<string>(); foreach (var line in nonEmptyLines) { var trimmedLine = line.Trim(); if (trimmedLine.Length == 0) { continue; } // ignore empty lines if (line.StartsWith('#')) { continue; } // ignore full comment lines lines.Add(trimmedLine); } var lastSection = ""; foreach (var line in lines) { if (line.StartsWith('[')) { // this is a section if (line.EndsWith(']')) { lastSection = line[1..^1].Trim(); } else { // if no end bracket, just take it all in lastSection = line[1..].Trim(); } } else { // key value var parts = line.Split(new char[] { ':', '=' }, 2); if (parts.Length == 2) { // ignore lines that don't have both key and value var key = parts[0]?.Trim() ?? ""; if (!key.Contains('#')) { // make sure comment doesn't start in key var valueChars = new Queue<char>(parts[1]); valueChars.Enqueue('\n'); // add new line to make parsing easier var state = State.Normal; var valueParts = new List<(string Text, bool Trimmable)>(); var valueText = new StringBuilder(); while (valueChars.Count > 0) { var ch = valueChars.Dequeue(); switch (state) { case State.Normal: if (ch is '\n') { // done with parsing if (valueText.Length > 0) { // just add trimmable text if there's any valueParts.Add((valueText.ToString(), Trimmable: true)); valueText.Length = 0; } } else if (ch is '#' or ';') { // comment if (valueText.Length > 0) { // just add trimmable text if there's any valueParts.Add((valueText.ToString(), Trimmable: true)); valueText.Length = 0; } state = State.Done; } else if (ch is '\'') { // single quote if (valueText.Length > 0) { // just add trimmable text if there's any valueParts.Add((valueText.ToString(), Trimmable: true)); valueText.Length = 0; } state = State.Single; } else if (ch is '"') { // double quote if (valueText.Length > 0) { // just add trimmable text if there's any valueParts.Add((valueText.ToString(), Trimmable: true)); valueText.Length = 0; } state = State.Double; } else { // any other valid character valueText.Append(ch); } break; case State.Single: if (ch is '\n') { // done with parsing valueParts.Add((valueText.ToString(), Trimmable: false)); // just add whatever you have } else if (ch is '\'') { if (valueChars.Peek() == '\'') { // double apostrophe valueChars.Dequeue(); valueText.Append('\''); } else { valueParts.Add((valueText.ToString(), Trimmable: false)); // add to list valueText.Length = 0; state = State.Normal; } } else { valueText.Append(ch); } break; case State.Double: if (ch is '\n') { // done with parsing valueParts.Add((valueText.ToString(), Trimmable: false)); // just add whatever you have } else if (ch is '"') { valueParts.Add((valueText.ToString(), Trimmable: false)); // add to list valueText.Length = 0; state = State.Normal; } else if (ch is '\\') { ch = valueChars.Dequeue(); // get next char switch (ch) { case '\n': break; // ignore escape case '0': valueText.Append('\0'); break; case 'a': valueText.Append('\a'); break; case 'b': valueText.Append('\b'); break; case 'f': valueText.Append('\f'); break; case 'n': valueText.Append('\n'); break; case 'r': valueText.Append('\r'); break; case 't': valueText.Append('\t'); break; case 'v': valueText.Append('\v'); break; case 'u': if (valueChars.Count <= 4) { //not enough characters, abandon parse valueChars.Clear(); valueChars.Enqueue('\n'); // return end-of-line so that it can be catched in next loop iteration } else { var number = 0; for (var i = 0; i < 4; i++) { if (number == -1) { continue; } // just consume var nextChar = valueChars.Dequeue(); if (int.TryParse(nextChar.ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var parsedHex)) { number = (number << 4) | parsedHex; } else { number = -1; // abandon parse } } if (number >= 0) { // don't add if not fully parsed valueText.Append(char.ConvertFromUtf32(number)); } } break; case 'U': if (valueChars.Count <= 8) { //not enough characters, abandon parse valueChars.Clear(); valueChars.Enqueue('\n'); // return end-of-line so that it can be catched in next loop iteration } else { var number = 0; for (var i = 0; i < 8; i++) { if (number == -1) { continue; } // just consume var nextChar = valueChars.Dequeue(); if (int.TryParse(nextChar.ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var parsedHex)) { number = (number << 4) | parsedHex; } else { number = -1; // abandon parse } } if (number is >= 0 and <= 0x00FFFFFF) { // don't add if not fully parsed valueText.Append(char.ConvertFromUtf32(number)); } } break; case 'x': if (valueChars.Count > 1) { //only parse if we have more than 1 character (i.e. more than new-line) var number = 0; for (var i = 0; i < 4; i++) { var nextChar = valueChars.Peek(); if (int.TryParse(nextChar.ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var parsedHex)) { valueChars.Dequeue(); number = (number << 4) | parsedHex; } else { if (i == 0) { valueChars.Dequeue(); number = -1; } // even in the case of errors, consume at least one character break; } } if (number >= 0) { // don't add if not fully parsed valueText.Append(char.ConvertFromUtf32(number)); } } break; default: valueText.Append(ch); break; } } else { valueText.Append(ch); } break; case State.Done: break; } } var composedValue = new StringBuilder(); for (var i = 0; i < valueParts.Count; i++) { var part = valueParts[i]; var text = part.Text; if ((valueParts.Count == 1) && (part.Trimmable)) { composedValue.Append(text.Trim()); } else if ((i == 0) && (part.Trimmable)) { composedValue.Append(text.TrimStart()); } else if ((i == valueParts.Count - 1) && (part.Trimmable)) { composedValue.Append(text.TrimEnd()); } else { composedValue.Append(text); } } rawEntries.Add((lastSection, key, composedValue.ToString())); } } } } var newResult = new Dictionary<string, Dictionary<string, List<string>>>(StringComparer.InvariantCultureIgnoreCase); foreach (var (section, key, value) in rawEntries) { if (!newResult.TryGetValue(section, out var perSectionEntries)) { perSectionEntries = new Dictionary<string, List<string>>(StringComparer.InvariantCultureIgnoreCase); newResult.Add(section, perSectionEntries); } if (!perSectionEntries.TryGetValue(key, out var perKeyEntries)) { perKeyEntries = new List<string>(); perSectionEntries.Add(key, perKeyEntries); } perKeyEntries.Add(value); } CachedResult = newResult; CachedResultCount = rawEntries.Count; } return CachedResult; } } private static (string section, string key, string value) ParseRawEntry(StringBuilder sbSection, StringBuilder sbKey, StringBuilder? sbValue) { // just a helper var section = sbSection.ToString(); var key = sbKey.ToString(); var value = sbValue?.ToString() ?? ""; sbKey.Clear(); if (sbValue != null) { sbValue.Clear(); } return (section, key, value); } private static StringBuilder TrimEnd(StringBuilder sb) { var outputLen = sb.Length; for (var i = sb.Length - 1; i >= 0; i--) { if (!char.IsWhiteSpace(sb[i])) { break; } outputLen = i; } sb.Length = outputLen; return sb; // just return it for call chaining } internal IReadOnlyList<string> GetSections() { var perSectionDict = Parse(); return new List<string>(perSectionDict.Keys).AsReadOnly(); } internal IReadOnlyList<string> GetKeys(string section) { var perSectionDict = Parse(); if (perSectionDict.TryGetValue(section, out var perKeyDict)) { return new List<string>(perKeyDict.Keys).AsReadOnly(); } return Array.Empty<string>(); } internal IReadOnlyList<string> GetValue(string section, string key) { var perSectionDict = Parse(); if (perSectionDict.TryGetValue(section, out var perKeyDict)) { if (perKeyDict.TryGetValue(key, out var valueList)) { return valueList.AsReadOnly(); } } return Array.Empty<string>(); } internal int GetCount() { var _ = Parse(); return CachedResultCount; } } #endregion Parsing #region Sections/Keys /// <summary> /// Returns all sections that have keys. /// </summary> /// <returns></returns> public IReadOnlyList<string> GetSections() { return ParserObject.GetSections(); } /// <summary> /// Returns all keys in given section. /// </summary> /// <param name="section">Section name.</param> /// <exception cref="ArgumentNullException">Section cannot be null.</exception> public IReadOnlyList<string> GetKeys(string section) { if (section == null) { throw new ArgumentNullException(nameof(section), "Section cannot be null."); } return ParserObject.GetKeys(section); } /// <summary> /// Gets number of properties present. /// </summary> public int Count { get { return ParserObject.GetCount(); } } #endregion Sections/Keys #region Convert /// <summary> /// Returns value if non-empty or default value otherwise. /// </summary> /// <param name="value">Value.</param> /// <param name="defaultValue">Default value.</param> /// <exception cref="ArgumentNullException">Default value cannot be null.</exception> internal static string GetValue(string? value, string defaultValue) { if (defaultValue == null) { throw new ArgumentNullException(nameof(defaultValue), "Default value cannot be null."); } return value is not null ? value : defaultValue; } /// <summary> /// Returns boolean value if non-empty or default value if it cannot be converted. /// </summary> /// <param name="value">Value.</param> /// <param name="defaultValue">Default value.</param> internal static bool GetValue(string? value, bool defaultValue) { if (value == null) { return defaultValue; } if (bool.TryParse(value, out var result)) { return result; } else if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var resultInt)) { return (resultInt != 0); } else { return defaultValue; } } /// <summary> /// Returns integer value if non-empty or default value if it cannot be converted. /// </summary> /// <param name="value">Value.</param> /// <param name="defaultValue">Default value.</param> internal static int GetValue(string? value, int defaultValue) { if (value == null) { return defaultValue; } if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } else { return defaultValue; } } /// <summary> /// Returns integer value if non-empty or default value if it cannot be converted. /// </summary> /// <param name="value">Value.</param> /// <param name="defaultValue">Default value.</param> internal static long GetValue(string? value, long defaultValue) { if (value == null) { return defaultValue; } if (long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } else { return defaultValue; } } /// <summary> /// Returns floating point value if non-empty or default value if it cannot be converted. /// </summary> /// <param name="value">Value.</param> /// <param name="defaultValue">Default value.</param> internal static float GetValue(string? value, float defaultValue) { if (value == null) { return defaultValue; } if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return result; } else { return defaultValue; } } /// <summary> /// Returns floating point value if non-empty or default value if it cannot be converted. /// </summary> /// <param name="value">Value.</param> /// <param name="defaultValue">Default value.</param> internal static double GetValue(string? value, double defaultValue) { if (value == null) { return defaultValue; } if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return result; } else { return defaultValue; } } #endregion }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlTypes; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Xml; //using LearningRegistryCache2.App_Code.Classes; using LearningRegistryCache2.App_Code.Classes; using Isle.BizServices; using OLDDM = LearningRegistryCache2.App_Code.DataManagers; using LRWarehouse.Business; using LR_Import; using Newtonsoft.Json; namespace LearningRegistryCache2 { public class MetadataController : BaseDataController { protected AuditReportingServices reportingManager = new AuditReportingServices(); public MetadataController() { } protected Resource LoadCommonMetadata(string docId, ref string url, string payloadPlacement, XmlDocument xdoc, XmlDocument xpayload, ref bool isValid) { url = FixPlusesInUrl(url); Resource resource = new Resource(); isValid = true; XmlNodeList list = null; string submitterName; string payload = ""; list = xdoc.GetElementsByTagName("submitter"); if (list.Count == 0) { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, docId, url, ErrorType.Error, ErrorRouting.Technical, "Submitter not found. Substituting 'Unknown'."); submitterName = "Unknown"; } else { submitterName = TrimWhitespace(list[0].InnerText); } //Resource oldResource = versionManager.GetByResourceUrlAndSubmitter(url, submitterName); //string searchUrl = url.Replace("'", "''"); Resource oldResource = new ResourceVersionController().GetActiveVersionByResourceUrl(url); if (oldResource != null && oldResource.RowId.ToString() != ImportServices.DEFAULT_GUID) { resource = oldResource; // TODO: When files from 11/4/2015 thru 2/26/2016 have been reprocessed, remove the next two lines. resource.IsActive = true; importManager.UpdateResource(resource); // End TODO block ResourceVersion version = CopyOldToNewResourceVersion(resource.Version); importManager.VersionSetActiveState(false, resource.Version.Id); resource.Version = version; resource.Version.ResourceIntId = resource.Id; resource.Version.LRDocId = docId; resource.Version.Submitter = submitterName; //isOldVersion = true; LearningRegistry.deleteResourceIdList += string.Format("{0},", resource.Id); } else { //Get resource, if it exists, otherwise create it string status = "successful"; oldResource = importManager.GetByResourceUrl(url, ref status); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, docId, url, ErrorType.Error, ErrorRouting.Technical, status); } if (oldResource == null || oldResource.RowId.ToString() == ImportServices.DEFAULT_GUID) { status = "successful"; resource.ResourceUrl = url; resource.FavoriteCount = 0; resource.ViewCount = 0; importManager.CreateResource(resource, ref status); resource.Version.ResourceIntId = resource.Id; resource.Version.Submitter = submitterName; //isOldVersion = false; } else { resource = oldResource; resource.Version.Submitter = submitterName; resource.Version.ResourceIntId = resource.Id; //isOldVersion = false; } resource.ResourceUrl = url; resource.Version.LRDocId = docId; } if (payloadPlacement == "inline") { list = xdoc.GetElementsByTagName("resource_data"); if (list[0].InnerXml.IndexOf("<resource_data>") > -1) { Regex resourceDataNodeEx = new Regex(@"<resource_data>([\s\S]*)</resource_data>"); payload = resourceDataNodeEx.Match(list[0].InnerXml).Value; //payload = payload.Replace("<resource_data>", ""); //payload = payload.Replace("</resource_data>", ""); payload = payload.Replace("&lt;", "<").Replace("&gt;", ">"); payload = payload.Replace(">>", ">"); payload = payload.Replace("\\\"", "\""); } else { payload = list[0].OuterXml.Replace("&lt;", "<").Replace("&gt;", ">"); payload = payload.Replace(">>", ">"); payload = payload.Replace("\\\"", "\""); } // Can't have this with any whitespace in front of it. Some LR records have this with whitespace in front of it, or with other tags preceeding it. payload = payload.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>",""); //xpayload = new XmlDocument(); try { xpayload.LoadXml(payload); // check to see if <resource_data> contains json. If so, convert the JSON to xml and load again. list = xpayload.GetElementsByTagName("resource_data"); if (list != null) { string xmlJson = list[0].InnerXml; if (xmlJson.Substring(0, 1) == "{" || xmlJson.Substring(0, 1) == "[") { // contains json, so do conversion XmlDocument xd = new XmlDocument(); xd = JsonConvert.DeserializeXmlNode(xmlJson, "root"); string newXml = xd.GetElementsByTagName("root")[0].InnerXml.ToString(); payload = payload.Replace(xmlJson, newXml); //xpayload = new XmlDocument(); xpayload.LoadXml(payload); } } } catch (Exception ex) { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, docId, url, ErrorType.Error, ErrorRouting.Technical, ex.ToString()); isValid = false; } list = xdoc.GetElementsByTagName("node_timestamp"); foreach (XmlNode node in list) { string strDate = TrimWhitespace(node.InnerText); resource.Version.Modified = importManager.ConvertLRTimeToDateTime(strDate); break; } list = xdoc.GetElementsByTagName("create_timestamp"); foreach (XmlNode node in list) { string strDate = TrimWhitespace(node.InnerText); resource.Version.Created = importManager.ConvertLRTimeToDateTime(strDate); break; } resource.Version.Imported = DateTime.Now; if (resource.Version.Created < DateTime.Parse("1900-01-01")) { resource.Version.Created = resource.Version.Modified; } if (resource.Version.Modified < SqlDateTime.MinValue) { resource.Version.Modified = (DateTime)SqlDateTime.MinValue; } if (resource.Version.Created < SqlDateTime.MinValue) { resource.Version.Created = (DateTime)SqlDateTime.MinValue; } } else { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, docId, url, ErrorType.Error, ErrorRouting.Technical, "Payload placement is not \"inline\"."); isValid = false; } return resource; } private ResourceVersion CopyOldToNewResourceVersion(ResourceVersion version) { ResourceVersion vers = new ResourceVersion(); vers.Id = 0; vers.ResourceIntId = version.ResourceIntId; vers.Title = version.Title; vers.Description = version.Description; vers.LRDocId = version.LRDocId; vers.Publisher = version.Publisher; vers.Creator = version.Creator; vers.Rights = version.Rights; vers.AccessRights = version.AccessRights; vers.Modified = version.Modified; vers.Submitter = version.Submitter; vers.Imported = version.Imported; vers.Created = version.Created; vers.TypicalLearningTime = version.TypicalLearningTime; vers.IsSkeletonFromParadata = false; vers.IsActive = true; vers.Requirements = version.Requirements; vers.SortTitle = version.SortTitle; vers.Schema = version.Schema; vers.AccessRightsId = version.AccessRightsId; vers.InteractivityTypeId = version.InteractivityTypeId; vers.InteractivityType = version.InteractivityType; return vers; } public bool AddResource(Resource resource) { bool isValid = true; string statusMessage = "successful"; resource.Version.ResourceIntId = resource.Id; importManager.CreateVersion(resource.Version, ref statusMessage); if (statusMessage != "successful") { //if rv add fails, need to reject whole resource isValid = false; reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, "MetadataController.AddResource. " + statusMessage); } return isValid; // Thumbnail generation is now done in a separate process. This code is no longer needed. /*ManualResetEvent doneEvent = new ManualResetEvent(false); doneEvents.Add(doneEvent); ImageGenerator imageGenerator = new ImageGenerator(resource.ResourceUrl, resource.Id, doneEvent); ThreadPool.QueueUserWorkItem(imageGenerator.ImageGeneratorThreadPoolCallback, doneEvent);*/ } public void UpdateResource(Resource resource) { string statusMessage = "successful"; resource.Version.ResourceIntId = resource.Id; //quepasa statusMessage = new ResourceVersionController().Update(resource.Version); if (statusMessage != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, statusMessage); } } public bool SkipSubject(string subject) { bool retVal = false; if (subject.Length > 1 && subject.Substring(0, 1) == "\"" && subject.Substring(subject.Length - 1, 1) == "\"") { // subject begins and ends with a quotation mark - check for internal quotes. Note that stripping quotes requires the subject to be at least 2 characters long. string tSubject = subject.Substring(1, subject.Length - 2); if (tSubject.IndexOf("\"") == -1) { // no internal quotes found. Strip all quotes from subject. subject = subject.Replace("\"", ""); } } if (subject.Length <= 1) { retVal = true; } if (subject.IndexOf("http:") > -1 || subject.IndexOf("https:") > -1) { retVal = true; } return retVal; } public string ApplySubjectEditRules(string subject) { if (subject.Length > 1 && subject.Substring(0, 1) == "\"" && subject.Substring(subject.Length - 1, 1) == "\"") { // subject begins and ends with a quotation mark - check for internal quotes. Note that stripping quotes requires the subject to be at least 2 characters long. string tSubject = subject.Substring(1, subject.Length - 2); if (tSubject.IndexOf("\"") == -1) { // no internal quotes found. Strip all quotes from subject. subject = subject.Replace("\"", ""); } } return subject; } public void VerifyResourceVersionRecordExists(Resource resource) { string status = "successful"; DataSet ds = new ResourceVersionController().GetByResourceUrl(resource.ResourceUrl); if (BaseDataController.DoesDataSetHaveRows(ds)) { // do nothing - it is verified } else { // Resource record exists without Resource.Version. Attempt to delete the Resource record. status = importManager.DeleteResource(resource.RowId.ToString()); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } } protected string CleanseDescription(string description) { description = description.Replace("&amp;", "&"); description = description.Replace("\\r\\n", " "); description = description.Replace("\r\n", " "); description = description.Replace("\\t", " "); description = description.Replace("\t", " "); Regex stripHtml = new Regex(@"&lt;\S(.*?)&gt;"); description = stripHtml.Replace(description, ""); return description; } protected string CleanUpAgeRange(string input) { Regex whiteSpace = new Regex(@"\s+"); // Regex for removing all whitespace from string Regex leadingDash = new Regex(@"^-+"); // Regex for removing leading "-" characters Regex multiDash = new Regex(@"--+"); // Regex for removing multiple "-" characters anywhere in the string (there must be at least two) Regex twoNumbers = new Regex(@"[0-9]-[0-9U]"); // Regex for testing if two numbers separated by a "-" are present Regex nonEndingPlus = new Regex(@"\+(?!$)"); // Regex for matching a "+" that is not at the end of the string Regex endingPlus = new Regex(@"\+$"); // Regex for matching a "+" that is at the end of the string so we can replace with "-99" Regex trailingDash = new Regex(@"-+$"); // Regex for removing trailing dashes Regex multipleNines = new Regex(@"99+"); // Regex for matching two or more 9's Regex gtAge = new Regex(@"^>[0-9]*"); // Regex for ages greater than a certain age Regex ltAge = new Regex(@"^<[0-9]*"); // Regex for ages less than a certain age string[] monthAbbrevs = { "", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; Match match; // Remove whitespace string output = whiteSpace.Replace(input, ""); // If equal to "U-" change to "0-99" if (output == "U-") { output = "0-99"; } // Convert month abbreviations to numbers for (int i = 1; i <= 12; i++) { Regex monthAbbrev = new Regex(monthAbbrevs[i], RegexOptions.IgnoreCase); output = monthAbbrev.Replace(output, i.ToString()); } // Replace HTML entities for > and < with > and < output = output.Replace("&gt;", ">"); output = output.Replace("&lt;", "<"); // Convert ">age" to "age-99" match = gtAge.Match(output); if (match.Value != string.Empty) { output = output.Substring(match.Index + 1, match.Length - 1) + "-99"; } // Convert "<age" to "0-age" match = ltAge.Match(output); if (match.Value != string.Empty) { output = "0-" + output.Substring(match.Index + 1, match.Length - 1); } // Change + to - if it is not the last character in the string output = nonEndingPlus.Replace(output, "-"); // Change ending + to "-99" output = endingPlus.Replace(output, "-99"); // change two or more 9's to 99 output = multipleNines.Replace(output, "99"); // Strip leading dashes output = leadingDash.Replace(output, ""); // Strip multiple dashes within the string output = multiDash.Replace(output, "-"); // If there are two numbers, strip trailing dashes match = twoNumbers.Match(output); if (match.Value != string.Empty) { output = trailingDash.Replace(output, ""); } else { // There are not two numbers, replace trailing dash with -99 output = trailingDash.Replace(output, "-99"); // By this point there should be two numbers separated by a dash. If not, then make it a range with only 1 number if (output.IndexOf("-") == -1) { // No dash found output = output + "-" + output; } } // Replace -U with -99 output = output.Replace("-U", "-99"); // Make sure ages are in correct order (for example, convert "99-14" to "14-99") // Also drop leading zeroes. try { string[] ages = output.Split('-'); int age1 = int.Parse(ages[0]); int age2 = int.Parse(ages[1]); if (age1 > age2) { output = age2.ToString() + "-" + age1.ToString(); } else { output = age1.ToString() + "-" + age2.ToString(); } } catch (Exception ex) { //Ignore } return output; } /// <summary> /// Crosswalk Age Ranges to Grade Levels where possible. /// </summary> /// <param name="resource"></param> /// <param name="age"></param> /// <param name="status"></param> protected void ConvertAgeToGrade(Resource resource, string age, ref string status) { status = "successful"; ResourceAgeRange level = new ResourceAgeRange(); level.ResourceIntId = resource.Id; level.OriginalValue = age; int dashIndex = level.OriginalValue.IndexOf("-"); int length = level.OriginalValue.Length; level.FromAge = int.Parse(level.OriginalValue.Substring(0, dashIndex)); level.ToAge = int.Parse(level.OriginalValue.Substring(dashIndex + 1, length - dashIndex - 1)); if (level.ToAge > 21) { // After high school, age range to grade level tends to break down. Map to "Adult Education." ResourceChildItem generalPublic = new ResourceChildItem(); generalPublic.ResourceIntId = resource.Id; generalPublic.OriginalValue = "Adult Education"; importManager.ImportGradeLevel(generalPublic, ref status); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, "", resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } if (level.FromAge > 13) { // It's adult ed and high school, so let's do high school too ResourceChildItem highSchool = new ResourceChildItem(); highSchool.ResourceIntId = resource.Id; highSchool.OriginalValue = "High School"; status = "successful"; importManager.ImportGradeLevel(highSchool, ref status); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, "", resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } } // If it's not Adult Ed, don't try to outsmart age ranges - take it as whatever it's tagged. else { // Map to grade levels CodeGradeLevelCollection grades = importManager.GradeLevelGetByAgeRange(level.FromAge, level.ToAge, false, ref status); foreach (CodeGradeLevel grade in grades) { ResourceChildItem gradeLevel = new ResourceChildItem(); gradeLevel.ResourceIntId = resource.Id; gradeLevel.OriginalValue = grade.Title; gradeLevel.CodeId = grade.Id; importManager.ImportGradeLevel(gradeLevel, ref status); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, "", resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } } }// ConvertAgeToGrade protected void ConvertGradesToAgeRange(Resource resource, string[] grades) { bool k12GradeLevelPresent = false; foreach (string title in grades) { if (title.ToLower().IndexOf("pre-k") > -1) { k12GradeLevelPresent = true; break; } if (title.ToLower().IndexOf("kindergarten") > -1) { k12GradeLevelPresent = true; break; } if (title.ToLower().IndexOf("grade") > -1) { k12GradeLevelPresent = true; break; } } if (!k12GradeLevelPresent) { // If there's no PreK-12, do not convert return; } bool firstTimeThru = true; ResourceAgeRange gradeLevel = new ResourceAgeRange(); foreach (string title in grades) { CodeGradeLevel level = importManager.GradeLevelGetByTitle(title); gradeLevel.ResourceIntId = resource.Id; if (gradeLevel.FromAge == 0) { gradeLevel.FromAge = level.FromAge; } if (gradeLevel.ToAge == 0) { gradeLevel.ToAge = level.ToAge; } if (level.FromAge < gradeLevel.FromAge) { gradeLevel.FromAge = level.FromAge; firstTimeThru = false; } if (level.ToAge > gradeLevel.ToAge) { gradeLevel.ToAge = level.ToAge; firstTimeThru = false; } } string status = importManager.ImportAgeRange(gradeLevel); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, "", resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } }// ConvertGradesToAgeRange protected bool CheckForGoodLanguage(int resourceIntId) { bool isGoodLanguage = true; List<ResourceChildItem> languages = importManager.SelectLanguage(resourceIntId, ""); DataSet goodLanguages = importManager.SelectLanguageCodeTable(); if (languages.Count > 0) { // At least one language is present. Check for English, Spanish, Polish, Chinese or Russian. If one of these is present, the language is good. bool goodLanguageFound = false; foreach (ResourceChildItem language in languages) { DataView dv = goodLanguages.Tables[0].DefaultView; dv.RowFilter = "Id = " + language.CodeId.ToString(); if (dv.Count > 0) { goodLanguageFound = true; break; } } isGoodLanguage = goodLanguageFound; } return isGoodLanguage; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using GitVersion.Common; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; namespace GitVersion.Configuration { public class BranchConfigurationCalculator : IBranchConfigurationCalculator { private const string FallbackConfigName = "Fallback"; private readonly ILog log; private readonly IRepositoryStore repositoryStore; public BranchConfigurationCalculator(ILog log, IRepositoryStore repositoryStore) { this.log = log ?? throw new ArgumentNullException(nameof(log)); this.repositoryStore = repositoryStore ?? throw new ArgumentNullException(nameof(repositoryStore)); } /// <summary> /// Gets the <see cref="BranchConfig"/> for the current commit. /// </summary> public BranchConfig GetBranchConfiguration(IBranch targetBranch, ICommit currentCommit, Config configuration, IList<IBranch> excludedInheritBranches = null) { var matchingBranches = configuration.GetConfigForBranch(targetBranch.Name.WithoutRemote); if (matchingBranches == null) { log.Info($"No branch configuration found for branch {targetBranch}, falling back to default configuration"); matchingBranches = BranchConfig.CreateDefaultBranchConfig(FallbackConfigName) .Apply(new BranchConfig { Regex = "", VersioningMode = configuration.VersioningMode, Increment = configuration.Increment ?? IncrementStrategy.Inherit, }); } if (matchingBranches.Increment == IncrementStrategy.Inherit) { matchingBranches = InheritBranchConfiguration(targetBranch, matchingBranches, currentCommit, configuration, excludedInheritBranches); if (matchingBranches.Name.IsEquivalentTo(FallbackConfigName) && matchingBranches.Increment == IncrementStrategy.Inherit) { // We tried, and failed to inherit, just fall back to patch matchingBranches.Increment = IncrementStrategy.Patch; } } return matchingBranches; } // TODO I think we need to take a fresh approach to this.. it's getting really complex with heaps of edge cases private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConfig branchConfiguration, ICommit currentCommit, Config configuration, IList<IBranch> excludedInheritBranches) { using (log.IndentLog("Attempting to inherit branch configuration from parent branch")) { var excludedBranches = new[] { targetBranch }; // Check if we are a merge commit. If so likely we are a pull request var parentCount = currentCommit.Parents.Count(); if (parentCount == 2) { excludedBranches = CalculateWhenMultipleParents(currentCommit, ref targetBranch, excludedBranches); } excludedInheritBranches ??= repositoryStore.GetExcludedInheritBranches(configuration).ToList(); excludedBranches = excludedBranches.Where(b => excludedInheritBranches.All(bte => !b.Equals(bte))).ToArray(); // Add new excluded branches. foreach (var excludedBranch in excludedBranches) { excludedInheritBranches.Add(excludedBranch); } var branchesToEvaluate = repositoryStore.ExcludingBranches(excludedInheritBranches).ToList(); var branchPoint = repositoryStore .FindCommitBranchWasBranchedFrom(targetBranch, configuration, excludedInheritBranches.ToArray()); List<IBranch> possibleParents; if (branchPoint == BranchCommit.Empty) { possibleParents = repositoryStore.GetBranchesContainingCommit(targetBranch.Tip, branchesToEvaluate) // It fails to inherit Increment branch configuration if more than 1 parent; // therefore no point to get more than 2 parents .Take(2) .ToList(); } else { var branches = repositoryStore.GetBranchesContainingCommit(branchPoint.Commit, branchesToEvaluate).ToList(); if (branches.Count > 1) { var currentTipBranches = repositoryStore.GetBranchesContainingCommit(currentCommit, branchesToEvaluate).ToList(); possibleParents = branches.Except(currentTipBranches).ToList(); } else { possibleParents = branches; } } log.Info("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.ToString()))); if (possibleParents.Count == 1) { var branchConfig = GetBranchConfiguration(possibleParents[0], currentCommit, configuration, excludedInheritBranches); // If we have resolved a fallback config we should not return that we have got config if (branchConfig.Name != FallbackConfigName) { return new BranchConfig(branchConfiguration) { Increment = branchConfig.Increment, PreventIncrementOfMergedBranchVersion = branchConfig.PreventIncrementOfMergedBranchVersion, // If we are inheriting from develop then we should behave like develop TracksReleaseBranches = branchConfig.TracksReleaseBranches }; } } // If we fail to inherit it is probably because the branch has been merged and we can't do much. So we will fall back to develop's config // if develop exists and master if not var errorMessage = possibleParents.Count == 0 ? "Failed to inherit Increment branch configuration, no branches found." : "Failed to inherit Increment branch configuration, ended up with: " + string.Join(", ", possibleParents.Select(p => p.ToString())); var chosenBranch = repositoryStore.GetChosenBranch(configuration); if (chosenBranch == null) { // TODO We should call the build server to generate this exception, each build server works differently // for fetch issues and we could give better warnings. throw new InvalidOperationException("Could not find a 'develop' or 'master' branch, neither locally nor remotely."); } log.Warning($"{errorMessage}{System.Environment.NewLine}Falling back to {chosenBranch} branch config"); // To prevent infinite loops, make sure that a new branch was chosen. if (targetBranch.Equals(chosenBranch)) { var developOrMasterConfig = ChooseMasterOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem( chosenBranch, branchConfiguration, configuration); if (developOrMasterConfig != null) { return developOrMasterConfig; } log.Warning("Fallback branch wants to inherit Increment branch configuration from itself. Using patch increment instead."); return new BranchConfig(branchConfiguration) { Increment = IncrementStrategy.Patch }; } var inheritingBranchConfig = GetBranchConfiguration(chosenBranch, currentCommit, configuration, excludedInheritBranches); var configIncrement = inheritingBranchConfig.Increment; if (inheritingBranchConfig.Name.IsEquivalentTo(FallbackConfigName) && configIncrement == IncrementStrategy.Inherit) { log.Warning("Fallback config inherits by default, dropping to patch increment"); configIncrement = IncrementStrategy.Patch; } return new BranchConfig(branchConfiguration) { Increment = configIncrement, PreventIncrementOfMergedBranchVersion = inheritingBranchConfig.PreventIncrementOfMergedBranchVersion, // If we are inheriting from develop then we should behave like develop TracksReleaseBranches = inheritingBranchConfig.TracksReleaseBranches }; } } private IBranch[] CalculateWhenMultipleParents(ICommit currentCommit, ref IBranch currentBranch, IBranch[] excludedBranches) { var parents = currentCommit.Parents.ToArray(); var branches = repositoryStore.GetBranchesForCommit(parents[1]).ToList(); if (branches.Count == 1) { var branch = branches[0]; excludedBranches = new[] { currentBranch, branch }; currentBranch = branch; } else if (branches.Count > 1) { currentBranch = branches.FirstOrDefault(b => b.Name.WithoutRemote == Config.MasterBranchKey) ?? branches.First(); } else { var possibleTargetBranches = repositoryStore.GetBranchesForCommit(parents[0]).ToList(); if (possibleTargetBranches.Count > 1) { currentBranch = possibleTargetBranches.FirstOrDefault(b => b.Name.WithoutRemote == Config.MasterBranchKey) ?? possibleTargetBranches.First(); } else { currentBranch = possibleTargetBranches.FirstOrDefault() ?? currentBranch; } } log.Info($"HEAD is merge commit, this is likely a pull request using {currentBranch} as base"); return excludedBranches; } private static BranchConfig ChooseMasterOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem(IBranch chosenBranch, BranchConfig branchConfiguration, Config config) { BranchConfig masterOrDevelopConfig = null; var developBranchRegex = config.Branches[Config.DevelopBranchKey].Regex; var masterBranchRegex = config.Branches[Config.MasterBranchKey].Regex; if (Regex.IsMatch(chosenBranch.Name.Friendly, developBranchRegex, RegexOptions.IgnoreCase)) { // Normally we would not expect this to happen but for safety we add a check if (config.Branches[Config.DevelopBranchKey].Increment != IncrementStrategy.Inherit) { masterOrDevelopConfig = new BranchConfig(branchConfiguration) { Increment = config.Branches[Config.DevelopBranchKey].Increment }; } } else if (Regex.IsMatch(chosenBranch.Name.Friendly, masterBranchRegex, RegexOptions.IgnoreCase)) { // Normally we would not expect this to happen but for safety we add a check if (config.Branches[Config.MasterBranchKey].Increment != IncrementStrategy.Inherit) { masterOrDevelopConfig = new BranchConfig(branchConfiguration) { Increment = config.Branches[Config.DevelopBranchKey].Increment }; } } return masterOrDevelopConfig; } } }
using Microsoft.Xna.Framework.Graphics; using Loon.Java; using System; using Loon.Core.Graphics.Opengl; using Loon.Core.Graphics.Device; using Loon.Utils; using Loon.Core.Resource; using Microsoft.Xna.Framework; using System.IO; using System.Collections.Generic; namespace Loon.Core.Graphics { public class LImage : LRelease { internal void XNAUpdateAlpha(byte alpha) { Color[] pixels = new Color[width * height]; m_data.GetData<Color>(pixels); for (int i = 0; i < pixels.Length; i++) { pixels[i].A = alpha; } m_data.SetData<Color>(pixels); } public int Width { get { return width; } } public int Height { get { return height; } } private Loon.Core.Graphics.Opengl.LTexture.Format m_format; private bool bMutable; internal Texture2D m_data; internal bool isExt, isAutoDispose, isUpdate, isClose, hasAlpha; internal int width, height; string fileName; private static List<LImage> images = new List<LImage>(100); private void Init() { if (!images.Contains(this)) { images.Add(this); } this.bMutable = true; } private LImage() { Init(); } public LImage(string resName) { string extName = FileUtils.GetExtension(resName); if ("".Equals(extName) || "xna".Equals(extName, StringComparison.InvariantCultureIgnoreCase)) { isExt = false; } else { isExt = true; } string newPath = resName; if (newPath[0] == '/') { newPath = newPath.Substring(1); } if (isExt) { m_data = Texture2D.FromStream(GL.device, Resources.OpenStream(newPath)); width = m_data.Width; height = m_data.Height; } else { if (newPath.IndexOf("/") == -1 && (FileUtils.GetExtension(newPath).Length == 0)) { newPath = "Content/" + newPath; } m_data = LSystem.screenActivity.GameRes.Load<Texture2D>(StringUtils.ReplaceIgnoreCase(newPath, ".xnb", "")); width = m_data.Width; height = m_data.Height; } fileName = newPath; CheckAlpha(); Init(); } public LImage(Texture2D tex2d) { m_data = tex2d; width = tex2d.Width; height = tex2d.Height; CheckAlpha(); Init(); } public static LImage CreateImage(int width, int height) { return CreateImage(width, height, SurfaceFormat.Color); } public static LImage CreateImage(int width, int height, SurfaceFormat format) { LImage image = new LImage(); image.m_data = new RenderTarget2D(GL.device, width, height, false, format, DepthFormat.None, 0, RenderTargetUsage.PreserveContents); image.width = image.m_data.Width; image.height = image.m_data.Height; image.CheckAlpha(); return image; } public static LImage CreateImage(LImage image, int x, int y, int width, int height, int transform) { LImage result = new LImage(); if (transform < 4) { result.m_data = new Texture2D(GL.device, width, height, false, SurfaceFormat.Color); } else { result.m_data = new Texture2D(GL.device, height, width, true, SurfaceFormat.Color); } result.width = image.m_data.Width; result.height = image.m_data.Height; result.CheckAlpha(); return result; } public static LImage CreateImage(byte[] buffer) { MemoryStream stream = new MemoryStream(buffer); return CreateImage(stream); } public static LImage CreateImage(Color[] pixels, int width, int height, bool hasAlpha) { LImage image = new LImage(); image.hasAlpha = hasAlpha; image.width = width; image.height = height; int size = width * height; Texture2D texture = new Texture2D(GL.device, width, height); texture.SetData<Color>(pixels); image.m_data = texture; return image; } public static LImage CreateImage(int width, int height, bool hasAlpha) { LImage image = new LImage(); image.hasAlpha = hasAlpha; image.width = width; image.height = height; int size = width * height; Color[] pixels = new Color[size]; if (!hasAlpha) { for (int i = 0; i < size; i++) { pixels[i] = Color.Black; } } Texture2D texture = new Texture2D(GL.device, width, height); texture.SetData<Color>(pixels); image.m_data = texture; return image; } internal static LImage NewImage(Texture2D tex2d) { int size = tex2d.Width * tex2d.Height; Color[] pixels = new Color[size]; tex2d.GetData<Color>(pixels); LImage image = new LImage(); Texture2D newTex2d = new Texture2D(GL.device, tex2d.Width, tex2d.Height); newTex2d.SetData<Color>(pixels); image.m_data = newTex2d; image.width = image.m_data.Width; image.height = image.m_data.Height; image.CheckAlpha(); return image; } public static LImage CreateImage(InputStream ins) { LImage image = null; try { image = new LImage(); image.m_data = Texture2D.FromStream(GL.device, ins); image.width = image.m_data.Width; image.height = image.m_data.Height; image.isExt = true; image.CheckAlpha(); } catch (Exception ex) { Loon.Utils.Debugging.Log.Exception(ex); } finally { if (ins != null) { try { ins.Close(); ins = null; } catch (Exception) { } } } return image; } public static LImage CreateImage(Texture2D tex2d) { return new LImage(tex2d); } public static LImage CreateImage(string resName) { return new LImage(resName); } private void CheckAlpha() { hasAlpha = m_data.Format == SurfaceFormat.Dxt5 || m_data.Format == SurfaceFormat.Dxt3 || m_data.Format == SurfaceFormat.Alpha8 || m_data.Format == SurfaceFormat.Bgra4444 || m_data.Format == SurfaceFormat.Rgba64; if (!hasAlpha) { int w = width - 1; int h = height - 1; hasAlpha = GetIntPixel(0, 0) == 0; if (!hasAlpha) { hasAlpha = GetIntPixel(w, 0) == 0; } if (!hasAlpha) { hasAlpha = GetIntPixel(w, h) == 0; } if (!hasAlpha) { hasAlpha = GetIntPixel(0, h) == 0; } if (!hasAlpha) { hasAlpha = GetIntPixel(w / 2, h / 2) == 0; } } } public bool HasAlpha() { return hasAlpha; } public Texture2D GetBitmap() { return m_data; } public LImage Clone() { LImage image = new LImage(); image.width = width; image.height = height; image.hasAlpha = hasAlpha; image.m_data = m_data; image.fileName = fileName; image.isExt = isExt; return image; } private LTexture _texture; public LTexture GetTexture() { if (_texture == null || _texture.isClose || isUpdate) { SetAutoDispose(false); LTexture tmp = _texture; _texture = new LTexture(GLLoader.GetTextureData(this), m_format); if (tmp != null) { tmp.Dispose(); tmp = null; } isUpdate = false; } return _texture; } private LGraphics m_g; public LGraphics GetLGraphics() { if (this.bMutable) { if (m_g == null || m_g.IsClose()) { m_g = new LGraphics(this); isUpdate = true; } return m_g; } return null; } public LGraphics Create() { return new LGraphics(this); } public Color[] GetPixels() { Color[] pixels = new Color[width * height]; m_data.GetData<Color>(pixels); return pixels; } public int[] GetIntPixels() { int[] pixels = new int[width * height]; m_data.GetData<int>(pixels); return pixels; } public int[] GetIntPixels(int[] pixels) { m_data.GetData<int>(pixels); return pixels; } public Color[] GetPixels(Color[] pixels) { m_data.GetData<Color>(pixels); return pixels; } public int[] GetIntPixels(int x, int y, int w, int h) { int[] pixels = new int[w * h]; _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.GetData<int>(0, _pixel_rect, pixels, 0, pixels.Length); return pixels; } public Color[] GetPixels(int x, int y, int w, int h) { Color[] pixels = new Color[w * h]; _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.GetData<Color>(0, _pixel_rect, pixels, 0, pixels.Length); return pixels; } public int[] GetIntPixels(int offset, int stride, int x, int y, int w, int h) { int[] pixels = new int[w * h]; _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.GetData<int>(0, _pixel_rect, pixels, offset, stride); return pixels; } public Color[] GetPixels(int offset, int stride, int x, int y, int w, int h) { Color[] pixels = new Color[w * h]; _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.GetData<Color>(0, _pixel_rect, pixels, offset, stride); return pixels; } public int[] GetPixels(int[] pixels, int offset, int stride, int x, int y, int w, int h) { _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.GetData<int>(0, _pixel_rect, pixels, offset, stride); return pixels; } public Color[] GetPixels(Color[] pixels, int offset, int stride, int x, int y, int w, int h) { _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.GetData<Color>(0, _pixel_rect, pixels, offset, stride); return pixels; } public int[] GetIntPixels(int[] pixels, int offset, int stride, int x, int y, int w, int h) { _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.GetData<int>(0, _pixel_rect, pixels, offset, stride); return pixels; } public Color[] GetRGB(Color[] pixels, int offset, int stride, int x, int y, int w, int h) { _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.GetData<Color>(0, _pixel_rect, pixels, offset, stride); return pixels; } public void GetIntRGB(int startX, int startY, int w, int h, ref int[] rgbArray, int offset, int scansize) { _pixel_rect.X = startX; _pixel_rect.Y = startY; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.GetData<int>(0, _pixel_rect, rgbArray, offset, scansize); } public void GetRGB(int startX, int startY, int w, int h, ref Color[] rgbArray, int offset, int scansize) { _pixel_rect.X = startX; _pixel_rect.Y = startY; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.GetData<Color>(0, _pixel_rect, rgbArray, offset, scansize); } public Color GetRGB(int x, int y) { return GetPixel(x, y); } public void SetIntPixels(int[] pixels) { isUpdate = true; m_data.SetData<int>(pixels); } public void SetPixels(Color[] pixels) { isUpdate = true; m_data.SetData<Color>(pixels); } public void SetPixels(int[] pixels, int w, int h) { isUpdate = true; _pixel_rect.X = 0; _pixel_rect.Y = 0; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.SetData<int>(0, _pixel_rect, pixels, 0, pixels.Length); } public void SetPixels(Color[] pixels, int w, int h) { isUpdate = true; _pixel_rect.X = 0; _pixel_rect.Y = 0; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.SetData<Color>(0, _pixel_rect, pixels, 0, pixels.Length); } public void SetIntPixels(int[] pixels, int offset, int stride, int x, int y, int w, int h) { isUpdate = true; _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.SetData<int>(0, _pixel_rect, pixels, offset, stride); } public void SetPixels(Color[] pixels, int offset, int stride, int x, int y, int w, int h) { isUpdate = true; _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.SetData<Color>(0, _pixel_rect, pixels, offset, stride); } public void SetIntRGB(int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize) { SetIntPixels(rgbArray, offset, scansize, startX, startY, w, h); } public void SetRGB(int startX, int startY, int w, int h, Color[] rgbArray, int offset, int scansize) { SetPixels(rgbArray, offset, scansize, startX, startY, w, h); } public int[] SetIntPixels(int[] pixels, int x, int y, int w, int h) { isUpdate = true; _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.SetData<int>(0, _pixel_rect, pixels, 0, pixels.Length); return pixels; } public Color[] SetPixels(Color[] pixels, int x, int y, int w, int h) { isUpdate = true; _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = w; _pixel_rect.Height = h; m_data.SetData<Color>(0, _pixel_rect, pixels, 0, pixels.Length); return pixels; } private Rectangle _pixel_rect = new Rectangle(0, 0, 1, 1); private Color[] color_data = new Color[1]; public Color GetPixel(int x, int y) { if (this.m_data.Format != SurfaceFormat.Color) { return Color.Black; } _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = 1; _pixel_rect.Height = 1; this.m_data.GetData<Color>(0, _pixel_rect, color_data, 0, 1); return color_data[0]; } private int[] int_data = new int[1]; public int GetIntPixel(int x, int y) { _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = 1; _pixel_rect.Height = 1; this.m_data.GetData<int>(0, _pixel_rect, int_data, 0, 1); return int_data[0]; } public void SetPixel(Color c, int x, int y) { isUpdate = true; _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = 1; _pixel_rect.Height = 1; this.m_data.SetData<Color>(0, _pixel_rect, new Color[1] { c }, 0, 1); } public void SetPixel(uint rgb, int x, int y) { isUpdate = true; _pixel_rect.X = x; _pixel_rect.Y = y; _pixel_rect.Width = 1; _pixel_rect.Height = 1; Color c = new Color(); c.PackedValue = rgb; this.m_data.SetData<Color>(0, _pixel_rect, new Color[1] { c }, 0, 1); } public void SetRGB(uint rgb, int x, int y) { SetPixel(rgb, x, y); } public LColor GetColorAt(int x, int y) { return new LColor(GetPixel(x, y)); } public uint GetRGBAt(int x, int y) { if (x >= this.width) { throw new Exception("X is out of bounds: " + x + "," + this.width); } else if (y >= this.height) { throw new Exception("Y is out of bounds: " + y + "," + this.height); } else if (x < 0) { throw new Exception("X is out of bounds: " + x); } else if (y < 0) { throw new Exception("Y is out of bounds: " + y); } else { return GetPixel(x, y).PackedValue; } } public Loon.Core.Graphics.Opengl.LTexture.Format GetFormat() { return m_format; } public void SetFormat(Loon.Core.Graphics.Opengl.LTexture.Format format) { this.m_format = format; this.isUpdate = true; } public bool IsAutoDispose() { return isAutoDispose && !IsClose(); } public void SetAutoDispose(bool dispose) { this.isAutoDispose = dispose; } public bool IsClose() { return isClose || m_data == null || (m_data != null ? m_data.IsDisposed : false); } public void Dispose() { Dispose(true); } public LImage ScaledInstance(int w, int h) { int width = GetWidth(); int height = GetHeight(); if (width == w && height == h) { return this; } return GraphicsUtils.GetResize(this, w, h); } public LImage GetSubImage(int x, int y, int w, int h) { return this.GetLGraphics().GetSubImage(x, y, w, h); } public string GetPath() { return fileName; } public int GetWidth() { return width; } public int GetHeight() { return height; } public void CopyPixelsToBuffer(ByteBuffer buffer) { sbyte[] m_data = new sbyte[(this.m_data.Width * this.m_data.Height) * 4]; this.m_data.GetData<sbyte>(m_data); buffer.Put(m_data, 0, m_data.Length); buffer.Rewind(); } public SurfaceFormat GetConfig() { return m_data.Format; } private void Dispose(bool remove) { isClose = true; if (m_data != null && !isUpdate && (_texture == null || _texture.IsClose())) { m_data.Dispose(); m_data = null; } if (_texture != null && isAutoDispose) { _texture.Dispose(); _texture = null; } if (remove) { CollectionUtils.Remove(images, this); } } public static void DisposeAll() { if (images.Count > 0) { foreach (LImage img in images) { if (img != null) { img.Dispose(false); } } CollectionUtils.Clear(images); } } } }
#if UNITY_IOS // Copyright 2015-2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using GoogleMobileAds.Api; using GoogleMobileAds.Common; namespace GoogleMobileAds.iOS { public class InterstitialClient : IInterstitialClient, IDisposable { private IntPtr interstitialClientPtr; private IntPtr interstitialPtr; #region interstitial ad callback types internal delegate void GADUInterstitialAdLoadedCallback(IntPtr interstitialClient); internal delegate void GADUInterstitialAdFailedToLoadCallback(IntPtr interstitialClient, IntPtr error); internal delegate void GADUInterstitialPaidEventCallback( IntPtr interstitialClient, int precision, long value, string currencyCode); #endregion #region full screen content callback types internal delegate void GADUInterstitialAdFailedToPresentFullScreenContentCallback(IntPtr interstitialClient, IntPtr error); internal delegate void GADUInterstitialAdWillPresentFullScreenContentCallback(IntPtr interstitialClient); internal delegate void GADUInterstitialAdDidDismissFullScreenContentCallback(IntPtr interstitialClient); internal delegate void GADUInterstitialAdDidRecordImpressionCallback(IntPtr interstitialClient); #endregion public event EventHandler<EventArgs> OnAdLoaded; public event EventHandler<LoadAdErrorClientEventArgs> OnAdFailedToLoad; public event EventHandler<AdValueEventArgs> OnPaidEvent; public event EventHandler<AdErrorClientEventArgs> OnAdFailedToPresentFullScreenContent; public event EventHandler<EventArgs> OnAdDidPresentFullScreenContent; public event EventHandler<EventArgs> OnAdDidDismissFullScreenContent; public event EventHandler<EventArgs> OnAdDidRecordImpression; // This property should be used when setting the interstitialPtr. private IntPtr InterstitialPtr { get { return this.interstitialPtr; } set { Externs.GADURelease(this.interstitialPtr); this.interstitialPtr = value; } } #region IInterstitialClient implementation public void CreateInterstitialAd() { this.interstitialClientPtr = (IntPtr)GCHandle.Alloc(this); this.InterstitialPtr = Externs.GADUCreateInterstitial(this.interstitialClientPtr); Externs.GADUSetInterstitialCallbacks( this.InterstitialPtr, InterstitialLoadedCallback, InterstitialFailedToLoadCallback, AdWillPresentFullScreenContentCallback, AdFailedToPresentFullScreenContentCallback, AdDidDismissFullScreenContentCallback, AdDidRecordImpressionCallback, InterstitialPaidEventCallback); } public void LoadAd(string adUnitID, AdRequest request) { IntPtr requestPtr = Utils.BuildAdRequest(request); Externs.GADULoadInterstitialAd(this.InterstitialPtr, adUnitID, requestPtr); Externs.GADURelease(requestPtr); } // Show the interstitial ad on the screen. public void Show() { Externs.GADUShowInterstitial(this.InterstitialPtr); } public IResponseInfoClient GetResponseInfoClient() { return new ResponseInfoClient(ResponseInfoClientType.AdLoaded, this.InterstitialPtr); } // Destroys the interstitial ad. public void DestroyInterstitial() { this.InterstitialPtr = IntPtr.Zero; } public void Dispose() { this.DestroyInterstitial(); ((GCHandle)this.interstitialClientPtr).Free(); } ~InterstitialClient() { this.Dispose(); } #endregion #region interstitial ad callback methods [MonoPInvokeCallback(typeof(GADUInterstitialAdLoadedCallback))] private static void InterstitialLoadedCallback(IntPtr interstitialClient) { InterstitialClient client = IntPtrToInterstitialClient(interstitialClient); if (client.OnAdLoaded != null) { client.OnAdLoaded(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUInterstitialAdFailedToLoadCallback))] private static void InterstitialFailedToLoadCallback( IntPtr interstitialClient, IntPtr error) { InterstitialClient client = IntPtrToInterstitialClient(interstitialClient); if (client.OnAdFailedToLoad != null) { LoadAdErrorClientEventArgs args = new LoadAdErrorClientEventArgs() { LoadAdErrorClient = new LoadAdErrorClient(error) }; client.OnAdFailedToLoad(client, args); } } [MonoPInvokeCallback(typeof(GADUInterstitialPaidEventCallback))] private static void InterstitialPaidEventCallback( IntPtr interstitialClient, int precision, long value, string currencyCode) { InterstitialClient client = IntPtrToInterstitialClient(interstitialClient); if (client.OnPaidEvent != null) { AdValue adValue = new AdValue() { Precision = (AdValue.PrecisionType)precision, Value = value, CurrencyCode = currencyCode }; AdValueEventArgs args = new AdValueEventArgs() { AdValue = adValue }; client.OnPaidEvent(client, args); } } [MonoPInvokeCallback(typeof(GADUInterstitialAdFailedToPresentFullScreenContentCallback))] private static void AdFailedToPresentFullScreenContentCallback(IntPtr interstitialClient, IntPtr error) { InterstitialClient client = IntPtrToInterstitialClient(interstitialClient); if (client.OnAdFailedToPresentFullScreenContent != null) { AdErrorClientEventArgs args = new AdErrorClientEventArgs() { AdErrorClient = new AdErrorClient(error) }; client.OnAdFailedToPresentFullScreenContent(client, args); } } [MonoPInvokeCallback(typeof(GADUInterstitialAdWillPresentFullScreenContentCallback))] private static void AdWillPresentFullScreenContentCallback(IntPtr interstitialClient) { InterstitialClient client = IntPtrToInterstitialClient(interstitialClient); if (client.OnAdDidPresentFullScreenContent != null) { client.OnAdDidPresentFullScreenContent(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUInterstitialAdDidDismissFullScreenContentCallback))] private static void AdDidDismissFullScreenContentCallback(IntPtr interstitialClient) { InterstitialClient client = IntPtrToInterstitialClient(interstitialClient); if (client.OnAdDidDismissFullScreenContent != null) { client.OnAdDidDismissFullScreenContent(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUInterstitialAdDidRecordImpressionCallback))] private static void AdDidRecordImpressionCallback(IntPtr interstitialClient) { InterstitialClient client = IntPtrToInterstitialClient(interstitialClient); if (client.OnAdDidRecordImpression != null) { client.OnAdDidRecordImpression(client, EventArgs.Empty); } } private static InterstitialClient IntPtrToInterstitialClient( IntPtr interstitialClient) { GCHandle handle = (GCHandle)interstitialClient; return handle.Target as InterstitialClient; } #endregion } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace Microsoft.AspNetCore.Components.Server.Circuits { public class ServerComponentDeserializerTest { private readonly IDataProtectionProvider _ephemeralDataProtectionProvider; private readonly ITimeLimitedDataProtector _protector; private readonly ServerComponentInvocationSequence _invocationSequence = new ServerComponentInvocationSequence(); public ServerComponentDeserializerTest() { _ephemeralDataProtectionProvider = new EphemeralDataProtectionProvider(); _protector = _ephemeralDataProtectionProvider .CreateProtector(ServerComponentSerializationSettings.DataProtectionProviderPurpose) .ToTimeLimitedDataProtector(); } [Fact] public void CanParseSingleMarker() { // Arrange var markers = SerializeMarkers(CreateMarkers(typeof(TestComponent))); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.True(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); var deserializedDescriptor = Assert.Single(descriptors); Assert.Equal(typeof(TestComponent).FullName, deserializedDescriptor.ComponentType.FullName); Assert.Equal(0, deserializedDescriptor.Sequence); } [Fact] public void CanParseSingleMarkerWithParameters() { // Arrange var markers = SerializeMarkers(CreateMarkers( (typeof(TestComponent), new Dictionary<string, object> { ["Parameter"] = "Value" }))); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.True(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); var deserializedDescriptor = Assert.Single(descriptors); Assert.Equal(typeof(TestComponent).FullName, deserializedDescriptor.ComponentType.FullName); Assert.Equal(0, deserializedDescriptor.Sequence); var parameters = deserializedDescriptor.Parameters.ToDictionary(); Assert.Single(parameters); Assert.Contains("Parameter", parameters.Keys); Assert.Equal("Value", parameters["Parameter"]); } [Fact] public void CanParseSingleMarkerWithNullParameters() { // Arrange var markers = SerializeMarkers(CreateMarkers( (typeof(TestComponent), new Dictionary<string, object> { ["Parameter"] = null }))); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.True(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); var deserializedDescriptor = Assert.Single(descriptors); Assert.Equal(typeof(TestComponent).FullName, deserializedDescriptor.ComponentType.FullName); Assert.Equal(0, deserializedDescriptor.Sequence); var parameters = deserializedDescriptor.Parameters.ToDictionary(); Assert.Single(parameters); Assert.Contains("Parameter", parameters.Keys); Assert.Null(parameters["Parameter"]); } [Fact] public void CanParseMultipleMarkers() { // Arrange var markers = SerializeMarkers(CreateMarkers(typeof(TestComponent), typeof(TestComponent))); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.True(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Equal(2, descriptors.Count); var firstDescriptor = descriptors[0]; Assert.Equal(typeof(TestComponent).FullName, firstDescriptor.ComponentType.FullName); Assert.Equal(0, firstDescriptor.Sequence); var secondDescriptor = descriptors[1]; Assert.Equal(typeof(TestComponent).FullName, secondDescriptor.ComponentType.FullName); Assert.Equal(1, secondDescriptor.Sequence); } [Fact] public void CanParseMultipleMarkersWithParameters() { // Arrange var markers = SerializeMarkers(CreateMarkers( (typeof(TestComponent), new Dictionary<string, object> { ["First"] = "Value" }), (typeof(TestComponent), new Dictionary<string, object> { ["Second"] = null }))); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.True(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Equal(2, descriptors.Count); var firstDescriptor = descriptors[0]; Assert.Equal(typeof(TestComponent).FullName, firstDescriptor.ComponentType.FullName); Assert.Equal(0, firstDescriptor.Sequence); var firstParameters = firstDescriptor.Parameters.ToDictionary(); Assert.Single(firstParameters); Assert.Contains("First", firstParameters.Keys); Assert.Equal("Value", firstParameters["First"]); var secondDescriptor = descriptors[1]; Assert.Equal(typeof(TestComponent).FullName, secondDescriptor.ComponentType.FullName); Assert.Equal(1, secondDescriptor.Sequence); var secondParameters = secondDescriptor.Parameters.ToDictionary(); Assert.Single(secondParameters); Assert.Contains("Second", secondParameters.Keys); Assert.Null(secondParameters["Second"]); } [Fact] public void CanParseMultipleMarkersWithAndWithoutParameters() { // Arrange var markers = SerializeMarkers(CreateMarkers( (typeof(TestComponent), new Dictionary<string, object> { ["First"] = "Value" }), (typeof(TestComponent), null))); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.True(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Equal(2, descriptors.Count); var firstDescriptor = descriptors[0]; Assert.Equal(typeof(TestComponent).FullName, firstDescriptor.ComponentType.FullName); Assert.Equal(0, firstDescriptor.Sequence); var firstParameters = firstDescriptor.Parameters.ToDictionary(); Assert.Single(firstParameters); Assert.Contains("First", firstParameters.Keys); Assert.Equal("Value", firstParameters["First"]); var secondDescriptor = descriptors[1]; Assert.Equal(typeof(TestComponent).FullName, secondDescriptor.ComponentType.FullName); Assert.Equal(1, secondDescriptor.Sequence); Assert.Empty(secondDescriptor.Parameters.ToDictionary()); } [Fact] public void DoesNotParseOutOfOrderMarkers() { // Arrange var markers = SerializeMarkers(CreateMarkers(typeof(TestComponent), typeof(TestComponent)).Reverse().ToArray()); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.False(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Empty(descriptors); } [Fact] public void DoesNotParseMarkersFromDifferentInvocationSequences() { // Arrange var firstChain = CreateMarkers(typeof(TestComponent)); var secondChain = CreateMarkers(new ServerComponentInvocationSequence(), typeof(TestComponent), typeof(TestComponent)).Skip(1); var markers = SerializeMarkers(firstChain.Concat(secondChain).ToArray()); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.False(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Empty(descriptors); } [Fact] public void DoesNotParseMarkersWhoseSequenceDoesNotStartAtZero() { // Arrange var markers = SerializeMarkers(CreateMarkers(typeof(TestComponent), typeof(TestComponent)).Skip(1).ToArray()); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.False(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Empty(descriptors); } [Fact] public void DoesNotParseMarkersWithGapsInTheSequence() { // Arrange var brokenChain = CreateMarkers(typeof(TestComponent), typeof(TestComponent), typeof(TestComponent)) .Where(m => m.Sequence != 1) .ToArray(); var markers = SerializeMarkers(brokenChain); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.False(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Empty(descriptors); } [Fact] public void DoesNotParseMarkersWithMissingDescriptor() { // Arrange var missingDescriptorMarker = CreateMarkers(typeof(TestComponent)); missingDescriptorMarker[0].Descriptor = null; var markers = SerializeMarkers(missingDescriptorMarker); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.False(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Empty(descriptors); } [Fact] public void DoesNotParseMarkersWithMissingType() { // Arrange var missingTypeMarker = CreateMarkers(typeof(TestComponent)); missingTypeMarker[0].Type = null; var markers = SerializeMarkers(missingTypeMarker); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.False(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Empty(descriptors); } // Ensures we don't use untrusted data for validation. [Fact] public void AllowsMarkersWithMissingSequence() { // Arrange var missingSequenceMarker = CreateMarkers(typeof(TestComponent), typeof(TestComponent)); missingSequenceMarker[0].Sequence = null; missingSequenceMarker[1].Sequence = null; var markers = SerializeMarkers(missingSequenceMarker); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.True(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Equal(2, descriptors.Count); } // Ensures that we don't try to load assemblies [Fact] public void DoesNotParseMarkersWithUnknownComponentTypeAssembly() { // Arrange var missingUnknownComponentTypeMarker = CreateMarkers(typeof(TestComponent)); missingUnknownComponentTypeMarker[0].Descriptor = _protector.Protect( SerializeComponent("UnknownAssembly", "System.String"), TimeSpan.FromSeconds(30)); var markers = SerializeMarkers(missingUnknownComponentTypeMarker); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.False(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Empty(descriptors); } [Fact] public void DoesNotParseMarkersWithUnknownComponentTypeName() { // Arrange var missingUnknownComponentTypeMarker = CreateMarkers(typeof(TestComponent)); missingUnknownComponentTypeMarker[0].Descriptor = _protector.Protect( SerializeComponent(typeof(TestComponent).Assembly.GetName().Name, "Unknown.Type"), TimeSpan.FromSeconds(30)); var markers = SerializeMarkers(missingUnknownComponentTypeMarker); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.False(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Empty(descriptors); } [Fact] public void DoesNotParseMarkersWithInvalidDescriptorPayloads() { // Arrange var invalidDescriptorMarker = CreateMarkers(typeof(TestComponent)); invalidDescriptorMarker[0].Descriptor = "nondataprotecteddata"; var markers = SerializeMarkers(invalidDescriptorMarker); var serverComponentDeserializer = CreateServerComponentDeserializer(); // Act & assert Assert.False(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors)); Assert.Empty(descriptors); } private string SerializeComponent(string assembly, string type) => JsonSerializer.Serialize( new ServerComponent(0, assembly, type, Array.Empty<ComponentParameter>(), Array.Empty<object>(), Guid.NewGuid()), ServerComponentSerializationSettings.JsonSerializationOptions); private ServerComponentDeserializer CreateServerComponentDeserializer() { return new ServerComponentDeserializer( _ephemeralDataProtectionProvider, NullLogger<ServerComponentDeserializer>.Instance, new RootComponentTypeCache(), new ComponentParameterDeserializer(NullLogger<ComponentParameterDeserializer>.Instance, new ComponentParametersTypeCache())); } private string SerializeMarkers(ServerComponentMarker[] markers) => JsonSerializer.Serialize(markers, ServerComponentSerializationSettings.JsonSerializationOptions); private ServerComponentMarker[] CreateMarkers(params Type[] types) { var serializer = new ServerComponentSerializer(_ephemeralDataProtectionProvider); var markers = new ServerComponentMarker[types.Length]; for (var i = 0; i < types.Length; i++) { markers[i] = serializer.SerializeInvocation(_invocationSequence, types[i], ParameterView.Empty, false); } return markers; } private ServerComponentMarker[] CreateMarkers(params (Type, Dictionary<string,object>)[] types) { var serializer = new ServerComponentSerializer(_ephemeralDataProtectionProvider); var markers = new ServerComponentMarker[types.Length]; for (var i = 0; i < types.Length; i++) { var (type, parameters) = types[i]; markers[i] = serializer.SerializeInvocation( _invocationSequence, type, parameters == null ? ParameterView.Empty : ParameterView.FromDictionary(parameters), false); } return markers; } private ServerComponentMarker[] CreateMarkers(ServerComponentInvocationSequence sequence, params Type[] types) { var serializer = new ServerComponentSerializer(_ephemeralDataProtectionProvider); var markers = new ServerComponentMarker[types.Length]; for (var i = 0; i < types.Length; i++) { markers[i] = serializer.SerializeInvocation(sequence, types[i], ParameterView.Empty, false); } return markers; } private class TestComponent : IComponent { public void Attach(RenderHandle renderHandle) => throw new NotImplementedException(); public Task SetParametersAsync(ParameterView parameters) => throw new NotImplementedException(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.CodeAnalysis; using Microsoft.Modeling; using Microsoft.Protocols.TestTools; namespace Microsoft.Protocol.TestSuites.Smb { /// <summary> /// TRANS2_QUERY_FILE_INFORMATION Response handler. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server /// that the client is accessing. /// </param> /// <param name="isSigned">Indicate whether the SUT has message signing enabled or required.</param> /// <param name="messageStatus"> /// Indicate that the status code returned from the SUT is success or failure. /// </param> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public delegate void Trans2QueryFileInfoResponseHandler( int messageId, int sessionId, int treeId, bool isSigned, MessageStatus messageStatus); /// <summary> /// TRANS2_QUERY_PATH_INFORMATION Response handler. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server /// that the client is accessing. /// </param> /// <param name="isSigned">Indicate whether the SUT has message signing enabled or required.</param> /// <param name="messageStatus"> /// Indicate that the status code returned from the SUT is success or failure. /// </param> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public delegate void Trans2QueryPathInfoResponseHandler( int messageId, int sessionId, int treeId, bool isSigned, MessageStatus messageStatus); /// <summary> /// TRANS2_QUERY_FS_INFORMATION Response handler. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server /// that the client is accessing. /// </param> /// <param name="isSigned">Indicate whether the SUT has message signing enabled or required.</param> /// <param name="messageStatus"> /// Indicate that the status code returned from the SUT is success or failure. /// </param> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public delegate void Trans2QueryFsInfoResponseHandler( int messageId, int sessionId, int treeId, bool isSigned, MessageStatus messageStatus); /// <summary> /// TRANS2_SET_FILE_INFORMATION Response handler. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server /// that the client is accessing. /// </param> /// <param name="isSigned">Indicate whether the SUT has message signing enabled or required.</param> /// <param name="messageStatus"> /// Indicate that the status code returned from the SUT is success or failure. /// </param> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public delegate void Trans2SetFileInfoResponseHandler( int messageId, int sessionId, int treeId, bool isSigned, MessageStatus messageStatus); /// <summary> /// TRANS2_SET_PATH_INFORMATION Response handler. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server /// that the client is accessing. /// </param> /// <param name="isSigned">Indicate whether the SUT has message signing enabled or required.</param> /// <param name="messageStatus"> /// Indicate that the status code returned from the SUT is success or failure. /// </param> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public delegate void Trans2SetPathInfoResponseHandler( int messageId, int sessionId, int treeId, bool isSigned, MessageStatus messageStatus); /// <summary> /// TRANS2_SET_FS_INFORMATION Response handler. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server /// that the client is accessing. /// </param> /// <param name="isSigned">Indicate whether the SUT has message signing enabled or required.</param> /// <param name="messageStatus"> /// Indicate that the status code returned from the SUT is success or failure. /// </param> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public delegate void Trans2SetFsInfoResponseHandler( int messageId, int sessionId, int treeId, bool isSigned, MessageStatus messageStatus); /// <summary> /// TRANS2_FIND_FIRST2 response handler. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server /// that the client is accessing. /// </param> /// <param name="isSigned">Indicate whether the SUT has message signing enabled or required.</param> /// <param name="isFileIdEqualZero">Indicate whether the fileId equals 0.</param> /// <param name="searchHandlerId">Search Handler.</param> /// <param name="returnEnumPreviousVersion"> /// Indicate whether the SUT will return the previous version. /// </param> /// <param name="messageStatus"> /// Indicate that the status code returned from the SUT is success or failure. /// </param> /// <param name="isRS2398Implemented">If the RS2398 implemented, it is true, else it is false.</param> /// <param name="isRS4899Implemented">If the RS4899 implemented, it is true, else it is false.</param> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public delegate void Trans2FindFirst2ResponseHandler( int messageId, int sessionId, int treeId, bool isSigned, bool isFileIdEqualZero, int searchHandlerId, bool returnEnumPreviousVersion, MessageStatus messageStatus, bool isRS2398Implemented, bool isRS4899Implemented); /// <summary> /// Trans2SetFSInfo Response additional handler. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously /// established session identifier to reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server that /// the client is accessing. /// </param> /// <param name="isSigned">Indicate whether the SUT has message signing enabled or required.</param> /// <param name="messageStatus"> /// Indicate that the status code returned from the SUT is success or failure. /// </param> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public delegate void Trans2SetFsInfoResponseAdditionalHandle( int messageId, int sessionId, int treeId, bool isSigned, MessageStatus messageStatus); /// <summary> /// ErrorTrans2SetFSInfo response additional handler. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="messageStatus"> /// Indicate that the status code returned from the SUT is success or failure. /// </param> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public delegate void ErrorTrans2SetFsInfoResponseAdditionalHandle(int messageId, MessageStatus messageStatus); /// <summary> /// TRANS2_FIND_NEXT2 Response handler. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously /// established session identifier to reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server that /// the client is accessing. /// </param> /// <param name="isSigned">Indicate whether the SUT has message signing enabled or required.</param> /// <param name="isFileIdEqualZero">Indicate whether the fileId equals 0.</param> /// <param name="messageStatus"> /// Indicate that the status code returned from the SUT is success or failure. /// </param> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public delegate void Trans2FindNext2ResponseHandler( int messageId, int sessionId, int treeId, bool isSigned, bool isFileIdEqualZero, MessageStatus messageStatus); #region FSCC methods /// <summary> /// FSCC Trans2 QueryPathInfo Response Handle /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously /// established session identifier to reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server that /// the client is accessing. /// </param> /// <param name="isSigned">Indicate whether the SUT has message signing enabled or required.</param> /// <param name="messageStatus"> /// Indicate that the status code returned from the SUT is success or failure. /// </param> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public delegate void FSCCTrans2QueryPathInfoResponseHandle( int messageId, int sessionId, int treeId, bool isSigned, MessageStatus messageStatus); /// <summary> /// TRANS2_QUERY_FS_INFORMATION Response handler /// </summary> /// <param name="messageId"> This is used to associate a response with a request.</param> /// <param name="sessionId"> Set this value to 0 to request a new session setup, or set this value to a /// previously established session identifier to reauthenticate to an existing session.</param> /// <param name="treeId"> This field identifies the subdirectory (or tree) (also referred to as a share in /// this document) on the server that the client is accessing.</param> /// <param name="isSigned"> Indicates whether the server has message signing enabled or required.</param> /// <param name="messageStatus"> Indicate the status code returned from server, success or fail.</param> public delegate void FSCCTrans2QueryFSInfoResponseHandle( int messageId, int sessionId, int treeId, bool isSigned, MessageStatus messageStatus); #endregion /// <summary> /// ISMBTransaction2 Adapter. /// </summary> public partial interface ISmbAdapter : IAdapter { /// <summary> /// TRANS2_QUERY_FILE_INFORMATION response. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event Trans2QueryFileInfoResponseHandler Trans2QueryFileInfoResponse; /// <summary> /// TRANS2_QUERY_PATH_INFORMATION response. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event Trans2QueryPathInfoResponseHandler Trans2QueryPathInfoResponse; /// <summary> /// TRANS2_QUERY_FS_INFORMATION response. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event Trans2QueryFsInfoResponseHandler Trans2QueryFsInfoResponse; /// <summary> /// TRANS2_SET_FILE_INFORMATION response. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event Trans2SetFileInfoResponseHandler Trans2SetFileInfoResponse; /// <summary> /// TRANS2_SET_PATH_INFORMATION response. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event Trans2SetPathInfoResponseHandler Trans2SetPathInfoResponse; /// <summary> /// TRANS2_SET_FS_INFORMATION response. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event Trans2SetFsInfoResponseHandler Trans2SetFsInfoResponse; /// <summary> /// TRANS2_FIND_FIRST2 response. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event Trans2FindFirst2ResponseHandler Trans2FindFirst2Response; /// <summary> /// TRANS2_FIND_NEXT2 response. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event Trans2FindNext2ResponseHandler Trans2FindNext2Response; /// <summary> /// Trans2SetFSInfo Response additional handler. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event Trans2SetFsInfoResponseAdditionalHandle Trans2SetFsInfoResponseAdditional; /// <summary> /// ErrorTrans2SetFSInfo response additional handler. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event ErrorTrans2SetFsInfoResponseAdditionalHandle ErrorTrans2SetFsInfoResponseAdditional; /// <summary> /// Check previous version. /// </summary> /// <param name="fid">The file identifier.</param> /// <param name="previousVersion">The previous version.</param> /// <param name="isSucceed">Indicate whether the checking is successful or not.</param> void CheckPreviousVersion(int fid, Microsoft.Modeling.Set<int> previousVersion, out bool isSucceed); /// <summary> /// TRANS2_QUERY_FILE_INFORMATION Request handler. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the /// server that the client is accessing. /// </param> /// <param name="isSigned"> /// Indicate whether the SUT has message signing enabled or required. /// </param> /// <param name="isUsePassthrough"> /// Indicate whether adding SMB_INFO_PASSTHROUGH in InformationLevel field of the request. /// </param> /// <param name="informationLevel">This can be used to query information from the server.</param> /// <param name="fid">The file identifier.</param> /// <param name="reserved">The reserved int value.</param> void Trans2QueryFileInfoRequest( int messageId, int sessionId, int treeId, bool isSigned, bool isUsePassthrough, [Domain("InfoLevelQueriedByFid")] InformationLevel informationLevel, int fid, int reserved); /// <summary> /// TRANS2_QUERY_FILE_INFORMATION Request. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the /// server that the client is accessing. /// </param> /// <param name="isSigned"> /// Indicate whether the SUT has message signing enabled or required. /// </param> /// <param name="isUsePassthrough"> /// Indicate whether adding SMB_INFO_PASSTHROUGH in InformationLevel field of the request. /// </param> /// <param name="isReparse">Indicate whether it is reparsed or not.</param> /// <param name="informationLevel">This can be used to query information from the server.</param> /// <param name="gmtTokenIndex">The index of the GMT token configured by CheckPreviousVersion action.</param> void Trans2QueryPathInfoRequest( int messageId, int sessionId, int treeId, bool isSigned, bool isUsePassthrough, bool isReparse, [Domain("InfoLevelQueriedByPath")] InformationLevel informationLevel, int gmtTokenIndex); /// <summary> /// TRANS2_QUERY_FS_INFORMATION Request. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the /// server that the client is accessing. /// </param> /// <param name="isSigned"> /// Indicate whether the SUT has message signing enabled or required. /// </param> /// <param name="isUsePassthrough"> /// Indicate whether adding SMB_INFO_PASSTHROUGH in InformationLevel field of the request. /// </param> /// <param name="informationLevel">This can be used to query information from the server.</param> /// <param name="otherBits">If it contains other bits.</param> /// <param name="reserved">The reserved int value.</param> void Trans2QueryFsInfoRequest( int messageId, int sessionId, int treeId, bool isSigned, bool isUsePassthrough, [Domain("InfoLevelQueriedByFS")] InformationLevel informationLevel, bool otherBits, int reserved); /// <summary> /// TRANS2_SET_FILE_INFORMATION Request. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the /// server that the client is accessing. /// </param> /// <param name="isSigned"> /// Indicate whether the SUT has message signing enabled or required. /// </param> /// <param name="relaceEnable"> /// Indicate whether the new name or link will replace the original one that exists already. /// </param> /// <param name="isUsePassthrough"> /// Indicate whether adding SMB_INFO_PASSTHROUGH in InformationLevel field of the request. /// </param> /// <param name="informationLevel">This can be used to query information from the server.</param> /// <param name="fid">The file identifier.</param> /// <param name="fileName">File name.</param> /// <param name="isRootDirecotyNull">Whether the root directory is null.</param> /// <param name="reserved">The reserved int value.</param> void Trans2SetFileInfoRequest( int messageId, int sessionId, int treeId, bool isSigned, bool relaceEnable, bool isUsePassthrough, [Domain("InfoLevelSetByFid")] InformationLevel informationLevel, int fid, string fileName, bool isRootDirecotyNull, int reserved); /// <summary> /// TRANS2_SET_PATH_INFORMATION Request. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the /// server that the client is accessing. /// </param> /// <param name="isSigned"> /// Indicate whether the SUT has message signing enabled or required. /// </param> /// <param name="isUsePassthrough"> /// Indicate whether adding SMB_INFO_PASSTHROUGH in InformationLevel field of the request. /// </param> /// <param name="isReparse">Indicate whether it is reparsed or not.</param> /// <param name="informationLevel">This can be used to query information from the server.</param> /// <param name="gmtTokenIndex">The index of the GMT token configured by CheckPreviousVersion action.</param> void Trans2SetPathInfoRequest( int messageId, int sessionId, int treeId, bool isSigned, bool isUsePassthrough, bool isReparse, [Domain("InfoLevelSetByPath")] InformationLevel informationLevel, int gmtTokenIndex); /// <summary> /// TRANS2_SET_FS_INFORMATION Request. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the /// server that the client is accessing. /// </param> /// <param name="isSigned"> /// Indicate whether the SUT has message signing enabled or required. /// </param> /// <param name="isUsePassthrough"> /// Indicate whether adding SMB_INFO_PASSTHROUGH in InformationLevel field of the request. /// </param> /// <param name="requireDisconnectTreeFlags">Indicate whether flags set to Disconnect_TID.</param> /// <param name="requireNoResponseFlags">Indicate whether flags set to NO_RESPONSE.</param> /// <param name="informationLevel">This can be used to query information from the server.</param> /// <param name="fid">The file identifier.</param> /// <param name="otherBits">If it contains other bits.</param> /// <param name="reserved">The reserved int value.</param> void Trans2SetFsInfoRequest( int messageId, int sessionId, int treeId, bool isSigned, bool isUsePassthrough, bool requireDisconnectTreeFlags, bool requireNoResponseFlags, InformationLevel informationLevel, int fid, bool otherBits, int reserved); /// <summary> /// TRANS2_FIND_FIRST2 Request. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the /// server that the client is accessing. /// </param> /// <param name="isSigned"> /// Indicate whether the SUT has message signing enabled or required. /// </param> /// <param name="isReparse">Indicate whether it is reparsed or not.</param> /// <param name="informationLevel">This can be used to query information from the server.</param> /// <param name="gmtTokenIndex">The index of the GMT token configured by CheckPreviousVersion action.</param> /// <param name="isFlagsKnowsLongNameSet"> /// Indicate the adpater to set the SMB_FLAGS2_KNOWS_LONG_NAMES flag in smb header or not. /// </param> /// <param name="isGmtPattern">Whether it is GMT pattern.</param> void Trans2FindFirst2Request( int messageId, int sessionId, int treeId, bool isSigned, bool isReparse, [Domain("InfoLevelByFind")] InformationLevel informationLevel, int gmtTokenIndex, bool isFlagsKnowsLongNameSet, bool isGmtPattern); /// <summary> /// TRANS2_FIND_FIRST2 Request for invalid directory token. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId">The current session ID for this connection.</param> /// <param name="treeId">The tree ID for the current share connection.</param> /// <param name="isSigned">Indicate whether the message is signed or not for this request.</param> /// <param name="isReparse"> /// Indicate whether the SMB_FLAGS2_REPARSE_PATH is set in the Flag2 field of the SMB header. /// </param> /// <param name="informationLevel"> The information level used for this request.</param> /// <param name="gmtTokenIndex"> The index of the GMT token configured by CheckPreviousVersion action.</param> /// <param name="isFlagsKnowsLongNameSet"> /// Indicate whether the SMB_FLAGS2_KNOWS_LONG_NAMES flag in SMB header is set or not. /// </param> /// <param name="isGmtPatten">Indicate whether the GMT Patten is used.</param> void Trans2FindFirst2RequestInvalidDirectoryToken( int messageId, int sessionId, int treeId, bool isSigned, bool isReparse, InformationLevel informationLevel, int gmtTokenIndex, bool isFlagsKnowsLongNameSet, bool isGmtPatten); /// <summary> /// TRANS2_FIND_FIRST2 Request for invalid file token. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId">The current session ID for this connection.</param> /// <param name="treeId">The tree ID for the current share connection.</param> /// <param name="isSigned">Indicate whether the message is signed or not for this request.</param> /// <param name="isReparse"> /// Indicate whether the SMB_FLAGS2_REPARSE_PATH is set in the Flag2 field of the SMB header. /// </param> /// <param name="informationLevel"> The information level used for this request.</param> /// <param name="gmtTokenIndex"> The index of the GMT token configured by CheckPreviousVersion action.</param> /// <param name="isFlagsKnowsLongNameSet"> /// Indicate whether the SMB_FLAGS2_KNOWS_LONG_NAMES flag in SMB header is set or not. /// </param> /// <param name="isGmtPatten"> Indicate whether the GMT Patten is used.</param> void Trans2FindFirst2RequestInvalidFileToken( int messageId, int sessionId, int treeId, bool isSigned, bool isReparse, InformationLevel informationLevel, int gmtTokenIndex, bool isFlagsKnowsLongNameSet, bool isGmtPatten); /// <summary> /// TRANS2_SET_FS_INFORMATION request additional. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a previously established session /// identifier to request reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the /// server that the client is accessing. /// </param> /// <param name="fid">The file identifier.</param> /// <param name="isSigned"> /// Indicate whether the SUT has message signing enabled or required. /// </param> /// <param name="informationLevel">This can be used to query information from the server.</param> /// <param name="requestPara">Trans2SetFSInfo response parameter.</param> void Trans2SetFsInfoRequestAdditional( int messageId, int sessionId, int treeId, int fid, bool isSigned, [Domain("InfoLevelSetByFS")] InformationLevel informationLevel, Trans2SetFsInfoResponseParameter requestPara); /// <summary> /// TRANS2_FIND_FIRST2 Request. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a /// previously established session identifier to reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server /// that the client is accessing. /// </param> /// <param name="isSigned"> /// Indicate whether the SUT has message signing enabled or required. /// </param> /// <param name="isReparse">Indicate whether it is reparsed or not.</param> /// <param name="informationLevel">This can be used to query information from the server.</param> /// <param name="sid">The sid.</param> /// <param name="gmtTokenIndex">The index of the GMT token configured by CheckPreviousVersion action.</param> /// <param name="isFlagsKnowsLongNameSet"> /// Indicate the adpater to set the SMB_FLAGS2_KNOWS_LONG_NAMES flag in smb header or not. /// </param> void Trans2FindNext2Request( int messageId, int sessionId, int treeId, bool isSigned, bool isReparse, [Domain("InfoLevelByFind")] InformationLevel informationLevel, int sid, int gmtTokenIndex, bool isFlagsKnowsLongNameSet); #region FSCC methods /// <summary> /// FSCC TRANS2_QUERY_PATH_INFORMATION Request. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a /// previously established session identifier to reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server /// that the client is accessing. /// </param> /// <param name="isSigned"> /// Indicate whether the SUT has message signing enabled or required. /// </param> /// <param name="informationLevel">Indicate the query path info level</param> void FSCCTrans2QueryPathInfoRequest( int messageId, int sessionId, int treeId, bool isSigned, FSCCTransaction2QueryPathInforLevel informationLevel); /// <summary> /// FSCC TRANS2_QUERY_PATH_INFORMATION response. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event FSCCTrans2QueryPathInfoResponseHandle FSCCTrans2QueryPathInfoResponse; /// <summary> /// FSCC TRANS2_QUERY_FS_INFORMATION response. /// </summary> /// Disable warning CA1009 because according to Test Case design, /// the two parameters, System.Object and System.EventArgs, are unnecessary. [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] event FSCCTrans2QueryFSInfoResponseHandle FSCCTrans2QueryFSInfoResponse; /// <summary> /// FSCC TRANS2_QUERY_FS_INFORMATION Request. /// </summary> /// <param name="messageId">This is used to associate a response with a request.</param> /// <param name="sessionId"> /// Set this value to 0 to request a new session setup, or set this value to a /// previously established session identifier to reauthenticate to an existing session. /// </param> /// <param name="treeId"> /// This field identifies the subdirectory (or tree) (also referred as a share in this document) on the server /// that the client is accessing. /// </param> /// <param name="isSigned"> /// Indicate whether the SUT has message signing enabled or required. /// </param> /// <param name="informationLevel">Indicate the query FS info level</param> void FSCCTrans2QueryFSInfoRequest(int messageId, int sessionId, int treeId, bool isSigned, FSCCTransaction2QueryFSInforLevel informationLevel); #endregion } }
namespace Ioke.Lang.Parser { using System.IO; using System.Collections; using System.Text; using Ioke.Lang; using Ioke.Lang.Util; public class IokeParser { private readonly Runtime runtime; private readonly TextReader reader; private readonly IokeObject context; private readonly IokeObject message; public IokeParser(Runtime runtime, TextReader reader, IokeObject context, IokeObject message) { this.runtime = runtime; this.reader = reader; this.context = context; this.message = message; } public IokeObject ParseFully() { IokeObject result = parseExpressions(); return result; } private IokeObject parseExpressions() { IokeObject c = null; IokeObject last = null; IokeObject head = null; while((c = parseExpression()) != null) { if(head == null) { head = c; last = c; } else { Message.SetNext(last, c); Message.SetPrev(c, last); last = c; } } if(head != null) { while(Message.IsTerminator(head) && Message.GetNext(head) != null) { head = Message.GetNext(head); Message.SetPrev(head, null); } } return head; } private IList parseExpressionChain() { ArrayList chain = new SaneArrayList(); IokeObject curr = parseExpressions(); while(curr != null) { chain.Add(curr); readWhiteSpace(); int rr = peek(); if(rr == ',') { read(); curr = parseExpressions(); if(curr == null) { fail("Expected expression following comma"); } } else { if(curr != null && Message.IsTerminator(curr) && Message.GetNext(curr) == null) { chain.RemoveAt(chain.Count-1); } curr = null; } } return chain; } private int lineNumber = 1; private int currentCharacter = -1; private bool skipLF = false; private int saved2 = -2; private int saved = -2; private int read() { if(saved > -2) { int x = saved; saved = saved2; saved2 = -2; if(skipLF) { skipLF = false; if(x == '\n') { return x; } } currentCharacter++; switch(x) { case '\r': skipLF = true; goto case '\n'; case '\n': /* Fall through */ lineNumber++; currentCharacter = 0; break; } return x; } int xx = reader.Read(); if(skipLF) { skipLF = false; if(xx == '\n') { return xx; } } currentCharacter++; switch(xx) { case '\r': skipLF = true; goto case '\n'; case '\n': /* Fall through */ lineNumber++; currentCharacter = 0; break; } return xx; } private int peek() { if(saved == -2) { if(saved2 != -2) { saved = saved2; saved2 = -2; } else { saved = reader.Read(); } } return saved; } private int peek2() { if(saved == -2) { saved = reader.Read(); } if(saved2 == -2) { saved2 = reader.Read(); } return saved2; } private IokeObject parseExpression() { int rr; while(true) { rr = peek(); switch(rr) { case -1: read(); return null; case ',': goto case '}'; case ')': goto case '}'; case ']': goto case '}'; case '}': return null; case '(': read(); return parseEmptyMessageSend(); case '[': read(); return parseSquareMessageSend(); case '{': read(); return parseCurlyMessageSend(); case '#': read(); switch(peek()) { case '{': return parseSetMessageSend(); case '/': return parseRegexpLiteral('/'); case '[': return parseText('['); case 'r': return parseRegexpLiteral('r'); case '!': parseComment(); break; default: return parseOperatorChars('#'); } break; case '"': read(); return parseText('"'); case '0': goto case '9'; case '1': goto case '9'; case '2': goto case '9'; case '3': goto case '9'; case '4': goto case '9'; case '5': goto case '9'; case '6': goto case '9'; case '7': goto case '9'; case '8': goto case '9'; case '9': read(); return parseNumber(rr); case '.': read(); if((rr = peek()) == '.') { return parseRange(); } else { return parseTerminator('.'); } case ';': read(); parseComment(); break; case ' ': goto case '\u000c'; case '\u0009': goto case '\u000c'; case '\u000b': goto case '\u000c'; case '\u000c': read(); readWhiteSpace(); break; case '\\': read(); if((rr = peek()) == '\n') { read(); break; } else { fail("Expected newline after free-floating escape character"); } break; case '\r': goto case '\n'; case '\n': read(); return parseTerminator(rr); case '+': goto case '/'; case '-': goto case '/'; case '*': goto case '/'; case '%': goto case '/'; case '<': goto case '/'; case '>': goto case '/'; case '!': goto case '/'; case '?': goto case '/'; case '~': goto case '/'; case '&': goto case '/'; case '|': goto case '/'; case '^': goto case '/'; case '$': goto case '/'; case '=': goto case '/'; case '@': goto case '/'; case '\'': goto case '/'; case '`': goto case '/'; case '/': read(); return parseOperatorChars(rr); case ':': read(); if(isLetter(rr = peek()) || isIDDigit(rr)) { return parseRegularMessageSend(':'); } else { return parseOperatorChars(':'); } default: read(); return parseRegularMessageSend(rr); } } } private void fail(int l, int c, string message, string expected, string got) { string file = ((IokeSystem)IokeObject.dataOf(runtime.System)).CurrentFile; IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, this.message, this.context, "Error", "Parser", "Syntax"), this.context).Mimic(this.message, this.context); condition.SetCell("message", this.message); condition.SetCell("context", this.context); condition.SetCell("receiver", this.context); if(expected != null) { condition.SetCell("expected", runtime.NewText(expected)); } if(got != null) { condition.SetCell("got", runtime.NewText(got)); } condition.SetCell("file", runtime.NewText(file)); condition.SetCell("line", runtime.NewNumber(l)); condition.SetCell("character", runtime.NewNumber(c)); condition.SetCell("text", runtime.NewText(file + ":" + l + ":" + c + ": " + message)); runtime.ErrorCondition(condition); } private void fail(string message) { fail(lineNumber, currentCharacter, message, null, null); } private void parseCharacter(int c) { int l = lineNumber; int cc = currentCharacter; readWhiteSpace(); int rr = read(); if(rr != c) { fail(l, cc, "Expected: '" + (char)c + "' got: " + charDesc(rr), "" + (char)c, charDesc(rr)); } } private IokeObject parseEmptyMessageSend() { int l = lineNumber; int cc = currentCharacter-1; IList args = parseExpressionChain(); parseCharacter(')'); Message m = new Message(runtime, ""); m.Line = l; m.Position = cc; IokeObject mx = runtime.CreateMessage(m); Message.SetArguments(mx, args); return mx; } private IokeObject parseSquareMessageSend() { int l = lineNumber; int cc = currentCharacter-1; int rr = peek(); int r2 = peek2(); Message m = new Message(runtime, "[]"); m.Line = l; m.Position = cc; IokeObject mx = runtime.CreateMessage(m); if(rr == ']' && r2 == '(') { read(); read(); IList args = parseExpressionChain(); parseCharacter(')'); Message.SetArguments(mx, args); } else { IList args = parseExpressionChain(); parseCharacter(']'); Message.SetArguments(mx, args); } return mx; } private IokeObject parseCurlyMessageSend() { int l = lineNumber; int cc = currentCharacter-1; int rr = peek(); int r2 = peek2(); Message m = new Message(runtime, "{}"); m.Line = l; m.Position = cc; IokeObject mx = runtime.CreateMessage(m); if(rr == '}' && r2 == '(') { read(); read(); IList args = parseExpressionChain(); parseCharacter(')'); Message.SetArguments(mx, args); } else { IList args = parseExpressionChain(); parseCharacter('}'); Message.SetArguments(mx, args); } return mx; } private IokeObject parseSetMessageSend() { int l = lineNumber; int cc = currentCharacter-1; parseCharacter('{'); IList args = parseExpressionChain(); parseCharacter('}'); Message m = new Message(runtime, "set"); m.Line = l; m.Position = cc; IokeObject mx = runtime.CreateMessage(m); Message.SetArguments(mx, args); return mx; } private void parseComment() { int rr; while((rr = peek()) != '\n' && rr != '\r' && rr != -1) { read(); } } private readonly static string[] RANGES = { "", ".", "..", "...", "....", ".....", "......", ".......", "........", ".........", "..........", "...........", "............" }; private IokeObject parseRange() { int l = lineNumber; int cc = currentCharacter-1; int count = 2; read(); while(peek() == '.') { count++; read(); } string result = null; if(count < 13) { result = RANGES[count]; } else { StringBuilder sb = new StringBuilder(); for(int i = 0; i<count; i++) { sb.Append('.'); } result = sb.ToString(); } Message m = new Message(runtime, result); m.Line = l; m.Position = cc; return runtime.CreateMessage(m); } private IokeObject parseTerminator(int indicator) { int l = lineNumber; int cc = currentCharacter-1; int rr; int rr2; if(indicator == '\r') { rr = peek(); if(rr == '\n') { read(); } } while(true) { rr = peek(); rr2 = peek2(); if((rr == '.' && rr2 != '.') || (rr == '\n')) { read(); } else if(rr == '\r' && rr2 == '\n') { read(); read(); } else { break; } } Message m = new Message(runtime, ".", null, true); m.Line = l; m.Position = cc; return runtime.CreateMessage(m); } private void readWhiteSpace() { int rr; while((rr = peek()) == ' ' || rr == '\u0009' || rr == '\u000b' || rr == '\u000c') { read(); } } private IokeObject parseRegexpLiteral(int indicator) { StringBuilder sb = new StringBuilder(); bool slash = indicator == '/'; int l = lineNumber; int cc = currentCharacter-1; read(); if(!slash) { parseCharacter('['); } int rr; string name = "internal:createRegexp"; ArrayList args = new SaneArrayList(); while(true) { switch(rr = peek()) { case -1: fail("Expected end of regular expression, found EOF"); break; case '/': read(); if(slash) { args.Add(sb.ToString()); Message m = new Message(runtime, "internal:createRegexp"); m.Line = l; m.Position = cc; IokeObject mm = runtime.CreateMessage(m); if(!name.Equals("internal:createRegexp")) { Message.SetName(mm, name); } Message.SetArguments(mm, args); sb = new StringBuilder(); while(true) { switch(rr = peek()) { case 'x': case 'i': case 'u': case 'm': case 's': read(); sb.Append((char)rr); break; default: args.Add(sb.ToString()); return mm; } } } else { sb.Append((char)rr); } break; case ']': read(); if(!slash) { args.Add(sb.ToString()); Message m = new Message(runtime, "internal:createRegexp"); m.Line = l; m.Position = cc; IokeObject mm = runtime.CreateMessage(m); if(!name.Equals("internal:createRegexp")) { Message.SetName(mm, name); } Message.SetArguments(mm, args); sb = new StringBuilder(); while(true) { switch(rr = peek()) { case 'x': case 'i': case 'u': case 'm': case 's': read(); sb.Append((char)rr); break; default: args.Add(sb.ToString()); //System.err.println("-parseRegexpLiteral()"); return mm; } } } else { sb.Append((char)rr); } break; case '#': read(); if((rr = peek()) == '{') { read(); args.Add(sb.ToString()); sb = new StringBuilder(); name = "internal:compositeRegexp"; args.Add(parseExpressions()); readWhiteSpace(); parseCharacter('}'); } else { sb.Append((char)'#'); } break; case '\\': read(); parseRegexpEscape(sb); break; default: read(); sb.Append((char)rr); break; } } } private IokeObject parseText(int indicator) { StringBuilder sb = new StringBuilder(); bool dquote = indicator == '"'; int l = lineNumber; int cc = currentCharacter-1; if(!dquote) { read(); } int rr; string name = "internal:createText"; ArrayList args = new SaneArrayList(); while(true) { switch(rr = peek()) { case -1: fail("Expected end of text, found EOF"); break; case '"': read(); if(dquote) { args.Add(sb.ToString()); Message m = new Message(runtime, "internal:createText"); m.Line = l; m.Position = cc; IokeObject mm = runtime.CreateMessage(m); if(!name.Equals("internal:createText")) { for(int i = 0; i<args.Count; i++) { object o = args[i]; if(o is string) { Message mx = new Message(runtime, "internal:createText", o); mx.Line = l; mx.Position = cc; IokeObject mmx = runtime.CreateMessage(mx); args[i] = mmx; } } Message.SetName(mm, name); } Message.SetArguments(mm, args); return mm; } else { sb.Append((char)rr); } break; case ']': read(); if(!dquote) { args.Add(sb.ToString()); Message m = new Message(runtime, "internal:createText"); m.Line = l; m.Position = cc; IokeObject mm = runtime.CreateMessage(m); if(!name.Equals("internal:createText")) { for(int i = 0; i<args.Count; i++) { object o = args[i]; if(o is string) { Message mx = new Message(runtime, "internal:createText", o); mx.Line = l; mx.Position = cc; IokeObject mmx = runtime.CreateMessage(mx); args[i] = mmx; } } Message.SetName(mm, name); } Message.SetArguments(mm, args); return mm; } else { sb.Append((char)rr); } break; case '#': read(); if((rr = peek()) == '{') { read(); args.Add(sb.ToString()); sb = new StringBuilder(); name = "internal:concatenateText"; args.Add(parseExpressions()); readWhiteSpace(); parseCharacter('}'); } else { sb.Append((char)'#'); } break; case '\\': read(); parseDoubleQuoteEscape(sb); break; default: read(); sb.Append((char)rr); break; } } } private void parseRegexpEscape(StringBuilder sb) { sb.Append('\\'); int rr = peek(); switch(rr) { case 'u': read(); sb.Append((char)rr); for(int i = 0; i < 4; i++) { rr = peek(); if((rr >= '0' && rr <= '9') || (rr >= 'a' && rr <= 'f') || (rr >= 'A' && rr <= 'F')) { read(); sb.Append((char)rr); } else { fail("Expected four hexadecimal characters in unicode escape - got: " + charDesc(rr)); } } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': read(); sb.Append((char)rr); if(rr <= '3') { rr = peek(); if(rr >= '0' && rr <= '7') { read(); sb.Append((char)rr); rr = peek(); if(rr >= '0' && rr <= '7') { read(); sb.Append((char)rr); } } } else { rr = peek(); if(rr >= '0' && rr <= '7') { read(); sb.Append((char)rr); } } break; case 't': case 'n': case 'f': case 'r': case '/': case '\\': case '\n': case '#': case 'A': case 'd': case 'D': case 's': case 'S': case 'w': case 'W': case 'b': case 'B': case 'z': case 'Z': case '<': case '>': case 'G': case 'p': case 'P': case '{': case '}': case '[': case ']': case '*': case '(': case ')': case '$': case '^': case '+': case '?': case '.': case '|': read(); sb.Append((char)rr); break; case '\r': read(); sb.Append((char)rr); if((rr = peek()) == '\n') { read(); sb.Append((char)rr); } break; default: fail("Undefined regular expression escape character: " + charDesc(rr)); break; } } private void parseDoubleQuoteEscape(StringBuilder sb) { sb.Append('\\'); int rr = peek(); switch(rr) { case 'u': read(); sb.Append((char)rr); for(int i = 0; i < 4; i++) { rr = peek(); if((rr >= '0' && rr <= '9') || (rr >= 'a' && rr <= 'f') || (rr >= 'A' && rr <= 'F')) { read(); sb.Append((char)rr); } else { fail("Expected four hexadecimal characters in unicode escape - got: " + charDesc(rr)); } } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': read(); sb.Append((char)rr); if(rr <= '3') { rr = peek(); if(rr >= '0' && rr <= '7') { read(); sb.Append((char)rr); rr = peek(); if(rr >= '0' && rr <= '7') { read(); sb.Append((char)rr); } } } else { rr = peek(); if(rr >= '0' && rr <= '7') { read(); sb.Append((char)rr); } } break; case 'b': case 't': case 'n': case 'f': case 'r': case '"': case ']': case '\\': case '\n': case '#': case 'e': read(); sb.Append((char)rr); break; case '\r': read(); sb.Append((char)rr); if((rr = peek()) == '\n') { read(); sb.Append((char)rr); } break; default: fail("Undefined text escape character: " + charDesc(rr)); break; } } private IokeObject parseOperatorChars(int indicator) { int l = lineNumber; int cc = currentCharacter-1; StringBuilder sb = new StringBuilder(); sb.Append((char)indicator); int rr; if(indicator == '#') { while(true) { rr = peek(); switch(rr) { case '+': case '-': case '*': case '%': case '<': case '>': case '!': case '?': case '~': case '&': case '|': case '^': case '$': case '=': case '@': case '\'': case '`': case ':': case '#': read(); sb.Append((char)rr); break; default: Message m = new Message(runtime, sb.ToString()); m.Line = l; m.Position = cc; IokeObject mx = runtime.CreateMessage(m); if(rr == '(') { read(); IList args = parseExpressionChain(); parseCharacter(')'); Message.SetArguments(mx, args); } return mx; } } } else { while(true) { rr = peek(); switch(rr) { case '+': case '-': case '*': case '%': case '<': case '>': case '!': case '?': case '~': case '&': case '|': case '^': case '$': case '=': case '@': case '\'': case '`': case '/': case ':': case '#': read(); sb.Append((char)rr); break; default: Message m = new Message(runtime, sb.ToString()); m.Line = l; m.Position = cc; IokeObject mx = runtime.CreateMessage(m); if(rr == '(') { read(); IList args = parseExpressionChain(); parseCharacter(')'); Message.SetArguments(mx, args); } return mx; } } } } private IokeObject parseNumber(int indicator) { int l = lineNumber; int cc = currentCharacter-1; bool isdecimal = false; StringBuilder sb = new StringBuilder(); sb.Append((char)indicator); int rr = -1; if(indicator == '0') { rr = peek(); if(rr == 'x' || rr == 'X') { read(); sb.Append((char)rr); rr = peek(); if((rr >= '0' && rr <= '9') || (rr >= 'a' && rr <= 'f') || (rr >= 'A' && rr <= 'F')) { read(); sb.Append((char)rr); rr = peek(); while((rr >= '0' && rr <= '9') || (rr >= 'a' && rr <= 'f') || (rr >= 'A' && rr <= 'F')) { read(); sb.Append((char)rr); rr = peek(); } } else { fail("Expected at least one hexadecimal characters in hexadecimal number literal - got: " + charDesc(rr)); } } else { int r2 = peek2(); if(rr == '.' && (r2 >= '0' && r2 <= '9')) { isdecimal = true; sb.Append((char)rr); sb.Append((char)r2); read(); read(); while((rr = peek()) >= '0' && rr <= '9') { read(); sb.Append((char)rr); } if(rr == 'e' || rr == 'E') { read(); sb.Append((char)rr); if((rr = peek()) == '-' || rr == '+') { read(); sb.Append((char)rr); rr = peek(); } if(rr >= '0' && rr <= '9') { read(); sb.Append((char)rr); while((rr = peek()) >= '0' && rr <= '9') { read(); sb.Append((char)rr); } } else { fail("Expected at least one decimal character following exponent specifier in number literal - got: " + charDesc(rr)); } } } } } else { while((rr = peek()) >= '0' && rr <= '9') { read(); sb.Append((char)rr); } int r2 = peek2(); if(rr == '.' && r2 >= '0' && r2 <= '9') { isdecimal = true; sb.Append((char)rr); sb.Append((char)r2); read(); read(); while((rr = peek()) >= '0' && rr <= '9') { read(); sb.Append((char)rr); } if(rr == 'e' || rr == 'E') { read(); sb.Append((char)rr); if((rr = peek()) == '-' || rr == '+') { read(); sb.Append((char)rr); rr = peek(); } if(rr >= '0' && rr <= '9') { read(); sb.Append((char)rr); while((rr = peek()) >= '0' && rr <= '9') { read(); sb.Append((char)rr); } } else { fail("Expected at least one decimal character following exponent specifier in number literal - got: " + charDesc(rr)); } } } else if(rr == 'e' || rr == 'E') { isdecimal = true; read(); sb.Append((char)rr); if((rr = peek()) == '-' || rr == '+') { read(); sb.Append((char)rr); rr = peek(); } if(rr >= '0' && rr <= '9') { read(); sb.Append((char)rr); while((rr = peek()) >= '0' && rr <= '9') { read(); sb.Append((char)rr); } } else { fail("Expected at least one decimal character following exponent specifier in number literal - got: " + charDesc(rr)); } } } // TODO: add unit specifier here Message m = isdecimal ? new Message(runtime, "internal:createDecimal", sb.ToString()) : new Message(runtime, "internal:createNumber", sb.ToString()); m.Line = l; m.Position = cc; return runtime.CreateMessage(m); } private IokeObject parseRegularMessageSend(int indicator) { int l = lineNumber; int cc = currentCharacter-1; StringBuilder sb = new StringBuilder(); sb.Append((char)indicator); int rr = -1; while(isLetter(rr = peek()) || isIDDigit(rr) || rr == ':' || rr == '!' || rr == '?' || rr == '$') { read(); sb.Append((char)rr); } Message m = new Message(runtime, sb.ToString()); m.Line = l; m.Position = cc; IokeObject mx = runtime.CreateMessage(m); if(rr == '(') { read(); IList args = parseExpressionChain(); parseCharacter(')'); Message.SetArguments(mx, args); } return mx; } private bool isLetter(int c) { return ((c>='A' && c<='Z') || c=='_' || (c>='a' && c<='z') || (c>='\u00C0' && c<='\u00D6') || (c>='\u00D8' && c<='\u00F6') || (c>='\u00F8' && c<='\u1FFF') || (c>='\u2200' && c<='\u22FF') || (c>='\u27C0' && c<='\u27EF') || (c>='\u2980' && c<='\u2AFF') || (c>='\u3040' && c<='\u318F') || (c>='\u3300' && c<='\u337F') || (c>='\u3400' && c<='\u3D2D') || (c>='\u4E00' && c<='\u9FFF') || (c>='\uF900' && c<='\uFAFF')); } private bool isIDDigit(int c) { return ((c>='0' && c<='9') || (c>='\u0660' && c<='\u0669') || (c>='\u06F0' && c<='\u06F9') || (c>='\u0966' && c<='\u096F') || (c>='\u09E6' && c<='\u09EF') || (c>='\u0A66' && c<='\u0A6F') || (c>='\u0AE6' && c<='\u0AEF') || (c>='\u0B66' && c<='\u0B6F') || (c>='\u0BE7' && c<='\u0BEF') || (c>='\u0C66' && c<='\u0C6F') || (c>='\u0CE6' && c<='\u0CEF') || (c>='\u0D66' && c<='\u0D6F') || (c>='\u0E50' && c<='\u0E59') || (c>='\u0ED0' && c<='\u0ED9') || (c>='\u1040' && c<='\u1049')); } private static string charDesc(int c) { if(c == -1) { return "EOF"; } else if(c == 9) { return "TAB"; } else if(c == 10 || c == 13) { return "EOL"; } else { return "'" + (char)c + "'"; } } } }
namespace Orleans.CodeGenerator { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Runtime; using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Code generator which generates <see cref="IGrainMethodInvoker"/> for grains. /// </summary> internal static class GrainMethodInvokerGenerator { /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "MethodInvoker"; /// <summary> /// Returns the name of the generated class for the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>The name of the generated class for the provided type.</returns> internal static string GetGeneratedClassName(Type type) => CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(type) + ClassSuffix; /// <summary> /// Generates the class for the provided grain types. /// </summary> /// <param name="grainType">The grain interface type.</param> /// <param name="className">The name for the generated class.</param> /// <returns> /// The generated class. /// </returns> internal static TypeDeclarationSyntax GenerateClass(Type grainType, string className) { var baseTypes = new List<BaseTypeSyntax> { SF.SimpleBaseType(typeof(IGrainMethodInvoker).GetTypeSyntax()) }; var grainTypeInfo = grainType.GetTypeInfo(); var genericTypes = grainTypeInfo.IsGenericTypeDefinition ? grainType.GetGenericArguments() .Select(_ => SF.TypeParameter(_.ToString())) .ToArray() : new TypeParameterSyntax[0]; // Create the special method invoker marker attribute. var interfaceId = GrainInterfaceUtils.GetGrainInterfaceId(grainType); var interfaceIdArgument = SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId)); var grainTypeArgument = SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false)); var attributes = new List<AttributeSyntax> { CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(MethodInvokerAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(grainTypeArgument), SF.AttributeArgument(interfaceIdArgument)), SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()) }; var members = new List<MemberDeclarationSyntax>(GenerateGenericInvokerFields(grainType)) { GenerateInvokeMethod(grainType), GenerateInterfaceIdProperty(grainType), GenerateInterfaceVersionProperty(grainType), }; // If this is an IGrainExtension, make the generated class implement IGrainExtensionMethodInvoker. if (typeof(IGrainExtension).GetTypeInfo().IsAssignableFrom(grainTypeInfo)) { baseTypes.Add(SF.SimpleBaseType(typeof(IGrainExtensionMethodInvoker).GetTypeSyntax())); members.Add(GenerateExtensionInvokeMethod(grainType)); } var classDeclaration = SF.ClassDeclaration(className) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddBaseListTypes(baseTypes.ToArray()) .AddConstraintClauses(grainType.GetTypeConstraintSyntax()) .AddMembers(members.ToArray()) .AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray())); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } return classDeclaration; } /// <summary> /// Returns method declaration syntax for the InterfaceId property. /// </summary> /// <param name="grainType">The grain type.</param> /// <returns>Method declaration syntax for the InterfaceId property.</returns> private static MemberDeclarationSyntax GenerateInterfaceIdProperty(Type grainType) { var property = TypeUtils.Member((IGrainMethodInvoker _) => _.InterfaceId); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceId(grainType))); return SF.PropertyDeclaration(typeof(int).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)); } private static MemberDeclarationSyntax GenerateInterfaceVersionProperty(Type grainType) { var property = TypeUtils.Member((IGrainMethodInvoker _) => _.InterfaceVersion); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceVersion(grainType))); return SF.PropertyDeclaration(typeof(ushort).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)); } /// <summary> /// Generates syntax for the <see cref="IGrainMethodInvoker.Invoke"/> method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <returns> /// Syntax for the <see cref="IGrainMethodInvoker.Invoke"/> method. /// </returns> private static MethodDeclarationSyntax GenerateInvokeMethod(Type grainType) { // Get the method with the correct type. var invokeMethod = TypeUtils.Method( (IGrainMethodInvoker x) => x.Invoke(default(IAddressable), default(InvokeMethodRequest))); return GenerateInvokeMethod(grainType, invokeMethod); } /// <summary> /// Generates syntax for the <see cref="IGrainExtensionMethodInvoker"/> invoke method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <returns> /// Syntax for the <see cref="IGrainExtensionMethodInvoker"/> invoke method. /// </returns> private static MethodDeclarationSyntax GenerateExtensionInvokeMethod(Type grainType) { // Get the method with the correct type. var invokeMethod = TypeUtils.Method( (IGrainExtensionMethodInvoker x) => x.Invoke(default(IGrainExtension), default(InvokeMethodRequest))); return GenerateInvokeMethod(grainType, invokeMethod); } /// <summary> /// Generates syntax for an invoke method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <param name="invokeMethod"> /// The invoke method to generate. /// </param> /// <returns> /// Syntax for an invoke method. /// </returns> private static MethodDeclarationSyntax GenerateInvokeMethod(Type grainType, MethodInfo invokeMethod) { var parameters = invokeMethod.GetParameters(); var grainArgument = parameters[0].Name.ToIdentifierName(); var requestArgument = parameters[1].Name.ToIdentifierName(); // Store the relevant values from the request in local variables. var interfaceIdDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(int).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("interfaceId") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.InterfaceId))))); var interfaceIdVariable = SF.IdentifierName("interfaceId"); var methodIdDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(int).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("methodId") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.MethodId))))); var methodIdVariable = SF.IdentifierName("methodId"); var argumentsDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(object[]).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("arguments") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.Arguments))))); var argumentsVariable = SF.IdentifierName("arguments"); var methodDeclaration = invokeMethod.GetDeclarationSyntax() .AddModifiers(SF.Token(SyntaxKind.AsyncKeyword)) .AddBodyStatements(interfaceIdDeclaration, methodIdDeclaration, argumentsDeclaration); var interfaceCases = CodeGeneratorCommon.GenerateGrainInterfaceAndMethodSwitch( grainType, methodIdVariable, methodType => GenerateInvokeForMethod(grainType, grainArgument, methodType, argumentsVariable)); // Generate the default case, which will throw a NotImplementedException. var errorMessage = SF.BinaryExpression( SyntaxKind.AddExpression, "interfaceId=".GetLiteralExpression(), interfaceIdVariable); var throwStatement = SF.ThrowStatement( SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(errorMessage))); var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement); var interfaceIdSwitch = SF.SwitchStatement(interfaceIdVariable).AddSections(interfaceCases.ToArray()).AddSections(defaultCase); // If the provided grain is null, throw an argument exception. var argumentNullException = SF.ObjectCreationExpression(typeof(ArgumentNullException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(parameters[0].Name.GetLiteralExpression())); var grainArgumentCheck = SF.IfStatement( SF.BinaryExpression( SyntaxKind.EqualsExpression, grainArgument, SF.LiteralExpression(SyntaxKind.NullLiteralExpression)), SF.ThrowStatement(argumentNullException)); return methodDeclaration.AddBodyStatements(grainArgumentCheck, interfaceIdSwitch); } /// <summary> /// Generates syntax to invoke a method on a grain. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <param name="grain"> /// The grain instance expression. /// </param> /// <param name="method"> /// The method. /// </param> /// <param name="arguments"> /// The arguments expression. /// </param> /// <returns> /// Syntax to invoke a method on a grain. /// </returns> private static StatementSyntax[] GenerateInvokeForMethod( Type grainType, IdentifierNameSyntax grain, MethodInfo method, ExpressionSyntax arguments) { var castGrain = SF.ParenthesizedExpression(SF.CastExpression(grainType.GetTypeSyntax(), grain)); // Construct expressions to retrieve each of the method's parameters. var parameters = new List<ExpressionSyntax>(); var methodParameters = method.GetParameters().ToList(); for (var i = 0; i < methodParameters.Count; i++) { var parameter = methodParameters[i]; var parameterType = parameter.ParameterType.GetTypeSyntax(); var indexArg = SF.Argument(SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(i))); var arg = SF.CastExpression( parameterType, SF.ElementAccessExpression(arguments).AddArgumentListArguments(indexArg)); parameters.Add(arg); } // If the method is a generic method definition, use the generic method invoker field to invoke the method. if (method.IsGenericMethodDefinition) { var invokerFieldName = GetGenericMethodInvokerFieldName(method); var invokerCall = SF.InvocationExpression( SF.IdentifierName(invokerFieldName) .Member((GenericMethodInvoker invoker) => invoker.Invoke(null, null))) .AddArgumentListArguments(SF.Argument(grain), SF.Argument(arguments)); return new StatementSyntax[] { SF.ReturnStatement(SF.AwaitExpression(invokerCall)) }; } // Invoke the method. var grainMethodCall = SF.InvocationExpression(castGrain.Member(method.Name)) .AddArgumentListArguments(parameters.Select(SF.Argument).ToArray()); // For void methods, invoke the method and return null. if (method.ReturnType == typeof(void)) { return new StatementSyntax[] { SF.ExpressionStatement(grainMethodCall), SF.ReturnStatement(SF.LiteralExpression(SyntaxKind.NullLiteralExpression)) }; } // For methods which return non-generic Task, await the method and return null. if (method.ReturnType == typeof(Task)) { return new StatementSyntax[] { SF.ExpressionStatement(SF.AwaitExpression(grainMethodCall)), SF.ReturnStatement(SF.LiteralExpression(SyntaxKind.NullLiteralExpression)) }; } return new StatementSyntax[] { SF.ReturnStatement(SF.AwaitExpression(grainMethodCall)) }; } /// <summary> /// Generates <see cref="GenericMethodInvoker"/> fields for the generic methods in <paramref name="grainType"/>. /// </summary> /// <param name="grainType">The grain type.</param> /// <returns>The generated fields.</returns> private static MemberDeclarationSyntax[] GenerateGenericInvokerFields(Type grainType) { var methods = GrainInterfaceUtils.GetMethods(grainType); var result = new List<MemberDeclarationSyntax>(); foreach (var method in methods) { if (!method.IsGenericMethodDefinition) continue; result.Add(GenerateGenericInvokerField(method)); } return result.ToArray(); } /// <summary> /// Generates a <see cref="GenericMethodInvoker"/> field for the provided generic method. /// </summary> /// <param name="method">The method.</param> /// <returns>The generated field.</returns> private static MemberDeclarationSyntax GenerateGenericInvokerField(MethodInfo method) { var fieldInfoVariable = SF.VariableDeclarator(GetGenericMethodInvokerFieldName(method)) .WithInitializer( SF.EqualsValueClause( SF.ObjectCreationExpression(typeof(GenericMethodInvoker).GetTypeSyntax()) .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(method.DeclaringType.GetTypeSyntax())), SF.Argument(method.Name.GetLiteralExpression()), SF.Argument( SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(method.GetGenericArguments().Length)))))); return SF.FieldDeclaration( SF.VariableDeclaration(typeof(GenericMethodInvoker).GetTypeSyntax()).AddVariables(fieldInfoVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword)); } /// <summary> /// Returns the name of the <see cref="GenericMethodInvoker"/> field corresponding to <paramref name="method"/>. /// </summary> /// <param name="method">The method.</param> /// <returns>The name of the invoker field corresponding to the provided method.</returns> private static string GetGenericMethodInvokerFieldName(MethodInfo method) { return method.Name + string.Join("_", method.GetGenericArguments().Select(arg => arg.Name)); } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using Google.ProtocolBuffers.Descriptors; namespace Google.ProtocolBuffers { /// <summary> /// Implementation of the non-generic IMessage interface as far as possible. /// </summary> public abstract class AbstractBuilder<TMessage, TBuilder> : IBuilder<TMessage, TBuilder> where TMessage : AbstractMessage<TMessage, TBuilder> where TBuilder : AbstractBuilder<TMessage, TBuilder> { protected abstract TBuilder ThisBuilder { get; } #region Unimplemented members of IBuilder public abstract UnknownFieldSet UnknownFields { get; set; } public abstract TBuilder MergeFrom(TMessage other); public abstract bool IsInitialized { get; } public abstract IDictionary<FieldDescriptor, object> AllFields { get; } public abstract object this[FieldDescriptor field] { get; set; } public abstract MessageDescriptor DescriptorForType { get; } public abstract int GetRepeatedFieldCount(FieldDescriptor field); public abstract object this[FieldDescriptor field, int index] { get; set; } public abstract bool HasField(FieldDescriptor field); public abstract TMessage Build(); public abstract TMessage BuildPartial(); public abstract TBuilder Clone(); public abstract TMessage DefaultInstanceForType { get; } public abstract IBuilder CreateBuilderForField(FieldDescriptor field); public abstract TBuilder ClearField(FieldDescriptor field); public abstract TBuilder AddRepeatedField(FieldDescriptor field, object value); #endregion #region Implementation of methods which don't require type parameter information public IMessage WeakBuild() { return Build(); } public IBuilder WeakAddRepeatedField(FieldDescriptor field, object value) { return AddRepeatedField(field, value); } public IBuilder WeakClear() { return Clear(); } public IBuilder WeakMergeFrom(IMessage message) { return MergeFrom(message); } public IBuilder WeakMergeFrom(CodedInputStream input) { return MergeFrom(input); } public IBuilder WeakMergeFrom(CodedInputStream input, ExtensionRegistry registry) { return MergeFrom(input, registry); } public IBuilder WeakMergeFrom(ByteString data) { return MergeFrom(data); } public IBuilder WeakMergeFrom(ByteString data, ExtensionRegistry registry) { return MergeFrom(data, registry); } public IMessage WeakBuildPartial() { return BuildPartial(); } public IBuilder WeakClone() { return Clone(); } public IMessage WeakDefaultInstanceForType { get { return DefaultInstanceForType; } } public IBuilder WeakClearField(FieldDescriptor field) { return ClearField(field); } #endregion public TBuilder SetUnknownFields(UnknownFieldSet fields) { UnknownFields = fields; return ThisBuilder; } public virtual TBuilder Clear() { foreach(FieldDescriptor field in AllFields.Keys) { ClearField(field); } return ThisBuilder; } public virtual TBuilder MergeFrom(IMessage other) { if (other.DescriptorForType != DescriptorForType) { throw new ArgumentException("MergeFrom(IMessage) can only merge messages of the same type."); } // Note: We don't attempt to verify that other's fields have valid // types. Doing so would be a losing battle. We'd have to verify // all sub-messages as well, and we'd have to make copies of all of // them to insure that they don't change after verification (since // the Message interface itself cannot enforce immutability of // implementations). // TODO(jonskeet): Provide a function somewhere called MakeDeepCopy() // which allows people to make secure deep copies of messages. foreach (KeyValuePair<FieldDescriptor, object> entry in other.AllFields) { FieldDescriptor field = entry.Key; if (field.IsRepeated) { // Concatenate repeated fields foreach (object element in (IEnumerable) entry.Value) { AddRepeatedField(field, element); } } else if (field.MappedType == MappedType.Message) { // Merge singular messages IMessage existingValue = (IMessage) this[field]; if (existingValue == existingValue.WeakDefaultInstanceForType) { this[field] = entry.Value; } else { this[field] = existingValue.WeakCreateBuilderForType() .WeakMergeFrom(existingValue) .WeakMergeFrom((IMessage) entry.Value) .WeakBuild(); } } else { // Overwrite simple values this[field] = entry.Value; } } return ThisBuilder; } public virtual TBuilder MergeFrom(CodedInputStream input) { return MergeFrom(input, ExtensionRegistry.Empty); } public virtual TBuilder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry) { UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder(UnknownFields); unknownFields.MergeFrom(input, extensionRegistry, this); UnknownFields = unknownFields.Build(); return ThisBuilder; } public virtual TBuilder MergeUnknownFields(UnknownFieldSet unknownFields) { UnknownFields = UnknownFieldSet.CreateBuilder(UnknownFields) .MergeFrom(unknownFields) .Build(); return ThisBuilder; } public virtual TBuilder MergeFrom(ByteString data) { CodedInputStream input = data.CreateCodedInput(); MergeFrom(input); input.CheckLastTagWas(0); return ThisBuilder; } public virtual TBuilder MergeFrom(ByteString data, ExtensionRegistry extensionRegistry) { CodedInputStream input = data.CreateCodedInput(); MergeFrom(input, extensionRegistry); input.CheckLastTagWas(0); return ThisBuilder; } public virtual TBuilder MergeFrom(byte[] data) { CodedInputStream input = CodedInputStream.CreateInstance(data); MergeFrom(input); input.CheckLastTagWas(0); return ThisBuilder; } public virtual TBuilder MergeFrom(byte[] data, ExtensionRegistry extensionRegistry) { CodedInputStream input = CodedInputStream.CreateInstance(data); MergeFrom(input, extensionRegistry); input.CheckLastTagWas(0); return ThisBuilder; } public virtual TBuilder MergeFrom(Stream input) { CodedInputStream codedInput = CodedInputStream.CreateInstance(input); MergeFrom(codedInput); codedInput.CheckLastTagWas(0); return ThisBuilder; } public virtual TBuilder MergeFrom(Stream input, ExtensionRegistry extensionRegistry) { CodedInputStream codedInput = CodedInputStream.CreateInstance(input); MergeFrom(codedInput, extensionRegistry); codedInput.CheckLastTagWas(0); return ThisBuilder; } public TBuilder MergeDelimitedFrom(Stream input, ExtensionRegistry extensionRegistry) { int size = (int) CodedInputStream.ReadRawVarint32(input); Stream limitedStream = new LimitedInputStream(input, size); return MergeFrom(limitedStream, extensionRegistry); } public TBuilder MergeDelimitedFrom(Stream input) { return MergeDelimitedFrom(input, ExtensionRegistry.Empty); } public virtual IBuilder SetField(FieldDescriptor field, object value) { this[field] = value; return ThisBuilder; } public virtual IBuilder SetRepeatedField(FieldDescriptor field, int index, object value) { this[field, index] = value; return ThisBuilder; } /// <summary> /// Stream implementation which proxies another stream, only allowing a certain amount /// of data to be read. Note that this is only used to read delimited streams, so it /// doesn't attempt to implement everything. /// </summary> private class LimitedInputStream : Stream { private readonly Stream proxied; private int bytesLeft; internal LimitedInputStream(Stream proxied, int size) { this.proxied = proxied; bytesLeft = size; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override void Flush() { } public override long Length { get { throw new NotImplementedException(); } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override int Read(byte[] buffer, int offset, int count) { if (bytesLeft > 0) { int bytesRead = proxied.Read(buffer, offset, Math.Min(bytesLeft, count)); bytesLeft -= bytesRead; return bytesRead; } return 0; } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace ProCultura.Web.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using Xunit; using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Tests { public class File_Delete : FileSystemTest { static bool IsBindMountSupported => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && !PlatformDetection.IsInContainer && !PlatformDetection.IsRedHatFamily6; public virtual void Delete(string path) { File.Delete(path); } public virtual FileInfo Create(string path) { var ret = new FileInfo(path); ret.Create().Dispose(); return ret; } #region UniversalTests [Fact] public void NullParameters() { Assert.Throws<ArgumentNullException>(() => Delete(null)); } [Fact] public void InvalidParameters() { Assert.Throws<ArgumentException>(() => Delete(string.Empty)); } [Fact] public void DeleteDot_ThrowsUnauthorizedAccessException() { Assert.Throws<UnauthorizedAccessException>(() => Delete(".")); } [Fact] public void ShouldBeAbleToDeleteHiddenFile() { FileInfo testFile = Create(GetTestFilePath()); testFile.Attributes = FileAttributes.Hidden; Delete(testFile.FullName); Assert.False(testFile.Exists); } [Fact] public void DeleteNonEmptyFile() { FileInfo testFile = Create(GetTestFilePath()); File.WriteAllText(testFile.FullName, "This is content"); Delete(testFile.FullName); Assert.False(testFile.Exists); } [Fact] public void PositiveTest() { FileInfo testFile = Create(GetTestFilePath()); Delete(testFile.FullName); Assert.False(testFile.Exists); } [Fact] public void NonExistentFile() { Delete(Path.Combine(Path.GetPathRoot(TestDirectory), Path.GetRandomFileName())); Delete(GetTestFilePath()); } [Fact] public void ShouldThrowIOExceptionDeletingDirectory() { Assert.Throws<UnauthorizedAccessException>(() => Delete(TestDirectory)); } [ConditionalFact(nameof(CanCreateSymbolicLinks))] public void DeletingSymLinkDoesntDeleteTarget() { var path = GetTestFilePath(); var linkPath = GetTestFilePath(); File.Create(path).Dispose(); Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: false)); // Both the symlink and the target exist Assert.True(File.Exists(path), "path should exist"); Assert.True(File.Exists(linkPath), "linkPath should exist"); // Delete the symlink File.Delete(linkPath); // Target should still exist Assert.True(File.Exists(path), "path should still exist"); Assert.False(File.Exists(linkPath), "linkPath should no longer exist"); } [Fact] public void NonExistentPath_Throws_DirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => Delete(Path.Combine(Path.GetRandomFileName(), "C"))); Assert.Throws<DirectoryNotFoundException>(() => Delete(Path.Combine(Path.GetPathRoot(TestDirectory), Path.GetRandomFileName(), "C"))); Assert.Throws<DirectoryNotFoundException>(() => Delete(Path.Combine(TestDirectory, GetTestFileName(), "C"))); } #endregion #region PlatformSpecific [ConditionalFact(nameof(IsBindMountSupported))] [OuterLoop("Needs sudo access")] [PlatformSpecific(TestPlatforms.Linux)] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void Unix_NonExistentPath_ReadOnlyVolume() { ReadOnly_FileSystemHelper(readOnlyDirectory => { Delete(Path.Combine(readOnlyDirectory, "DoesNotExist")); }); } [ConditionalFact(nameof(IsBindMountSupported))] [OuterLoop("Needs sudo access")] [PlatformSpecific(TestPlatforms.Linux)] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void Unix_ExistingDirectory_ReadOnlyVolume() { ReadOnly_FileSystemHelper(readOnlyDirectory => { Assert.Throws<IOException>(() => Delete(Path.Combine(readOnlyDirectory, "subdir"))); }, subDirectoryName: "subdir"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Deleting already-open file throws public void Windows_File_Already_Open_Throws_IOException() { string path = GetTestFilePath(); using (File.Create(path)) { Assert.Throws<IOException>(() => Delete(path)); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting already-open file allowed public void Unix_File_Already_Open_Allowed() { string path = GetTestFilePath(); using (File.Create(path)) { Delete(path); Assert.False(File.Exists(path)); } Assert.False(File.Exists(path)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Deleting readonly file throws public void WindowsDeleteReadOnlyFile() { string path = GetTestFilePath(); File.Create(path).Dispose(); File.SetAttributes(path, FileAttributes.ReadOnly); Assert.Throws<UnauthorizedAccessException>(() => Delete(path)); Assert.True(File.Exists(path)); File.SetAttributes(path, FileAttributes.Normal); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting readonly file allowed public void UnixDeleteReadOnlyFile() { FileInfo testFile = Create(GetTestFilePath()); testFile.Attributes = FileAttributes.ReadOnly; Delete(testFile.FullName); Assert.False(testFile.Exists); } [Theory, InlineData(":bar"), InlineData(":bar:$DATA")] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void WindowsDeleteAlternateDataStream(string streamName) { FileInfo testFile = Create(GetTestFilePath()); testFile.Create().Dispose(); streamName = testFile.FullName + streamName; File.Create(streamName).Dispose(); Assert.True(File.Exists(streamName)); Delete(streamName); Assert.False(File.Exists(streamName)); testFile.Refresh(); Assert.True(testFile.Exists); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.WebSockets.Client.Tests { /// <summary> /// ClientWebSocket unit tests that do not require a remote server. /// </summary> public class ClientWebSocketUnitTest { private readonly ITestOutputHelper _output; public ClientWebSocketUnitTest(ITestOutputHelper output) { _output = output; } private static bool WebSocketsSupported { get { return WebSocketHelper.WebSocketsSupported; } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void Ctor_Success() { var cws = new ClientWebSocket(); cws.Dispose(); } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void Abort_CreateAndAbort_StateIsClosed() { using (var cws = new ClientWebSocket()) { cws.Abort(); Assert.Equal(WebSocketState.Closed, cws.State); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_CreateAndClose_ThrowsInvalidOperationException() { using (var cws = new ClientWebSocket()) { Assert.Throws<InvalidOperationException>(() => { Task t = cws.CloseAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()); }); Assert.Equal(WebSocketState.None, cws.State); } } [ActiveIssue(20132, TargetFrameworkMonikers.Uap)] [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_CreateAndCloseOutput_ThrowsInvalidOperationExceptionWithMessage() { using (var cws = new ClientWebSocket()) { AssertExtensions.Throws<InvalidOperationException>( () => cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()).GetAwaiter().GetResult(), ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected")); Assert.Equal(WebSocketState.None, cws.State); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_CreateAndReceive_ThrowsInvalidOperationException() { using (var cws = new ClientWebSocket()) { var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); Assert.Throws<InvalidOperationException>(() => { Task t = cws.ReceiveAsync(segment, ct); }); Assert.Equal(WebSocketState.None, cws.State); } } [ActiveIssue(20132, TargetFrameworkMonikers.Uap)] [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_CreateAndReceive_ThrowsInvalidOperationExceptionWithMessage() { using (var cws = new ClientWebSocket()) { var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); AssertExtensions.Throws<InvalidOperationException>( () => cws.ReceiveAsync(segment, ct).GetAwaiter().GetResult(), ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected")); Assert.Equal(WebSocketState.None, cws.State); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_CreateAndSend_ThrowsInvalidOperationException() { using (var cws = new ClientWebSocket()) { var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); Assert.Throws<InvalidOperationException>(() => { Task t = cws.SendAsync(segment, WebSocketMessageType.Text, false, ct); }); Assert.Equal(WebSocketState.None, cws.State); } } [ActiveIssue(20132, TargetFrameworkMonikers.Uap)] [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_CreateAndSend_ThrowsInvalidOperationExceptionWithMessage() { using (var cws = new ClientWebSocket()) { var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); AssertExtensions.Throws<InvalidOperationException>( () => cws.SendAsync(segment, WebSocketMessageType.Text, false, ct).GetAwaiter().GetResult(), ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected")); Assert.Equal(WebSocketState.None, cws.State); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void Ctor_ExpectedPropertyValues() { using (var cws = new ClientWebSocket()) { Assert.Equal(null, cws.CloseStatus); Assert.Equal(null, cws.CloseStatusDescription); Assert.NotEqual(null, cws.Options); Assert.Equal(WebSocketState.None, cws.State); Assert.Equal(null, cws.SubProtocol); Assert.Equal("System.Net.WebSockets.ClientWebSocket", cws.ToString()); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void Abort_CreateAndDisposeAndAbort_StateIsClosedSuccess() { var cws = new ClientWebSocket(); cws.Dispose(); cws.Abort(); Assert.Equal(WebSocketState.Closed, cws.State); } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_DisposeAndClose_ThrowsObjectDisposedException() { var cws = new ClientWebSocket(); cws.Dispose(); Assert.Throws<ObjectDisposedException>(() => { Task t = cws.CloseAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()); }); Assert.Equal(WebSocketState.Closed, cws.State); } [ActiveIssue(20132, TargetFrameworkMonikers.Uap)] [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_DisposeAndCloseOutput_ThrowsObjectDisposedExceptionWithMessage() { var cws = new ClientWebSocket(); cws.Dispose(); var expectedException = new ObjectDisposedException(cws.GetType().FullName); AssertExtensions.Throws<ObjectDisposedException>( () => cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()).GetAwaiter().GetResult(), expectedException.Message); Assert.Equal(WebSocketState.Closed, cws.State); } [ActiveIssue(20132, TargetFrameworkMonikers.Uap)] [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void ReceiveAsync_CreateAndDisposeAndReceive_ThrowsObjectDisposedExceptionWithMessage() { var cws = new ClientWebSocket(); cws.Dispose(); var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); var expectedException = new ObjectDisposedException(cws.GetType().FullName); AssertExtensions.Throws<ObjectDisposedException>( () => cws.ReceiveAsync(segment, ct).GetAwaiter().GetResult(), expectedException.Message); Assert.Equal(WebSocketState.Closed, cws.State); } [ActiveIssue(20132, TargetFrameworkMonikers.Uap)] [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void SendAsync_CreateAndDisposeAndSend_ThrowsObjectDisposedExceptionWithMessage() { var cws = new ClientWebSocket(); cws.Dispose(); var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); var expectedException = new ObjectDisposedException(cws.GetType().FullName); AssertExtensions.Throws<ObjectDisposedException>( () => cws.SendAsync(segment, WebSocketMessageType.Text, false, ct).GetAwaiter().GetResult(), expectedException.Message); Assert.Equal(WebSocketState.Closed, cws.State); } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public void Dispose_CreateAndDispose_ExpectedPropertyValues() { var cws = new ClientWebSocket(); cws.Dispose(); Assert.Equal(null, cws.CloseStatus); Assert.Equal(null, cws.CloseStatusDescription); Assert.NotEqual(null, cws.Options); Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(null, cws.SubProtocol); Assert.Equal("System.Net.WebSockets.ClientWebSocket", cws.ToString()); } } }
using System; using Umbraco.Core.IO; namespace umbraco.scripting { /// <summary> /// Something like a proxy to IronPython. Does some initial settings and calls. /// Maps IronPython's StandardOutput and StandardError to a simple string. /// </summary> public class python { protected internal static PythonEngine Engine; protected static System.IO.MemoryStream ms; protected static System.IO.StreamReader sr; protected internal static System.Collections.Hashtable scripts; static python() { Engine = new PythonEngine(); initEnv(); loadScripts(); ms = new System.IO.MemoryStream(); sr = new System.IO.StreamReader(ms); Engine.SetStandardOutput(ms); Engine.SetStandardError(ms); } /// <summary> /// To be able to import umbraco dll's we have to append the umbraco path to python. /// It should also be possible to import other python scripts from umbracos python folder. /// And finally to run run some custom init stuff the script site.py in umbraco's /// root folder will be executed. /// </summary> /// <returns></returns> private static void initEnv() { // Add umbracos bin folder to python's path string path = IOHelper.MapPath(SystemDirectories.Bin); Engine.AddToPath(path); // Add umbracos python folder to python's path path = IOHelper.MapPath(SystemDirectories.MacroScripts); Engine.AddToPath(path); // execute the site.py to do all the initial stuff string initFile = IOHelper.MapPath(SystemDirectories.Root + "/site.py"); Engine.ExecuteFile(initFile); } /// <summary> /// /// </summary> /// <returns></returns> private static void loadScripts() { scripts = new System.Collections.Hashtable(); string path = IOHelper.MapPath(SystemDirectories.MacroScripts); System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path); foreach (System.IO.FileInfo f in dir.GetFiles("*.py")) { if (!f.Name.EndsWith("_temp.py")) { try { scripts[f.FullName] = Engine.CompileFile(f.FullName ); } catch { scripts[f.FullName] = Engine.Compile("print 'error in file " + f.Name + "'"); } } } } /// <summary> /// Executes a python command like in console /// </summary> /// <param name="expression">command to execute</param> /// <returns>returns standard out of executed command</returns> public static string execute(string expression) { if (!(expression == null)) { string ret; ms.SetLength(0); ms.Flush(); try { Engine.Execute(expression); ms.Position = 0; ret = sr.ReadToEnd(); } catch (Exception ex) { ret = ex.Message; } return ret; } else { return string.Empty; } } /// <summary> /// Executes a python script like in console /// </summary> /// <param name="file">absolute path to script</param> /// <returns>returns standard out of executed script</returns> public static string executeFile(string file) { if (System.IO.File.Exists(file)) { string ret; ms.SetLength(0); ms.Flush(); scripts[file].GetType().InvokeMember("Execute", System.Reflection.BindingFlags.InvokeMethod, null, scripts[file], null); ms.Position = 0; ret = sr.ReadToEnd(); return ret; } else { return "The File " + file + " could not be found."; } } /// <summary> /// Compiles a python script and add it to umbraco's script collection. /// If compilation fails then an exception will be raised. /// </summary> /// <param name="file">absolute path to script</param> /// <returns></returns> public static void compileFile(string file) { loadScripts(); scripts[file] = Engine.CompileFile(file); } /// <summary> /// Compiles a python script. /// If compilation fails then an exception will be raised. /// </summary> /// <param name="file">absolute path to script</param> /// <returns></returns> public static void tryCompile(string file) { Engine.CompileFile(file); } } /// <summary> /// The Class PythonEngine is just a wrapper for the real class IronPython.Hosting.PythonEngine /// in IronPython. In this manner we does not need a hard reference to the IronPython assembly. /// I've implemented only the methods i need for my purpose. /// </summary> public class PythonEngine { protected object Engine; public PythonEngine() { string path = IOHelper.MapPath(SystemDirectories.Bin + "/IronPython.dll"); System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFile(path); System.Type EngineType = asm.GetType("IronPython.Hosting.PythonEngine"); Engine = System.Activator.CreateInstance(EngineType); } public void AddToPath(string path) { Engine.GetType().InvokeMember("AddToPath", System.Reflection.BindingFlags.InvokeMethod, null, Engine, new object[] { path }); } public void SetStandardOutput(System.IO.Stream stream) { Engine.GetType().InvokeMember("SetStandardOutput", System.Reflection.BindingFlags.InvokeMethod, null, Engine, new object[] { stream }); } public void SetStandardError(System.IO.Stream stream) { Engine.GetType().InvokeMember("SetStandardError", System.Reflection.BindingFlags.InvokeMethod, null, Engine, new object[] { stream }); } public void ExecuteFile(string FileName) { Engine.GetType().InvokeMember("ExecuteFile", System.Reflection.BindingFlags.InvokeMethod, null, Engine, new object[] { FileName }); } public void Execute(string ScriptCode) { Engine.GetType().InvokeMember("Execute", System.Reflection.BindingFlags.InvokeMethod, null, Engine, new object[] { ScriptCode }); } public Object CompileFile(string FileName) { return Engine.GetType().InvokeMember("CompileFile", System.Reflection.BindingFlags.InvokeMethod, null, Engine, new object[] { FileName }); } public Object Compile(string Expression) { return Engine.GetType().InvokeMember("Compile", System.Reflection.BindingFlags.InvokeMethod, null, Engine, new object[] { Expression }); } public Object CreateModule(string Modulename, bool publish) { return Engine.GetType().InvokeMember("CreateModule", System.Reflection.BindingFlags.InvokeMethod, null, Engine, new object[] { Modulename, publish }); } public System.Collections.IDictionary Globals { set { Engine.GetType().InvokeMember("Globals", System.Reflection.BindingFlags.SetProperty, null, Engine, new object[] { value }); } get { return (System.Collections.IDictionary)Engine.GetType().InvokeMember("Globals", System.Reflection.BindingFlags.GetProperty, null, Engine, null); } } } }
using Lucene.Net.Store; using Lucene.Net.Util; using System; using System.Diagnostics; using System.IO; namespace Lucene.Net.Codecs { /* * 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. */ /// <summary> /// Utility class for reading and writing versioned headers. /// <para/> /// Writing codec headers is useful to ensure that a file is in /// the format you think it is. /// <para/> /// @lucene.experimental /// </summary> public sealed class CodecUtil { private CodecUtil() // no instance { } /// <summary> /// Constant to identify the start of a codec header. /// </summary> public static readonly int CODEC_MAGIC = 0x3fd76c17; /// <summary> /// Constant to identify the start of a codec footer. /// </summary> public static readonly int FOOTER_MAGIC = ~CODEC_MAGIC; /// <summary> /// Writes a codec header, which records both a string to /// identify the file and a version number. This header can /// be parsed and validated with /// <see cref="CheckHeader(DataInput, string, int, int)"/>. /// <para/> /// CodecHeader --&gt; Magic,CodecName,Version /// <list type="bullet"> /// <item><description>Magic --&gt; Uint32 (<see cref="DataOutput.WriteInt32(int)"/>). this /// identifies the start of the header. It is always <see cref="CODEC_MAGIC"/>.</description></item> /// <item><description>CodecName --&gt; String (<see cref="DataOutput.WriteString(string)"/>). this /// is a string to identify this file.</description></item> /// <item><description>Version --&gt; Uint32 (<see cref="DataOutput.WriteInt32(int)"/>). Records /// the version of the file.</description></item> /// </list> /// <para/> /// Note that the length of a codec header depends only upon the /// name of the codec, so this length can be computed at any time /// with <see cref="HeaderLength(string)"/>. /// </summary> /// <param name="out"> Output stream </param> /// <param name="codec"> String to identify this file. It should be simple ASCII, /// less than 128 characters in length. </param> /// <param name="version"> Version number </param> /// <exception cref="IOException"> If there is an I/O error writing to the underlying medium. </exception> public static void WriteHeader(DataOutput @out, string codec, int version) { BytesRef bytes = new BytesRef(codec); if (bytes.Length != codec.Length || bytes.Length >= 128) { throw new ArgumentException("codec must be simple ASCII, less than 128 characters in length [got " + codec + "]"); } @out.WriteInt32(CODEC_MAGIC); @out.WriteString(codec); @out.WriteInt32(version); } /// <summary> /// Computes the length of a codec header. /// </summary> /// <param name="codec"> Codec name. </param> /// <returns> Length of the entire codec header. </returns> /// <seealso cref="WriteHeader(DataOutput, string, int)"/> public static int HeaderLength(string codec) { return 9 + codec.Length; } /// <summary> /// Reads and validates a header previously written with /// <see cref="WriteHeader(DataOutput, string, int)"/>. /// <para/> /// When reading a file, supply the expected <paramref name="codec"/> and /// an expected version range (<paramref name="minVersion"/> to <paramref name="maxVersion"/>). /// </summary> /// <param name="in"> Input stream, positioned at the point where the /// header was previously written. Typically this is located /// at the beginning of the file. </param> /// <param name="codec"> The expected codec name. </param> /// <param name="minVersion"> The minimum supported expected version number. </param> /// <param name="maxVersion"> The maximum supported expected version number. </param> /// <returns> The actual version found, when a valid header is found /// that matches <paramref name="codec"/>, with an actual version /// where <c>minVersion &lt;= actual &lt;= maxVersion</c>. /// Otherwise an exception is thrown. </returns> /// <exception cref="Index.CorruptIndexException"> If the first four bytes are not /// <see cref="CODEC_MAGIC"/>, or if the actual codec found is /// not <paramref name="codec"/>. </exception> /// <exception cref="Index.IndexFormatTooOldException"> If the actual version is less /// than <paramref name="minVersion"/>. </exception> /// <exception cref="Index.IndexFormatTooNewException"> If the actual version is greater /// than <paramref name="maxVersion"/>. </exception> /// <exception cref="IOException"> If there is an I/O error reading from the underlying medium. </exception> /// <seealso cref="WriteHeader(DataOutput, string, int)"/> public static int CheckHeader(DataInput @in, string codec, int minVersion, int maxVersion) { // Safety to guard against reading a bogus string: int actualHeader = @in.ReadInt32(); if (actualHeader != CODEC_MAGIC) { throw new IOException("codec header mismatch: actual header=" + actualHeader + " vs expected header=" + CODEC_MAGIC + " (resource: " + @in + ")"); } return CheckHeaderNoMagic(@in, codec, minVersion, maxVersion); } /// <summary> /// Like /// <see cref="CheckHeader(DataInput,string,int,int)"/> except this /// version assumes the first <see cref="int"/> has already been read /// and validated from the input. /// </summary> public static int CheckHeaderNoMagic(DataInput @in, string codec, int minVersion, int maxVersion) { string actualCodec = @in.ReadString(); if (!actualCodec.Equals(codec, StringComparison.Ordinal)) { throw new IOException("codec mismatch: actual codec=" + actualCodec + " vs expected codec=" + codec + " (resource: " + @in + ")"); } int actualVersion = @in.ReadInt32(); if (actualVersion < minVersion) { throw new IOException("Version: " + actualVersion + " is not supported. Minimum Version number is " + minVersion + "."); } if (actualVersion > maxVersion) { throw new IOException("Version: " + actualVersion + " is not supported. Maximum Version number is " + maxVersion + "."); } return actualVersion; } /// <summary> /// Writes a codec footer, which records both a checksum /// algorithm ID and a checksum. This footer can /// be parsed and validated with /// <see cref="CheckFooter(ChecksumIndexInput)"/>. /// <para/> /// CodecFooter --&gt; Magic,AlgorithmID,Checksum /// <list type="bullet"> /// <item><description>Magic --&gt; Uint32 (<see cref="DataOutput.WriteInt32(int)"/>). this /// identifies the start of the footer. It is always <see cref="FOOTER_MAGIC"/>.</description></item> /// <item><description>AlgorithmID --&gt; Uint32 (<see cref="DataOutput.WriteInt32(int)"/>). this /// indicates the checksum algorithm used. Currently this is always 0, /// for zlib-crc32.</description></item> /// <item><description>Checksum --&gt; Uint32 (<see cref="DataOutput.WriteInt64(long)"/>). The /// actual checksum value for all previous bytes in the stream, including /// the bytes from Magic and AlgorithmID.</description></item> /// </list> /// </summary> /// <param name="out"> Output stream </param> /// <exception cref="IOException"> If there is an I/O error writing to the underlying medium. </exception> public static void WriteFooter(IndexOutput @out) { @out.WriteInt32(FOOTER_MAGIC); @out.WriteInt32(0); @out.WriteInt64(@out.Checksum); } /// <summary> /// Computes the length of a codec footer. /// </summary> /// <returns> Length of the entire codec footer. </returns> /// <seealso cref="WriteFooter(IndexOutput)"/> public static int FooterLength() { return 16; } /// <summary> /// Validates the codec footer previously written by <see cref="WriteFooter(IndexOutput)"/>. </summary> /// <returns> Actual checksum value. </returns> /// <exception cref="IOException"> If the footer is invalid, if the checksum does not match, /// or if <paramref name="in"/> is not properly positioned before the footer /// at the end of the stream. </exception> public static long CheckFooter(ChecksumIndexInput @in) { ValidateFooter(@in); long actualChecksum = @in.Checksum; long expectedChecksum = @in.ReadInt64(); if (expectedChecksum != actualChecksum) { throw new IOException("checksum failed (hardware problem?) : expected=" + expectedChecksum.ToString("x") + " actual=" + actualChecksum.ToString("x") + " (resource=" + @in + ")"); } if (@in.GetFilePointer() != @in.Length) { throw new IOException("did not read all bytes from file: read " + @in.GetFilePointer() + " vs size " + @in.Length + " (resource: " + @in + ")"); } return actualChecksum; } /// <summary> /// Returns (but does not validate) the checksum previously written by <see cref="CheckFooter(ChecksumIndexInput)"/>. </summary> /// <returns> actual checksum value </returns> /// <exception cref="IOException"> If the footer is invalid. </exception> public static long RetrieveChecksum(IndexInput @in) { @in.Seek(@in.Length - FooterLength()); ValidateFooter(@in); return @in.ReadInt64(); } private static void ValidateFooter(IndexInput @in) { int magic = @in.ReadInt32(); if (magic != FOOTER_MAGIC) { throw new IOException("codec footer mismatch: actual footer=" + magic + " vs expected footer=" + FOOTER_MAGIC + " (resource: " + @in + ")"); } int algorithmID = @in.ReadInt32(); if (algorithmID != 0) { throw new IOException("codec footer mismatch: unknown algorithmID: " + algorithmID); } } /// <summary> /// Checks that the stream is positioned at the end, and throws exception /// if it is not. </summary> [Obsolete("Use CheckFooter(ChecksumIndexInput) instead, this should only used for files without checksums.")] public static void CheckEOF(IndexInput @in) { if (@in.GetFilePointer() != @in.Length) { throw new IOException("did not read all bytes from file: read " + @in.GetFilePointer() + " vs size " + @in.Length + " (resource: " + @in + ")"); } } /// <summary> /// Clones the provided input, reads all bytes from the file, and calls <see cref="CheckFooter(ChecksumIndexInput)"/> /// <para/> /// Note that this method may be slow, as it must process the entire file. /// If you just need to extract the checksum value, call <see cref="RetrieveChecksum(IndexInput)"/>. /// </summary> public static long ChecksumEntireFile(IndexInput input) { IndexInput clone = (IndexInput)input.Clone(); clone.Seek(0); ChecksumIndexInput @in = new BufferedChecksumIndexInput(clone); Debug.Assert(@in.GetFilePointer() == 0); @in.Seek(@in.Length - FooterLength()); return CheckFooter(@in); } } }
using System; using System.Collections.Generic; using MCSharp.World; namespace MCSharp { public class CmdCuboid : Command { // Constructor public CmdCuboid (CommandGroup g, GroupEnum group, string name) : base(g, group, name) { blnConsoleSupported = false; /* By default no console support*/ } // Command usage help public override void Help (Player p) { p.SendMessage("/cuboid [type] <solid/hollow/walls> - create a cuboid of blocks."); } // Code to run when used by a player public override void Use (Player p, string message) { int number = message.Split(' ').Length; if (number > 2) { Help(p); return; } // example, /cuboid op_white walls if (number == 2) { int pos = message.IndexOf(' '); string t = message.Substring(0, pos).ToLower(); string s = message.Substring(pos + 1).ToLower(); byte type = Block.Byte(t); if (type == 255) { p.SendMessage("There is no block \"" + t + "\"."); return; } if (Server.advbuilders.Contains(p.name)) { if (!Block.Placable(type) && !Block.AdvPlacable(type)) { p.SendMessage("Your not allowed to place that."); return; } } SolidType solid; if (s == "solid") { solid = SolidType.solid; } else if (s == "hollow") { solid = SolidType.hollow; } else if (s == "walls") { solid = SolidType.walls; } else { Help(p); return; } CatchPos cpos = new CatchPos(); cpos.solid = solid; cpos.type = type; cpos.x = 0; cpos.y = 0; cpos.z = 0; p.blockchangeObject = cpos; } // Example, /cuboid op_white // Example, /cuboid walls else if (message != "") { SolidType solid = SolidType.solid; message = message.ToLower(); byte type; unchecked { type = (byte) -1; } if (message == "solid") { solid = SolidType.solid; } else if (message == "hollow") { solid = SolidType.hollow; } else if (message == "walls") { solid = SolidType.walls; } else { byte t = Block.Byte(message); if (t == 255) { p.SendMessage("There is no block \"" + message + "\"."); return; } if (p.Rank == GroupEnum.AdvBuilder) { if (!Block.Placable(t) && !Block.AdvPlacable(t)) { p.SendMessage("Your not allowed to place that."); return; } } type = t; } CatchPos cpos = new CatchPos(); cpos.solid = solid; cpos.type = type; cpos.x = 0; cpos.y = 0; cpos.z = 0; p.blockchangeObject = cpos; } // Example, /cuboid // Take currently held block else { CatchPos cpos = new CatchPos(); cpos.solid = SolidType.solid; unchecked { cpos.type = (byte) -1; } cpos.x = 0; cpos.y = 0; cpos.z = 0; p.blockchangeObject = cpos; } p.SendMessage("Place two blocks to determine the edges."); p.ClearBlockchange(); p.Blockchange += new Player.BlockchangeEventHandler(Blockchange1); } // Grab First Pos // First block change (defining first corner) // Figure out what kind of cuboid // Process Changes to the world public void Blockchange1 (Player p, ushort x, ushort y, ushort z, byte type) { p.ClearBlockchange(); byte b = p.level.GetTile(x, y, z); p.SendBlockchange(x, y, z, b); CatchPos bp = (CatchPos) p.blockchangeObject; bp.x = x; bp.y = y; bp.z = z; p.blockchangeObject = bp; p.Blockchange += new Player.BlockchangeEventHandler(Blockchange2); } // Second block change (defining second corner) public void Blockchange2 (Player p, ushort x, ushort y, ushort z, byte type) { p.ClearBlockchange(); byte b = p.level.GetTile(x, y, z); p.SendBlockchange(x, y, z, b); CatchPos cpos = (CatchPos) p.blockchangeObject; unchecked { if (cpos.type != (byte) -1) { type = cpos.type; } } List<Pos> buffer = new List<Pos>(); // Solid is default switch (cpos.solid) { case SolidType.solid: // redundant? if (Math.Abs(cpos.x - x) * Math.Abs(cpos.y - y) * Math.Abs(cpos.z - z) > p.group.CuboidLimit && p.group.CuboidLimit != 0) { p.SendMessage("You're trying to place " + buffer.Count.ToString() + " blocks."); p.SendMessage("Your block limit is " + p.group.CuboidLimit.ToString() + " blocks. Build in stages."); return; } // end redundant? buffer.Capacity = Math.Abs(cpos.x - x) * Math.Abs(cpos.y - y) * Math.Abs(cpos.z - z); // Nested for loops to cover a solid cube for (ushort xx = Math.Min(cpos.x, x); xx <= Math.Max(cpos.x, x); ++xx) for (ushort yy = Math.Min(cpos.y, y); yy <= Math.Max(cpos.y, y); ++yy) for (ushort zz = Math.Min(cpos.z, z); zz <= Math.Max(cpos.z, z); ++zz) if (p.level.GetTile(xx, yy, zz) != type) { BufferAdd(buffer, xx, yy, zz); } break; case SolidType.hollow: // TODO: Work out if theres 800 blocks used before making the buffer // Hollow will build only the outer shell of a cube leaving the center alone for (ushort yy = Math.Min(cpos.y, y); yy <= Math.Max(cpos.y, y); ++yy) for (ushort zz = Math.Min(cpos.z, z); zz <= Math.Max(cpos.z, z); ++zz) { if (p.level.GetTile(cpos.x, yy, zz) != type) { BufferAdd(buffer, cpos.x, yy, zz); } if (cpos.x != x) { if (p.level.GetTile(x, yy, zz) != type) { BufferAdd(buffer, x, yy, zz); } } } if (Math.Abs(cpos.x - x) >= 2) { for (ushort xx = (ushort) (Math.Min(cpos.x, x) + 1); xx <= Math.Max(cpos.x, x) - 1; ++xx) for (ushort zz = Math.Min(cpos.z, z); zz <= Math.Max(cpos.z, z); ++zz) { if (p.level.GetTile(xx, cpos.y, zz) != type) { BufferAdd(buffer, xx, cpos.y, zz); } if (cpos.y != y) { if (p.level.GetTile(xx, y, zz) != type) { BufferAdd(buffer, xx, y, zz); } } } if (Math.Abs(cpos.y - y) >= 2) { for (ushort xx = (ushort) (Math.Min(cpos.x, x) + 1); xx <= Math.Max(cpos.x, x) - 1; ++xx) for (ushort yy = (ushort) (Math.Min(cpos.y, y) + 1); yy <= Math.Max(cpos.y, y) - 1; ++yy) { if (p.level.GetTile(xx, yy, cpos.z) != type) { BufferAdd(buffer, xx, yy, cpos.z); } if (cpos.z != z) { if (p.level.GetTile(xx, yy, z) != type) { BufferAdd(buffer, xx, yy, z); } } } } } break; // Walls builds only the surrounding vertical borders of a cube case SolidType.walls: for (ushort yy = Math.Min(cpos.y, y); yy <= Math.Max(cpos.y, y); ++yy) for (ushort zz = Math.Min(cpos.z, z); zz <= Math.Max(cpos.z, z); ++zz) { if (p.level.GetTile(cpos.x, yy, zz) != type) { BufferAdd(buffer, cpos.x, yy, zz); } if (cpos.x != x) { if (p.level.GetTile(x, yy, zz) != type) { BufferAdd(buffer, x, yy, zz); } } } if (Math.Abs(cpos.x - x) >= 2) { if (Math.Abs(cpos.z - z) >= 2) { for (ushort xx = (ushort) (Math.Min(cpos.x, x) + 1); xx <= Math.Max(cpos.x, x) - 1; ++xx) for (ushort yy = (ushort) (Math.Min(cpos.y, y)); yy <= Math.Max(cpos.y, y); ++yy) { if (p.level.GetTile(xx, yy, cpos.z) != type) { BufferAdd(buffer, xx, yy, cpos.z); } if (cpos.z != z) { if (p.level.GetTile(xx, yy, z) != type) { BufferAdd(buffer, xx, yy, z); } } } } } break; } // Why are we running this in the solid case statement as well? if (buffer.Count > p.group.CuboidLimit && p.group.CuboidLimit != 0) { p.SendMessage("You're trying to place " + buffer.Count.ToString() + " blocks."); p.SendMessage("Your block limit is " + p.group.CuboidLimit.ToString() + " blocks. Build in stages."); return; } p.SendMessage(buffer.Count.ToString() + " blocks."); // This code may not be needed. We already check whether the player can place the block near the top of this class if (!Server.advbuilders.Contains(p.name)) { buffer.ForEach(delegate(Pos pos) { p.level.Blockchange(p, pos.x, pos.y, pos.z, type); //update block for everyone }); } else { buffer.ForEach(delegate(Pos pos) { byte bl = p.level.GetTile(pos.x, pos.y, pos.z); if (Block.Placable(bl) || Block.AdvPlacable(bl)) { p.level.Blockchange(p, pos.x, pos.y, pos.z, type); } //update block for everyone }); } // end possibly not needed code } void BufferAdd (List<Pos> list, ushort x, ushort y, ushort z) { Pos pos; pos.x = x; pos.y = y; pos.z = z; list.Add(pos); } } }
using System; using System.Diagnostics; namespace Lucene.Net.Codecs.Lucene3x { using Lucene.Net.Index; using BytesRef = Lucene.Net.Util.BytesRef; /* * 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 FieldInfos = Lucene.Net.Index.FieldInfos; using IndexInput = Lucene.Net.Store.IndexInput; using Term = Lucene.Net.Index.Term; /// <summary> /// @lucene.experimental </summary> /// @deprecated (4.0) [Obsolete("(4.0)")] internal sealed class SegmentTermPositions : SegmentTermDocs { private IndexInput ProxStream; private IndexInput ProxStreamOrig; private int ProxCount; private int Position; private BytesRef Payload_Renamed; // the current payload length private int PayloadLength_Renamed; // indicates whether the payload of the current position has // been read from the proxStream yet private bool NeedToLoadPayload; // these variables are being used to remember information // for a lazy skip private long LazySkipPointer = -1; private int LazySkipProxCount = 0; /* SegmentTermPositions(SegmentReader p) { super(p); this.proxStream = null; // the proxStream will be cloned lazily when nextPosition() is called for the first time } */ public SegmentTermPositions(IndexInput freqStream, IndexInput proxStream, TermInfosReader tis, FieldInfos fieldInfos) : base(freqStream, tis, fieldInfos) { this.ProxStreamOrig = proxStream; // the proxStream will be cloned lazily when nextPosition() is called for the first time } internal override void Seek(TermInfo ti, Term term) { base.Seek(ti, term); if (ti != null) { LazySkipPointer = ti.ProxPointer; } LazySkipProxCount = 0; ProxCount = 0; PayloadLength_Renamed = 0; NeedToLoadPayload = false; } public override void Close() { base.Close(); if (ProxStream != null) { ProxStream.Dispose(); } } public int NextPosition() { if (IndexOptions != FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) // this field does not store positions, payloads { return 0; } // perform lazy skips if necessary LazySkip(); ProxCount--; return Position += ReadDeltaPosition(); } private int ReadDeltaPosition() { int delta = ProxStream.ReadVInt(); if (CurrentFieldStoresPayloads) { // if the current field stores payloads then // the position delta is shifted one bit to the left. // if the LSB is set, then we have to read the current // payload length if ((delta & 1) != 0) { PayloadLength_Renamed = ProxStream.ReadVInt(); } delta = (int)((uint)delta >> 1); NeedToLoadPayload = true; } else if (delta == -1) { delta = 0; // LUCENE-1542 correction } return delta; } protected internal override void SkippingDoc() { // we remember to skip a document lazily LazySkipProxCount += Freq_Renamed; } public override bool Next() { // we remember to skip the remaining positions of the current // document lazily LazySkipProxCount += ProxCount; if (base.Next()) // run super { ProxCount = Freq_Renamed; // note frequency Position = 0; // reset position return true; } return false; } public override int Read(int[] docs, int[] freqs) { throw new System.NotSupportedException("TermPositions does not support processing multiple documents in one call. Use TermDocs instead."); } /// <summary> /// Called by super.skipTo(). </summary> protected internal override void SkipProx(long proxPointer, int payloadLength) { // we save the pointer, we might have to skip there lazily LazySkipPointer = proxPointer; LazySkipProxCount = 0; ProxCount = 0; this.PayloadLength_Renamed = payloadLength; NeedToLoadPayload = false; } private void SkipPositions(int n) { Debug.Assert(IndexOptions == FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); for (int f = n; f > 0; f--) // skip unread positions { ReadDeltaPosition(); SkipPayload(); } } private void SkipPayload() { if (NeedToLoadPayload && PayloadLength_Renamed > 0) { ProxStream.Seek(ProxStream.FilePointer + PayloadLength_Renamed); } NeedToLoadPayload = false; } // It is not always necessary to move the prox pointer // to a new document after the freq pointer has been moved. // Consider for example a phrase query with two terms: // the freq pointer for term 1 has to move to document x // to answer the question if the term occurs in that document. But // only if term 2 also matches document x, the positions have to be // read to figure out if term 1 and term 2 appear next // to each other in document x and thus satisfy the query. // So we move the prox pointer lazily to the document // as soon as positions are requested. private void LazySkip() { if (ProxStream == null) { // clone lazily ProxStream = (IndexInput)ProxStreamOrig.Clone(); } // we might have to skip the current payload // if it was not read yet SkipPayload(); if (LazySkipPointer != -1) { ProxStream.Seek(LazySkipPointer); LazySkipPointer = -1; } if (LazySkipProxCount != 0) { SkipPositions(LazySkipProxCount); LazySkipProxCount = 0; } } public int PayloadLength { get { return PayloadLength_Renamed; } } public BytesRef Payload { get { if (PayloadLength_Renamed <= 0) { return null; // no payload } if (NeedToLoadPayload) { // read payloads lazily if (Payload_Renamed == null) { Payload_Renamed = new BytesRef(PayloadLength_Renamed); } else { Payload_Renamed.Grow(PayloadLength_Renamed); } ProxStream.ReadBytes(Payload_Renamed.Bytes, Payload_Renamed.Offset, PayloadLength_Renamed); Payload_Renamed.Length = PayloadLength_Renamed; NeedToLoadPayload = false; } return Payload_Renamed; } } public bool PayloadAvailable { get { return NeedToLoadPayload && PayloadLength_Renamed > 0; } } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.ComponentModel; using Xunit; namespace Moq.Tests { public class MockedDelegatesFixture { [Fact] public void CanMockDelegate() { new Mock<EventHandler>(); } [Fact] public void CannotPassParametersToMockDelegate() { // Pass in parameters that match the delegate signature, // but this still makes absolutely no sense. Assert.Throws<ArgumentException>(() => new Mock<EventHandler>(this, EventArgs.Empty)); } [Fact] public void CanVerifyLooseMockDelegateWithNoReturnValue() { var mockIntAcceptingAction = new Mock<Action<int>>(MockBehavior.Loose); Use(mockIntAcceptingAction.Object, 3); mockIntAcceptingAction.Verify(act => act(3)); } [Fact] public void CanSetupStrictMockDelegateWithNoReturnValue() { var mockIntAcceptingAction = new Mock<Action<int>>(MockBehavior.Strict); mockIntAcceptingAction.Setup(act => act(7)); Use(mockIntAcceptingAction.Object, 7); } [Fact] public void CanVerifyLooseMockDelegateWithReturnValue() { var mockIntAcceptingStringReturningAction = new Mock<Func<int, string>>(MockBehavior.Loose); mockIntAcceptingStringReturningAction .Setup(f => f(It.IsAny<int>())) .Returns("hello"); var result = UseAndGetReturn(mockIntAcceptingStringReturningAction.Object, 96); mockIntAcceptingStringReturningAction .Verify(f => f(96)); Assert.Equal("hello", result); } [Fact] public void CanSubscribeMockDelegateAsEventListener() { var notifyingObject = new NotifyingObject(); var mockListener = new Mock<PropertyChangedEventHandler>(); notifyingObject.PropertyChanged += mockListener.Object; notifyingObject.Value = 5; // That should have caused one event to have been fired. mockListener .Verify(l => l(notifyingObject, It.Is<PropertyChangedEventArgs>(e => e.PropertyName == "Value")), Times.Once()); } [Fact] public void DelegateInterfacesAreReused() { // it's good if multiple mocks for the same delegate (interface) both // consider themselves to be proxying for the same method. var mock1 = new Mock<PropertyChangedEventHandler>(); var mock2 = new Mock<PropertyChangedEventHandler>(); Assert.Same(mock1.Object.Method, mock2.Object.Method); } [Fact] public void CanHandleOutParameterOfActionAsSameAsVoidMethod() { var out1 = 42; var methMock = new Mock<TypeOutAction<int>>(); methMock.Setup(t => t.Invoke(out out1)); var dlgtMock = new Mock<DelegateOutAction<int>>(); dlgtMock.Setup(f => f(out out1)); var methOut1 = default(int); methMock.Object.Invoke(out methOut1); var dlgtOut1 = default(int); dlgtMock.Object(out dlgtOut1); Assert.Equal(methOut1, dlgtOut1); } [Fact] public void CanHandleRefParameterOfActionAsSameAsVoidMethod() { var ref1 = 42; var methMock = new Mock<TypeRefAction<int>>(MockBehavior.Strict); methMock.Setup(t => t.Invoke(ref ref1)); var dlgtMock = new Mock<DelegateRefAction<int>>(MockBehavior.Strict); dlgtMock.Setup(f => f(ref ref1)); var methRef1 = 42; methMock.Object.Invoke(ref methRef1); var dlgtRef1 = 42; dlgtMock.Object(ref dlgtRef1); methMock.VerifyAll(); dlgtMock.VerifyAll(); } [Fact] public void CanHandleOutParameterOfFuncAsSameAsReturnableMethod() { var out1 = 42; var methMock = new Mock<TypeOutFunc<int, int>>(); methMock.Setup(t => t.Invoke(out out1)).Returns(114514); var dlgtMock = new Mock<DelegateOutFunc<int, int>>(); dlgtMock.Setup(f => f(out out1)).Returns(114514); var methOut1 = default(int); var methResult = methMock.Object.Invoke(out methOut1); var dlgtOut1 = default(int); var dlgtResult = dlgtMock.Object(out dlgtOut1); Assert.Equal(methOut1, dlgtOut1); Assert.Equal(methResult, dlgtResult); } [Fact] public void CanHandleRefParameterOfFuncAsSameAsReturnableMethod() { var ref1 = 42; var methMock = new Mock<TypeRefFunc<int, int>>(MockBehavior.Strict); methMock.Setup(t => t.Invoke(ref ref1)).Returns(114514); var dlgtMock = new Mock<DelegateRefFunc<int, int>>(MockBehavior.Strict); dlgtMock.Setup(f => f(ref ref1)).Returns(114514); var methRef1 = 42; var methResult = methMock.Object.Invoke(ref methRef1); var dlgtRef1 = 42; var dlgtResult = dlgtMock.Object(ref dlgtRef1); methMock.VerifyAll(); dlgtMock.VerifyAll(); Assert.Equal(methResult, dlgtResult); } private static void Use(Action<int> action, int valueToPass) { action(valueToPass); } private static string UseAndGetReturn(Func<int, string> func, int valueToPass) { return func(valueToPass); } private class NotifyingObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private int value; public int Value { get { return value; } set { this.value = value; var listeners = PropertyChanged; if (listeners != null) { listeners(this, new PropertyChangedEventArgs("Value")); } } } } public interface TypeOutAction<TOut1> { void Invoke(out TOut1 out1); } public delegate void DelegateOutAction<TOut1>(out TOut1 out1); public interface TypeRefAction<TRef1> { void Invoke(ref TRef1 ref1); } public delegate void DelegateRefAction<TRef1>(ref TRef1 ref1); public interface TypeOutFunc<TOut1, TResult> { TResult Invoke(out TOut1 out1); } public delegate TResult DelegateOutFunc<TOut1, TResult>(out TOut1 out1); public interface TypeRefFunc<TRef1, TResult> { TResult Invoke(ref TRef1 ref1); } public delegate TResult DelegateRefFunc<TRef1, TResult>(ref TRef1 ref1); } }
#region Header /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright (c) 2007-2008 James Nies and NArrange contributors. * All rights reserved. * * This program and the accompanying materials are made available under * the terms of the Common Public License v1.0 which accompanies this * distribution. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *<author>James Nies</author> *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #endregion Header namespace NArrange.Gui.Configuration { using System; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using NArrange.Core; using NArrange.Core.Configuration; /// <summary> /// Control for editing a code configuration. /// </summary> public partial class ConfigurationEditorControl : UserControl { #region Fields /// <summary> /// Code configuration to edit. /// </summary> private CodeConfiguration _configuration; #endregion Fields #region Constructors /// <summary> /// Static constructor. /// </summary> static ConfigurationEditorControl() { // // Register the type descriptor provider for configuration elements. // if (!MonoUtilities.IsMonoRuntime) { TypeDescriptor.AddProvider( new ConfigurationElementTypeDescriptionProvider(typeof(ConfigurationElement)), typeof(ConfigurationElement)); } } /// <summary> /// Creates a new ConfigurationEditorControl. /// </summary> public ConfigurationEditorControl() { InitializeComponent(); } #endregion Constructors #region Properties /// <summary> /// Gets or sets the CodeConfiguration to edit. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public CodeConfiguration Configuration { get { return _configuration; } set { _configuration = value; this.RefreshConfiguration(); if (this._configurationTreeView.TopNode != null) { this._configurationTreeView.TopNode.Expand(); } } } #endregion Properties #region Methods /// <summary> /// Creates a node for a list/collection property. /// </summary> /// <param name="property">The property.</param> /// <param name="component">The component.</param> /// <returns>The tree node.</returns> private static TreeNode CreateListPropertyNode(PropertyDescriptor property, object component) { Type[] newItemTypes = null; if (property.PropertyType == typeof(ConfigurationElementCollection)) { newItemTypes = ConfigurationElementCollectionEditor.ItemTypes; } else if (property.PropertyType == typeof(HandlerConfigurationCollection)) { newItemTypes = new Type[] { typeof(SourceHandlerConfiguration), typeof(ProjectHandlerConfiguration) }; } else if (property.PropertyType == typeof(ExtensionConfigurationCollection)) { newItemTypes = new Type[] { typeof(ExtensionConfiguration) }; } return new ListPropertyTreeNode(property, component, newItemTypes); } /// <summary> /// Adds child tree view nodes under the specified root node using data /// from the configuration object. /// </summary> /// <param name="rootNode">The root node.</param> /// <param name="configurationObject">The configuration.</param> private void AddChildTreeNodes(TreeNode rootNode, object configurationObject) { if (configurationObject != null) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(configurationObject); for (int propertyIndex = 0; propertyIndex < properties.Count; propertyIndex++) { PropertyDescriptor property = properties[propertyIndex]; if (property.IsBrowsable && !(property.PropertyType.IsValueType || property.PropertyType == typeof(string))) { object childPropertyValue = property.GetValue(configurationObject); IList childList = childPropertyValue as IList; TreeNode childNode; if (childList != null) { childNode = CreateListPropertyNode(property, configurationObject); IBindingList childBindingList = childList as IBindingList; if (childBindingList != null) { childBindingList.ListChanged += delegate(object sender, ListChangedEventArgs e) { RefreshListTreeNodes(childNode, property, configurationObject, childBindingList); }; } AddListTreeNodes(childNode, property, configurationObject, childBindingList); } else { childNode = CreatePropertyNode(property, configurationObject); AddChildTreeNodes(childNode, childPropertyValue); } rootNode.Nodes.Add(childNode); } } } } /// <summary> /// Adds nodes for a list. /// </summary> /// <param name="listNode">The list node.</param> /// <param name="listProperty">The list property.</param> /// <param name="component">The component.</param> /// <param name="childList">The child list.</param> private void AddListTreeNodes( TreeNode listNode, PropertyDescriptor listProperty, object component, IList childList) { foreach (object listItem in childList) { TreeNode listItemNode = new ListItemTreeNode(listProperty, component, listItem); listNode.Nodes.Add(listItemNode); AddChildTreeNodes(listItemNode, listItem); } } /// <summary> /// Creates a node for a regular property. /// </summary> /// <param name="property">The property.</param> /// <param name="component">The component.</param> /// <returns>The tree node for the property.</returns> private TreeNode CreatePropertyNode(PropertyDescriptor property, object component) { PropertyTreeNode propertyTreeNode = new PropertyTreeNode(property, component); propertyTreeNode.PropertyValueChanged += delegate(object sender, EventArgs e) { this._propertyGrid.SelectedObject = propertyTreeNode.PropertyValue; }; return propertyTreeNode; } /// <summary> /// Event handler for the tree view KeyDown event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param> private void HandleConfigurationTreeViewKeyDown(object sender, KeyEventArgs e) { ListItemTreeNode listNode = this._configurationTreeView.SelectedNode as ListItemTreeNode; if (listNode != null) { if (e.Control) { if (e.KeyCode == Keys.Up) { // // Move the list item up // listNode.MoveUp(); e.Handled = true; } else if (e.KeyCode == Keys.Down) { // // Move the list item down // listNode.MoveDown(); e.Handled = true; } } else if (e.KeyCode == Keys.Delete) { // // Delete the list item // listNode.RemoveItem(); e.Handled = true; } } } /// <summary> /// Event handler for the property grid PropertyValueChanged event. /// </summary> /// <param name="s">The sender.</param> /// <param name="e">The <see cref="System.Windows.Forms.PropertyValueChangedEventArgs"/> instance containing the event data.</param> private void HandlePropertyGridPropertyValueChanged(object s, PropertyValueChangedEventArgs e) { ListItemTreeNode listItemTreeNode = this._configurationTreeView.SelectedNode as ListItemTreeNode; if (listItemTreeNode != null) { listItemTreeNode.UpdateText(); } } /// <summary> /// Event handler for the tree view NodeSelect event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.Windows.Forms.TreeViewEventArgs"/> instance containing the event data.</param> private void HandleTreeNodeSelect(object sender, TreeViewEventArgs e) { TreeNode selectedNode = _configurationTreeView.SelectedNode; _propertyGrid.SelectedObject = null; if (selectedNode != null) { PropertyTreeNode propertyNode = selectedNode as PropertyTreeNode; if (propertyNode != null && !(propertyNode is ListPropertyTreeNode)) { _propertyGrid.SelectedObject = propertyNode.PropertyValue; } else if (selectedNode.Tag != null && !(selectedNode.Tag is IList)) { _propertyGrid.SelectedObject = selectedNode.Tag; } } } /// <summary> /// Refreshes the UI based on the current configuration instance. /// </summary> private void RefreshConfiguration() { this.RefreshTree(); this._propertyGrid.SelectedObject = _configuration; } /// <summary> /// Refreshes nodes within a list property. /// </summary> /// <param name="listNode">The list node.</param> /// <param name="listProperty">The list property.</param> /// <param name="component">The component.</param> /// <param name="childList">The child list.</param> private void RefreshListTreeNodes(TreeNode listNode, PropertyDescriptor listProperty, object component, IList childList) { for (int itemIndex = 0; itemIndex < childList.Count; itemIndex++) { object listItem = childList[itemIndex]; ListItemTreeNode listItemNode = null; // // Look for an existing node for the list item // for (int nodeIndex = 0; nodeIndex < listNode.Nodes.Count; nodeIndex++) { ListItemTreeNode listItemNodeCandidate = listNode.Nodes[nodeIndex] as ListItemTreeNode; object listItemNodeValue = listItemNodeCandidate.ListItem; if (listItemNodeValue.Equals(listItem)) { listItemNode = listItemNodeCandidate; break; } } if (listItemNode == null) { // Create a new node listItemNode = new ListItemTreeNode(listProperty, component, listItem); listNode.Nodes.Add(listItemNode); AddChildTreeNodes(listItemNode, listItem); } else if (listItemNode.Index != itemIndex) { // Update the node position listNode.Nodes.Remove(listItemNode); listNode.Nodes.Insert(itemIndex, listItemNode); itemIndex = 0; } listItemNode.UpdateMenu(); } // Remove nodes that are no longer present in the list for (int nodeIndex = childList.Count; nodeIndex < listNode.Nodes.Count; nodeIndex++) { listNode.Nodes.RemoveAt(nodeIndex); nodeIndex--; } } /// <summary> /// Refreshes the tree view for the current configuration instance. /// </summary> private void RefreshTree() { this._configurationTreeView.Nodes.Clear(); if (_configuration != null) { TreeNode rootNode = new TreeNode("Code Configuration"); rootNode.Tag = _configuration; this.AddChildTreeNodes(rootNode, _configuration); this._configurationTreeView.Nodes.Add(rootNode); } } #endregion Methods } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedRegionNetworkEndpointGroupsClientSnippets { /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteRegionNetworkEndpointGroupRequest, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) DeleteRegionNetworkEndpointGroupRequest request = new DeleteRegionNetworkEndpointGroupRequest { RequestId = "", Region = "", Project = "", NetworkEndpointGroup = "", }; // Make the request lro::Operation<Operation, Operation> response = regionNetworkEndpointGroupsClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNetworkEndpointGroupsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteRegionNetworkEndpointGroupRequest, CallSettings) // Additional: DeleteAsync(DeleteRegionNetworkEndpointGroupRequest, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) DeleteRegionNetworkEndpointGroupRequest request = new DeleteRegionNetworkEndpointGroupRequest { RequestId = "", Region = "", Project = "", NetworkEndpointGroup = "", }; // Make the request lro::Operation<Operation, Operation> response = await regionNetworkEndpointGroupsClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNetworkEndpointGroupsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, string, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string networkEndpointGroup = ""; // Make the request lro::Operation<Operation, Operation> response = regionNetworkEndpointGroupsClient.Delete(project, region, networkEndpointGroup); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNetworkEndpointGroupsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, string, CallSettings) // Additional: DeleteAsync(string, string, string, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string networkEndpointGroup = ""; // Make the request lro::Operation<Operation, Operation> response = await regionNetworkEndpointGroupsClient.DeleteAsync(project, region, networkEndpointGroup); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNetworkEndpointGroupsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetRegionNetworkEndpointGroupRequest, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) GetRegionNetworkEndpointGroupRequest request = new GetRegionNetworkEndpointGroupRequest { Region = "", Project = "", NetworkEndpointGroup = "", }; // Make the request NetworkEndpointGroup response = regionNetworkEndpointGroupsClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetRegionNetworkEndpointGroupRequest, CallSettings) // Additional: GetAsync(GetRegionNetworkEndpointGroupRequest, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) GetRegionNetworkEndpointGroupRequest request = new GetRegionNetworkEndpointGroupRequest { Region = "", Project = "", NetworkEndpointGroup = "", }; // Make the request NetworkEndpointGroup response = await regionNetworkEndpointGroupsClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, string, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string networkEndpointGroup = ""; // Make the request NetworkEndpointGroup response = regionNetworkEndpointGroupsClient.Get(project, region, networkEndpointGroup); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, string, CallSettings) // Additional: GetAsync(string, string, string, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string networkEndpointGroup = ""; // Make the request NetworkEndpointGroup response = await regionNetworkEndpointGroupsClient.GetAsync(project, region, networkEndpointGroup); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertRegionNetworkEndpointGroupRequest, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) InsertRegionNetworkEndpointGroupRequest request = new InsertRegionNetworkEndpointGroupRequest { RequestId = "", Region = "", Project = "", NetworkEndpointGroupResource = new NetworkEndpointGroup(), }; // Make the request lro::Operation<Operation, Operation> response = regionNetworkEndpointGroupsClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNetworkEndpointGroupsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertRegionNetworkEndpointGroupRequest, CallSettings) // Additional: InsertAsync(InsertRegionNetworkEndpointGroupRequest, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) InsertRegionNetworkEndpointGroupRequest request = new InsertRegionNetworkEndpointGroupRequest { RequestId = "", Region = "", Project = "", NetworkEndpointGroupResource = new NetworkEndpointGroup(), }; // Make the request lro::Operation<Operation, Operation> response = await regionNetworkEndpointGroupsClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNetworkEndpointGroupsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, string, NetworkEndpointGroup, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; NetworkEndpointGroup networkEndpointGroupResource = new NetworkEndpointGroup(); // Make the request lro::Operation<Operation, Operation> response = regionNetworkEndpointGroupsClient.Insert(project, region, networkEndpointGroupResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = regionNetworkEndpointGroupsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, string, NetworkEndpointGroup, CallSettings) // Additional: InsertAsync(string, string, NetworkEndpointGroup, CancellationToken) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; NetworkEndpointGroup networkEndpointGroupResource = new NetworkEndpointGroup(); // Make the request lro::Operation<Operation, Operation> response = await regionNetworkEndpointGroupsClient.InsertAsync(project, region, networkEndpointGroupResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionNetworkEndpointGroupsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListRegionNetworkEndpointGroupsRequest, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) ListRegionNetworkEndpointGroupsRequest request = new ListRegionNetworkEndpointGroupsRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = regionNetworkEndpointGroupsClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (NetworkEndpointGroup item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (NetworkEndpointGroupList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NetworkEndpointGroup item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NetworkEndpointGroup> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NetworkEndpointGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListRegionNetworkEndpointGroupsRequest, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) ListRegionNetworkEndpointGroupsRequest request = new ListRegionNetworkEndpointGroupsRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = regionNetworkEndpointGroupsClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((NetworkEndpointGroup item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((NetworkEndpointGroupList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NetworkEndpointGroup item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NetworkEndpointGroup> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NetworkEndpointGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, string, int?, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = RegionNetworkEndpointGroupsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = regionNetworkEndpointGroupsClient.List(project, region); // Iterate over all response items, lazily performing RPCs as required foreach (NetworkEndpointGroup item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (NetworkEndpointGroupList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NetworkEndpointGroup item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NetworkEndpointGroup> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NetworkEndpointGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, string, int?, CallSettings) // Create client RegionNetworkEndpointGroupsClient regionNetworkEndpointGroupsClient = await RegionNetworkEndpointGroupsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedAsyncEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = regionNetworkEndpointGroupsClient.ListAsync(project, region); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((NetworkEndpointGroup item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((NetworkEndpointGroupList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NetworkEndpointGroup item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NetworkEndpointGroup> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NetworkEndpointGroup item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Threading; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; namespace OpenSim.Region.Framework.Scenes { public partial class Scene { protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent, bool broadcast) { OSChatMessage args = new OSChatMessage(); args.Message = Utils.BytesToString(message); args.Channel = channel; args.Type = type; args.Position = fromPos; args.SenderUUID = fromID; args.Scene = this; if (fromAgent) { ScenePresence user = GetScenePresence(fromID); if (user != null) args.Sender = user.ControllingClient; } else { SceneObjectPart obj = GetSceneObjectPart(fromID); args.SenderObject = obj; } args.From = fromName; //args. if (broadcast) EventManager.TriggerOnChatBroadcast(this, args); else EventManager.TriggerOnChatFromWorld(this, args); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="type"></param> /// <param name="fromPos"></param> /// <param name="fromName"></param> /// <param name="fromAgentID"></param> public void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent) { SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, false); } public void SimChat(string message, ChatTypeEnum type, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent) { SimChat(Utils.StringToBytes(message), type, 0, fromPos, fromName, fromID, fromAgent); } public void SimChat(string message, string fromName) { SimChat(message, ChatTypeEnum.Broadcast, Vector3.Zero, fromName, UUID.Zero, false); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="type"></param> /// <param name="fromPos"></param> /// <param name="fromName"></param> /// <param name="fromAgentID"></param> public void SimChatBroadcast(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent) { SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true); } /// <summary> /// Invoked when the client requests a prim. /// </summary> /// <param name="primLocalID"></param> /// <param name="remoteClient"></param> public void RequestPrim(uint primLocalID, IClientAPI remoteClient) { List<EntityBase> EntityList = GetEntities(); foreach (EntityBase ent in EntityList) { if (ent is SceneObjectGroup) { if (((SceneObjectGroup)ent).LocalId == primLocalID) { ((SceneObjectGroup)ent).SendFullUpdateToClient(remoteClient); return; } } } } /// <summary> /// Invoked when the client selects a prim. /// </summary> /// <param name="primLocalID"></param> /// <param name="remoteClient"></param> public void SelectPrim(uint primLocalID, IClientAPI remoteClient) { List<EntityBase> EntityList = GetEntities(); foreach (EntityBase ent in EntityList) { if (ent is SceneObjectGroup) { if (((SceneObjectGroup) ent).LocalId == primLocalID) { ((SceneObjectGroup) ent).GetProperties(remoteClient); ((SceneObjectGroup) ent).IsSelected = true; // A prim is only tainted if it's allowed to be edited by the person clicking it. if (Permissions.CanEditObject(((SceneObjectGroup)ent).UUID, remoteClient.AgentId) || Permissions.CanMoveObject(((SceneObjectGroup)ent).UUID, remoteClient.AgentId)) { EventManager.TriggerParcelPrimCountTainted(); } break; } else { // We also need to check the children of this prim as they // can be selected as well and send property information bool foundPrim = false; foreach (KeyValuePair<UUID, SceneObjectPart> child in ((SceneObjectGroup) ent).Children) { if (child.Value.LocalId == primLocalID) { child.Value.GetProperties(remoteClient); foundPrim = true; break; } } if (foundPrim) break; } } } } /// <summary> /// Handle the deselection of a prim from the client. /// </summary> /// <param name="primLocalID"></param> /// <param name="remoteClient"></param> public void DeselectPrim(uint primLocalID, IClientAPI remoteClient) { SceneObjectPart part = GetSceneObjectPart(primLocalID); if (part == null) return; // The prim is in the process of being deleted. if (null == part.ParentGroup.RootPart) return; // A deselect packet contains all the local prims being deselected. However, since selection is still // group based we only want the root prim to trigger a full update - otherwise on objects with many prims // we end up sending many duplicate ObjectUpdates if (part.ParentGroup.RootPart.LocalId != part.LocalId) return; bool isAttachment = false; // This is wrong, wrong, wrong. Selection should not be // handled by group, but by prim. Legacy cruft. // TODO: Make selection flagging per prim! // part.ParentGroup.IsSelected = false; if (part.ParentGroup.IsAttachment) isAttachment = true; else part.ParentGroup.ScheduleGroupForFullUpdate(); // If it's not an attachment, and we are allowed to move it, // then we might have done so. If we moved across a parcel // boundary, we will need to recount prims on the parcels. // For attachments, that makes no sense. // if (!isAttachment) { if (Permissions.CanEditObject( part.UUID, remoteClient.AgentId) || Permissions.CanMoveObject( part.UUID, remoteClient.AgentId)) EventManager.TriggerParcelPrimCountTainted(); } } public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount, int transactiontype, string description) { EventManager.MoneyTransferArgs args = new EventManager.MoneyTransferArgs(source, destination, amount, transactiontype, description); EventManager.TriggerMoneyTransfer(this, args); } public virtual void ProcessParcelBuy(UUID agentId, UUID groupId, bool final, bool groupOwned, bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated) { EventManager.LandBuyArgs args = new EventManager.LandBuyArgs(agentId, groupId, final, groupOwned, removeContribution, parcelLocalID, parcelArea, parcelPrice, authenticated); // First, allow all validators a stab at it m_eventManager.TriggerValidateLandBuy(this, args); // Then, check validation and transfer m_eventManager.TriggerLandBuy(this, args); } public virtual void ProcessObjectGrab(uint localID, Vector3 offsetPos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { List<EntityBase> EntityList = GetEntities(); SurfaceTouchEventArgs surfaceArg = null; if (surfaceArgs != null && surfaceArgs.Count > 0) surfaceArg = surfaceArgs[0]; foreach (EntityBase ent in EntityList) { if (ent is SceneObjectGroup) { SceneObjectGroup obj = ent as SceneObjectGroup; if (obj != null) { // Is this prim part of the group if (obj.HasChildPrim(localID)) { // Currently only grab/touch for the single prim // the client handles rez correctly obj.ObjectGrabHandler(localID, offsetPos, remoteClient); SceneObjectPart part = obj.GetChildPart(localID); // If the touched prim handles touches, deliver it // If not, deliver to root prim if ((part.ScriptEvents & scriptEvents.touch_start) != 0) EventManager.TriggerObjectGrab(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg); // Deliver to the root prim if the touched prim doesn't handle touches // or if we're meant to pass on touches anyway. Don't send to root prim // if prim touched is the root prim as we just did it if (((part.ScriptEvents & scriptEvents.touch_start) == 0) || (part.PassTouches && (part.LocalId != obj.RootPart.LocalId))) { EventManager.TriggerObjectGrab(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg); } return; } } } } } public virtual void ProcessObjectDeGrab(uint localID, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { List<EntityBase> EntityList = GetEntities(); SurfaceTouchEventArgs surfaceArg = null; if (surfaceArgs != null && surfaceArgs.Count > 0) surfaceArg = surfaceArgs[0]; foreach (EntityBase ent in EntityList) { if (ent is SceneObjectGroup) { SceneObjectGroup obj = ent as SceneObjectGroup; // Is this prim part of the group if (obj.HasChildPrim(localID)) { SceneObjectPart part=obj.GetChildPart(localID); if (part != null) { // If the touched prim handles touches, deliver it // If not, deliver to root prim if ((part.ScriptEvents & scriptEvents.touch_end) != 0) EventManager.TriggerObjectDeGrab(part.LocalId, 0, remoteClient, surfaceArg); else EventManager.TriggerObjectDeGrab(obj.RootPart.LocalId, part.LocalId, remoteClient, surfaceArg); return; } return; } } } } public void ProcessAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query) { //EventManager.TriggerAvatarPickerRequest(); List<AvatarPickerAvatar> AvatarResponses = new List<AvatarPickerAvatar>(); AvatarResponses = m_sceneGridService.GenerateAgentPickerRequestResponse(RequestID, query); AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket) PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply); // TODO: don't create new blocks if recycling an old packet AvatarPickerReplyPacket.DataBlock[] searchData = new AvatarPickerReplyPacket.DataBlock[AvatarResponses.Count]; AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock(); agentData.AgentID = avatarID; agentData.QueryID = RequestID; replyPacket.AgentData = agentData; //byte[] bytes = new byte[AvatarResponses.Count*32]; int i = 0; foreach (AvatarPickerAvatar item in AvatarResponses) { UUID translatedIDtem = item.AvatarID; searchData[i] = new AvatarPickerReplyPacket.DataBlock(); searchData[i].AvatarID = translatedIDtem; searchData[i].FirstName = Utils.StringToBytes((string) item.firstName); searchData[i].LastName = Utils.StringToBytes((string) item.lastName); i++; } if (AvatarResponses.Count == 0) { searchData = new AvatarPickerReplyPacket.DataBlock[0]; } replyPacket.Data = searchData; AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs(); agent_data.AgentID = replyPacket.AgentData.AgentID; agent_data.QueryID = replyPacket.AgentData.QueryID; List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>(); for (i = 0; i < replyPacket.Data.Length; i++) { AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs(); data_arg.AvatarID = replyPacket.Data[i].AvatarID; data_arg.FirstName = replyPacket.Data[i].FirstName; data_arg.LastName = replyPacket.Data[i].LastName; data_args.Add(data_arg); } client.SendAvatarPickerReply(agent_data, data_args); } public void ProcessScriptReset(IClientAPI remoteClient, UUID objectID, UUID itemID) { SceneObjectPart part=GetSceneObjectPart(objectID); if (part == null) return; if (Permissions.CanResetScript(objectID, itemID, remoteClient.AgentId)) { EventManager.TriggerScriptReset(part.LocalId, itemID); } } /// <summary> /// Handle a fetch inventory request from the client /// </summary> /// <param name="remoteClient"></param> /// <param name="itemID"></param> /// <param name="ownerID"></param> public void HandleFetchInventory(IClientAPI remoteClient, UUID itemID, UUID ownerID) { if (ownerID == CommsManager.UserProfileCacheService.LibraryRoot.Owner) { //m_log.Debug("request info for library item"); return; } InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId); item = InventoryService.GetItem(item); if (item != null) { remoteClient.SendInventoryItemDetails(ownerID, item); } // else shouldn't we send an alert message? } /// <summary> /// Tell the client about the various child items and folders contained in the requested folder. /// </summary> /// <param name="remoteClient"></param> /// <param name="folderID"></param> /// <param name="ownerID"></param> /// <param name="fetchFolders"></param> /// <param name="fetchItems"></param> /// <param name="sortOrder"></param> public void HandleFetchInventoryDescendents(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder) { // FIXME MAYBE: We're not handling sortOrder! // TODO: This code for looking in the folder for the library should be folded back into the // CachedUserInfo so that this class doesn't have to know the details (and so that multiple libraries, etc. // can be handled transparently). InventoryFolderImpl fold = null; if ((fold = CommsManager.UserProfileCacheService.LibraryRoot.FindFolder(folderID)) != null) { remoteClient.SendInventoryFolderDetails( fold.Owner, folderID, fold.RequestListOfItems(), fold.RequestListOfFolders(), fetchFolders, fetchItems); return; } // We're going to send the reply async, because there may be // an enormous quantity of packets -- basically the entire inventory! // We don't want to block the client thread while all that is happening. SendInventoryDelegate d = SendInventoryAsync; d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d); } delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder); void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder) { SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems); } void SendInventoryComplete(IAsyncResult iar) { } /// <summary> /// Handle the caps inventory descendents fetch. /// /// Since the folder structure is sent to the client on login, I believe we only need to handle items. /// Diva comment 8/13/2009: what if someone gave us a folder in the meantime?? /// </summary> /// <param name="agentID"></param> /// <param name="folderID"></param> /// <param name="ownerID"></param> /// <param name="fetchFolders"></param> /// <param name="fetchItems"></param> /// <param name="sortOrder"></param> /// <returns>null if the inventory look up failed</returns> public List<InventoryItemBase> HandleFetchInventoryDescendentsCAPS(UUID agentID, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder) { // m_log.DebugFormat( // "[INVENTORY CACHE]: Fetching folders ({0}), items ({1}) from {2} for agent {3}", // fetchFolders, fetchItems, folderID, agentID); // FIXME MAYBE: We're not handling sortOrder! // TODO: This code for looking in the folder for the library should be folded back into the // CachedUserInfo so that this class doesn't have to know the details (and so that multiple libraries, etc. // can be handled transparently). InventoryFolderImpl fold; if ((fold = CommsManager.UserProfileCacheService.LibraryRoot.FindFolder(folderID)) != null) { return fold.RequestListOfItems(); } InventoryCollection contents = InventoryService.GetFolderContent(agentID, folderID); return contents.Items; } /// <summary> /// Handle an inventory folder creation request from the client. /// </summary> /// <param name="remoteClient"></param> /// <param name="folderID"></param> /// <param name="folderType"></param> /// <param name="folderName"></param> /// <param name="parentID"></param> public void HandleCreateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort folderType, string folderName, UUID parentID) { InventoryFolderBase folder = new InventoryFolderBase(folderID, folderName, remoteClient.AgentId, (short)folderType, parentID, 1); if (!InventoryService.AddFolder(folder)) { m_log.WarnFormat( "[AGENT INVENTORY]: Failed to move create folder for user {0} {1}", remoteClient.Name, remoteClient.AgentId); } } /// <summary> /// Handle a client request to update the inventory folder /// </summary> /// /// FIXME: We call add new inventory folder because in the data layer, we happen to use an SQL REPLACE /// so this will work to rename an existing folder. Needless to say, to rely on this is very confusing, /// and needs to be changed. /// /// <param name="remoteClient"></param> /// <param name="folderID"></param> /// <param name="type"></param> /// <param name="name"></param> /// <param name="parentID"></param> public void HandleUpdateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort type, string name, UUID parentID) { // m_log.DebugFormat( // "[AGENT INVENTORY]: Updating inventory folder {0} {1} for {2} {3}", folderID, name, remoteClient.Name, remoteClient.AgentId); InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId); folder = InventoryService.GetFolder(folder); if (folder != null) { folder.Name = name; folder.Type = (short)type; folder.ParentID = parentID; if (!InventoryService.UpdateFolder(folder)) { m_log.ErrorFormat( "[AGENT INVENTORY]: Failed to update folder for user {0} {1}", remoteClient.Name, remoteClient.AgentId); } } } public void HandleMoveInventoryFolder(IClientAPI remoteClient, UUID folderID, UUID parentID) { InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId); folder = InventoryService.GetFolder(folder); if (folder != null) { folder.ParentID = parentID; if (!InventoryService.MoveFolder(folder)) m_log.WarnFormat("[AGENT INVENTORY]: could not move folder {0}", folderID); else m_log.DebugFormat("[AGENT INVENTORY]: folder {0} moved to parent {1}", folderID, parentID); } else { m_log.WarnFormat("[AGENT INVENTORY]: request to move folder {0} but folder not found", folderID); } } /// <summary> /// This should delete all the items and folders in the given directory. /// </summary> /// <param name="remoteClient"></param> /// <param name="folderID"></param> delegate void PurgeFolderDelegate(UUID userID, UUID folder); public void HandlePurgeInventoryDescendents(IClientAPI remoteClient, UUID folderID) { PurgeFolderDelegate d = PurgeFolderAsync; try { d.BeginInvoke(remoteClient.AgentId, folderID, PurgeFolderCompleted, d); } catch (Exception e) { m_log.WarnFormat("[AGENT INVENTORY]: Exception on purge folder for user {0}: {1}", remoteClient.AgentId, e.Message); } } private void PurgeFolderAsync(UUID userID, UUID folderID) { InventoryFolderBase folder = new InventoryFolderBase(folderID, userID); if (InventoryService.PurgeFolder(folder)) m_log.DebugFormat("[AGENT INVENTORY]: folder {0} purged successfully", folderID); else m_log.WarnFormat("[AGENT INVENTORY]: could not purge folder {0}", folderID); } private void PurgeFolderCompleted(IAsyncResult iar) { } } }
// 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.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.SignatureHelp; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class ObjectCreationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { public ObjectCreationExpressionSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new ObjectCreationExpressionSignatureHelpProvider(); } #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParameters() { var markup = @" class C { void foo() { var c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> C() { } void Foo() { C c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", "Summary for C", null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn1() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C($$2, 3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> C(int a, int b) { } void Foo() { C c = [|new C($$2, 3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param a", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn2() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C(2, $$3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlComentsOn2() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> C(int a, int b) { } void Foo() { C c = [|new C(2, $$3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param b", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParen() { var markup = @" class C { void foo() { var c = [|new C($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParenWithParameters() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C($$2, 3 |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParenWithParametersOn2() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C(2, $$3 |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnLambda() { var markup = @" using System; class C { void foo() { var bar = [|new Action<int, int>($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Action<int, int>(void (int, int) target)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestCurrentParameterName() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(b: string.Empty, $$a: 2|]); } }"; await VerifyCurrentParameterNameAsync(markup, "a"); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerParens() { var markup = @" class C { void foo() { var c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(2,$$string.Empty|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, string b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestNoInvocationOnSpace() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(2, $$string.Empty|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableAlways() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableNever() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableAdvanced() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableMixed() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Foo(int x) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo(long y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(long y)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D { } #endif void foo() { var x = new D($$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D { } #endif #if BAR void foo() { var x = new D($$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // new foo($$"; await TestAsync(markup); } [WorkItem(1078993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078993")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestSigHelpInIncorrectObjectCreationExpression() { var markup = @" class C { void foo(C c) { foo([|new C{$$|] } }"; await TestAsync(markup); } } }
namespace Petstore { using Models; /// <summary> /// This is a sample server Petstore server. You can find out more about /// Swagger at &lt;a /// href="http://swagger.io"&gt;http://swagger.io&lt;/a&gt; or on /// irc.freenode.net, #swagger. For this sample, you can use the api key /// "special-key" to test the authorization filters /// </summary> public partial interface ISwaggerPetstore : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Fake endpoint to test byte array in body parameter for adding a /// new pet to the store /// </summary> /// <param name='body'> /// Pet object in the form of byte array /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> AddPetUsingByteArrayWithHttpMessagesAsync(string body = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Add a new pet to the store /// </summary> /// <remarks> /// Adds a new pet to the store. You may receive an HTTP invalid input /// if your pet is invalid. /// </remarks> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> AddPetWithHttpMessagesAsync(Pet body = default(Pet), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Update an existing pet /// </summary> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> UpdatePetWithHttpMessagesAsync(Pet body = default(Pet), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>>> FindPetsByStatusWithHttpMessagesAsync(System.Collections.Generic.IList<string> status = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use /// tag1, tag2, tag3 for testing. /// </remarks> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>>> FindPetsByTagsWithHttpMessagesAsync(System.Collections.Generic.IList<string> tags = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Fake endpoint to test byte array return by 'Find pet by ID' /// </summary> /// <remarks> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will /// simulate API error conditions /// </remarks> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<string>> FindPetsWithByteArrayWithHttpMessagesAsync(long petId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Find pet by ID /// </summary> /// <remarks> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will /// simulate API error conditions /// </remarks> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Pet>> GetPetByIdWithHttpMessagesAsync(long petId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='petId'> /// ID of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> UpdatePetWithFormWithHttpMessagesAsync(string petId, string name = default(string), string status = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a pet /// </summary> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> DeletePetWithHttpMessagesAsync(long petId, string apiKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// uploads an image /// </summary> /// <param name='petId'> /// ID of pet to update /// </param> /// <param name='additionalMetadata'> /// Additional data to pass to server /// </param> /// <param name='file'> /// file to upload /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> UploadFileWithHttpMessagesAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IDictionary<string, int?>>> GetInventoryWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Place an order for a pet /// </summary> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Order>> PlaceOrderWithHttpMessagesAsync(Order body = default(Order), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Find purchase order by ID /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. /// Other values will generated exceptions /// </remarks> /// <param name='orderId'> /// ID of pet that needs to be fetched /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Order>> GetOrderByIdWithHttpMessagesAsync(string orderId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Delete purchase order by ID /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything /// above 1000 or nonintegers will generate API errors /// </remarks> /// <param name='orderId'> /// ID of the order that needs to be deleted /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> DeleteOrderWithHttpMessagesAsync(string orderId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='body'> /// Created user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> CreateUserWithHttpMessagesAsync(User body = default(User), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> CreateUsersWithArrayInputWithHttpMessagesAsync(System.Collections.Generic.IList<User> body = default(System.Collections.Generic.IList<User>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> CreateUsersWithListInputWithHttpMessagesAsync(System.Collections.Generic.IList<User> body = default(System.Collections.Generic.IList<User>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Logs user into the system /// </summary> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<string>> LoginUserWithHttpMessagesAsync(string username = default(string), string password = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> LogoutUserWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get user by user name /// </summary> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<User>> GetUserByNameWithHttpMessagesAsync(string username, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> UpdateUserWithHttpMessagesAsync(string username, User body = default(User), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> DeleteUserWithHttpMessagesAsync(string username, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit { using System; using BusConfigurators; using EndpointConfigurators; using Magnum.Reflection; using Newtonsoft.Json; using Serialization; public static class SerializerConfigurationExtensions { public static T UseJsonSerializer<T>(this T configurator) where T : EndpointFactoryConfigurator { configurator.SetDefaultSerializer<JsonMessageSerializer>(); return configurator; } public static T ConfigureJsonSerializer<T>(this T configurator, Func<JsonSerializerSettings, JsonSerializerSettings> configure) where T : EndpointFactoryConfigurator { JsonMessageSerializer.SerializerSettings = configure(JsonMessageSerializer.SerializerSettings); return configurator; } public static T ConfigureJsonDeserializer<T>(this T configurator, Func<JsonSerializerSettings, JsonSerializerSettings> configure) where T : EndpointFactoryConfigurator { JsonMessageSerializer.DeserializerSettings = configure(JsonMessageSerializer.DeserializerSettings); return configurator; } public static T UseBsonSerializer<T>(this T configurator) where T : EndpointFactoryConfigurator { configurator.SetDefaultSerializer<BsonMessageSerializer>(); return configurator; } public static T UseXmlSerializer<T>(this T configurator) where T : EndpointFactoryConfigurator { configurator.SetDefaultSerializer<XmlMessageSerializer>(); return configurator; } public static T UseVersionOneXmlSerializer<T>(this T configurator) where T : EndpointFactoryConfigurator { configurator.SetDefaultSerializer<VersionOneXmlMessageSerializer>(); return configurator; } public static T UseBinarySerializer<T>(this T configurator) where T : EndpointFactoryConfigurator { configurator.SetDefaultSerializer<BinaryMessageSerializer>(); return configurator; } /// <summary> /// Support the receipt of messages serialized by the JsonMessageSerializer /// </summary> public static T SupportJsonSerializer<T>(this T configurator) where T : EndpointFactoryConfigurator { configurator.SupportMessageSerializer<JsonMessageSerializer>(); return configurator; } public static T SupportBsonSerializer<T>(this T configurator) where T : EndpointFactoryConfigurator { configurator.SupportMessageSerializer<BsonMessageSerializer>(); return configurator; } public static T SupportXmlSerializer<T>(this T configurator) where T : EndpointFactoryConfigurator { configurator.SupportMessageSerializer<XmlMessageSerializer>(); return configurator; } public static T SupportVersionOneXmlSerializer<T>(this T configurator) where T : EndpointFactoryConfigurator { configurator.SupportMessageSerializer<VersionOneXmlMessageSerializer>(); return configurator; } public static T SupportBinarySerializer<T>(this T configurator) where T : EndpointFactoryConfigurator { configurator.SupportMessageSerializer<BinaryMessageSerializer>(); return configurator; } public static ServiceBusConfigurator SupportMessageSerializer<TSerializer>( this ServiceBusConfigurator configurator) where TSerializer : IMessageSerializer, new() { return SupportMessageSerializer(configurator, () => new TSerializer()); } public static EndpointFactoryConfigurator SupportMessageSerializer<TSerializer>( this EndpointFactoryConfigurator configurator) where TSerializer : IMessageSerializer, new() { return SupportMessageSerializer(configurator, () => new TSerializer()); } static T SetDefaultSerializer<T>(this T configurator, Func<IMessageSerializer> serializerFactory) where T : EndpointFactoryConfigurator { var serializerConfigurator = new DefaultSerializerEndpointFactoryConfigurator(serializerFactory); configurator.AddEndpointFactoryConfigurator(serializerConfigurator); return configurator; } static T SupportMessageSerializer<T>(this T configurator, Func<IMessageSerializer> serializerFactory) where T : EndpointFactoryConfigurator { var serializerConfigurator = new AddSerializerEndpointFactoryConfigurator(serializerFactory); configurator.AddEndpointFactoryConfigurator(serializerConfigurator); return configurator; } /// <summary> /// Sets the default message serializer for endpoints /// </summary> /// <typeparam name="TSerializer"></typeparam> /// <param name="configurator"></param> /// <returns></returns> public static EndpointFactoryConfigurator SetDefaultSerializer<TSerializer>( this EndpointFactoryConfigurator configurator) where TSerializer : IMessageSerializer, new() { return SetDefaultSerializer(configurator, () => new TSerializer()); } /// <summary> /// Sets the default message serializer for endpoints /// </summary> /// <typeparam name="TSerializer"></typeparam> /// <param name="configurator"></param> /// <returns></returns> public static ServiceBusConfigurator SetDefaultSerializer<TSerializer>(this ServiceBusConfigurator configurator) where TSerializer : IMessageSerializer, new() { return SetDefaultSerializer(configurator, () => new TSerializer()); } /// <summary> /// Sets the default message serializer for endpoints /// </summary> /// <param name="configurator"></param> /// <param name="serializerType"></param> /// <returns></returns> public static T SetDefaultSerializer<T>(this T configurator, Type serializerType) where T : EndpointFactoryConfigurator { return SetDefaultSerializer(configurator, () => (IMessageSerializer)FastActivator.Create(serializerType)); } /// <summary> /// Sets the default message serializer for endpoints /// </summary> /// <param name="configurator"></param> /// <param name="serializer"></param> /// <returns></returns> public static T SetDefaultSerializer<T>(this T configurator, IMessageSerializer serializer) where T : EndpointFactoryConfigurator { return SetDefaultSerializer(configurator, () => serializer); } // ----------------------------------------------------------------------- public static ServiceBusConfigurator SetSupportedMessageSerializers<T>( this ServiceBusConfigurator configurator) where T : ISupportedMessageSerializers, new() { return SetSupportedMessageSerializers(configurator, () => new T()); } public static EndpointFactoryConfigurator SetSupportedMessageSerializers<T>( this EndpointFactoryConfigurator configurator) where T : ISupportedMessageSerializers, new() { return SetSupportedMessageSerializers(configurator, () => new T()); } /// <summary> /// Sets the default message serializer for endpoints /// </summary> /// <param name="configurator"></param> /// <param name="supportedSerializer"></param> /// <returns></returns> public static T SetSupportedMessageSerializers<T>(this T configurator, ISupportedMessageSerializers supportedSerializer) where T : EndpointFactoryConfigurator { return SetSupportedMessageSerializers(configurator, () => supportedSerializer); } static T SetSupportedMessageSerializers<T>(this T configurator, Func<ISupportedMessageSerializers> supportedSerializers) where T : EndpointFactoryConfigurator { var serializerConfigurator = new SetSupportedMessageSerializersEndpointFactoryConfigurator(supportedSerializers); configurator.AddEndpointFactoryConfigurator(serializerConfigurator); return configurator; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.PortableExecutable { public class ManagedPEBuilder : PEBuilder { public const int ManagedResourcesDataAlignment = ManagedTextSection.ManagedResourcesDataAlignment; public const int MappedFieldDataAlignment = ManagedTextSection.MappedFieldDataAlignment; private const int DefaultStrongNameSignatureSize = 128; private const string TextSectionName = ".text"; private const string ResourceSectionName = ".rsrc"; private const string RelocationSectionName = ".reloc"; private readonly PEDirectoriesBuilder _peDirectoriesBuilder; private readonly MetadataRootBuilder _metadataRootBuilder; private readonly BlobBuilder _ilStream; private readonly BlobBuilder _mappedFieldDataOpt; private readonly BlobBuilder _managedResourcesOpt; private readonly ResourceSectionBuilder _nativeResourcesOpt; private readonly int _strongNameSignatureSize; private readonly MethodDefinitionHandle _entryPointOpt; private readonly DebugDirectoryBuilder _debugDirectoryBuilderOpt; private readonly CorFlags _corFlags; private int _lazyEntryPointAddress; private Blob _lazyStrongNameSignature; public ManagedPEBuilder( PEHeaderBuilder header, MetadataRootBuilder metadataRootBuilder, BlobBuilder ilStream, BlobBuilder mappedFieldData = null, BlobBuilder managedResources = null, ResourceSectionBuilder nativeResources = null, DebugDirectoryBuilder debugDirectoryBuilder = null, int strongNameSignatureSize = DefaultStrongNameSignatureSize, MethodDefinitionHandle entryPoint = default(MethodDefinitionHandle), CorFlags flags = CorFlags.ILOnly, Func<IEnumerable<Blob>, BlobContentId> deterministicIdProvider = null) : base(header, deterministicIdProvider) { if (header == null) { Throw.ArgumentNull(nameof(header)); } if (metadataRootBuilder == null) { Throw.ArgumentNull(nameof(metadataRootBuilder)); } if (ilStream == null) { Throw.ArgumentNull(nameof(ilStream)); } if (strongNameSignatureSize < 0) { Throw.ArgumentOutOfRange(nameof(strongNameSignatureSize)); } _metadataRootBuilder = metadataRootBuilder; _ilStream = ilStream; _mappedFieldDataOpt = mappedFieldData; _managedResourcesOpt = managedResources; _nativeResourcesOpt = nativeResources; _strongNameSignatureSize = strongNameSignatureSize; _entryPointOpt = entryPoint; _debugDirectoryBuilderOpt = debugDirectoryBuilder ?? CreateDefaultDebugDirectoryBuilder(); _corFlags = flags; _peDirectoriesBuilder = new PEDirectoriesBuilder(); } private DebugDirectoryBuilder CreateDefaultDebugDirectoryBuilder() { if (IsDeterministic) { var builder = new DebugDirectoryBuilder(); builder.AddReproducibleEntry(); return builder; } return null; } protected override ImmutableArray<Section> CreateSections() { var builder = ImmutableArray.CreateBuilder<Section>(3); builder.Add(new Section(TextSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.MemExecute | SectionCharacteristics.ContainsCode)); if (_nativeResourcesOpt != null) { builder.Add(new Section(ResourceSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.ContainsInitializedData)); } if (Header.Machine == Machine.I386 || Header.Machine == 0) { builder.Add(new Section(RelocationSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.MemDiscardable | SectionCharacteristics.ContainsInitializedData)); } return builder.ToImmutable(); } protected override BlobBuilder SerializeSection(string name, SectionLocation location) { switch (name) { case TextSectionName: return SerializeTextSection(location); case ResourceSectionName: return SerializeResourceSection(location); case RelocationSectionName: return SerializeRelocationSection(location); default: throw new ArgumentException(SR.Format(SR.UnknownSectionName, name), nameof(name)); } } private BlobBuilder SerializeTextSection(SectionLocation location) { var sectionBuilder = new BlobBuilder(); var metadataBuilder = new BlobBuilder(); var metadataSizes = _metadataRootBuilder.Sizes; var textSection = new ManagedTextSection( imageCharacteristics: Header.ImageCharacteristics, machine: Header.Machine, ilStreamSize: _ilStream.Count, metadataSize: metadataSizes.MetadataSize, resourceDataSize: _managedResourcesOpt?.Count ?? 0, strongNameSignatureSize: _strongNameSignatureSize, debugDataSize: _debugDirectoryBuilderOpt?.Size ?? 0, mappedFieldDataSize: _mappedFieldDataOpt?.Count ?? 0); int methodBodyStreamRva = location.RelativeVirtualAddress + textSection.OffsetToILStream; int mappedFieldDataStreamRva = location.RelativeVirtualAddress + textSection.CalculateOffsetToMappedFieldDataStream(); _metadataRootBuilder.Serialize(metadataBuilder, methodBodyStreamRva, mappedFieldDataStreamRva); DirectoryEntry debugDirectoryEntry; BlobBuilder debugTableBuilderOpt; if (_debugDirectoryBuilderOpt != null) { int debugDirectoryOffset = textSection.ComputeOffsetToDebugDirectory(); debugTableBuilderOpt = new BlobBuilder(_debugDirectoryBuilderOpt.TableSize); _debugDirectoryBuilderOpt.Serialize(debugTableBuilderOpt, location, debugDirectoryOffset); // Only the size of the fixed part of the debug table goes here. debugDirectoryEntry = new DirectoryEntry( location.RelativeVirtualAddress + debugDirectoryOffset, _debugDirectoryBuilderOpt.TableSize); } else { debugTableBuilderOpt = null; debugDirectoryEntry = default(DirectoryEntry); } _lazyEntryPointAddress = textSection.GetEntryPointAddress(location.RelativeVirtualAddress); textSection.Serialize( sectionBuilder, location.RelativeVirtualAddress, _entryPointOpt.IsNil ? 0 : MetadataTokens.GetToken(_entryPointOpt), _corFlags, Header.ImageBase, metadataBuilder, _ilStream, _mappedFieldDataOpt, _managedResourcesOpt, debugTableBuilderOpt, out _lazyStrongNameSignature); _peDirectoriesBuilder.AddressOfEntryPoint = _lazyEntryPointAddress; _peDirectoriesBuilder.DebugTable = debugDirectoryEntry; _peDirectoriesBuilder.ImportAddressTable = textSection.GetImportAddressTableDirectoryEntry(location.RelativeVirtualAddress); _peDirectoriesBuilder.ImportTable = textSection.GetImportTableDirectoryEntry(location.RelativeVirtualAddress); _peDirectoriesBuilder.CorHeaderTable = textSection.GetCorHeaderDirectoryEntry(location.RelativeVirtualAddress); return sectionBuilder; } private BlobBuilder SerializeResourceSection(SectionLocation location) { Debug.Assert(_nativeResourcesOpt != null); var sectionBuilder = new BlobBuilder(); _nativeResourcesOpt.Serialize(sectionBuilder, location); _peDirectoriesBuilder.ResourceTable = new DirectoryEntry(location.RelativeVirtualAddress, sectionBuilder.Count); return sectionBuilder; } private BlobBuilder SerializeRelocationSection(SectionLocation location) { var sectionBuilder = new BlobBuilder(); WriteRelocationSection(sectionBuilder, Header.Machine, _lazyEntryPointAddress); _peDirectoriesBuilder.BaseRelocationTable = new DirectoryEntry(location.RelativeVirtualAddress, sectionBuilder.Count); return sectionBuilder; } private static void WriteRelocationSection(BlobBuilder builder, Machine machine, int entryPointAddress) { Debug.Assert(builder.Count == 0); builder.WriteUInt32((((uint)entryPointAddress + 2) / 0x1000) * 0x1000); builder.WriteUInt32((machine == Machine.IA64) ? 14u : 12u); uint offsetWithinPage = ((uint)entryPointAddress + 2) % 0x1000; uint relocType = (machine == Machine.Amd64 || machine == Machine.IA64 || machine == Machine.Arm64) ? 10u : 3u; ushort s = (ushort)((relocType << 12) | offsetWithinPage); builder.WriteUInt16(s); if (machine == Machine.IA64) { builder.WriteUInt32(relocType << 12); } builder.WriteUInt16(0); // next chunk's RVA } protected internal override PEDirectoriesBuilder GetDirectories() { return _peDirectoriesBuilder; } public void Sign(BlobBuilder peImage, Func<IEnumerable<Blob>, byte[]> signatureProvider) { if (peImage == null) { Throw.ArgumentNull(nameof(peImage)); } if (signatureProvider == null) { Throw.ArgumentNull(nameof(signatureProvider)); } Sign(peImage, _lazyStrongNameSignature, signatureProvider); } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System.Collections.Generic; using Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.TypeSystem; using Boo.Lang.Compiler.TypeSystem.Core; using Boo.Lang.Compiler.TypeSystem.Internal; namespace Boo.Lang.Compiler.Steps { public class ResolveImports : AbstractTransformerCompilerStep { private readonly Dictionary<string, Import> _namespaces = new Dictionary<string, Import>(); override public void Run() { NameResolutionService.Reset(); Visit(CompileUnit.Modules); } override public void OnModule(Module module) { Visit(module.Imports); _namespaces.Clear(); } public override void OnImport(Import import) { if (IsAlreadyBound(import)) return; if (import.AssemblyReference != null) { ImportFromAssemblyReference(import); return; } var entity = ResolveImport(import); if (HandledAsImportError(import, entity) || HandledAsDuplicatedNamespace(import)) return; Context.TraceInfo("{1}: import reference '{0}' bound to {2}.", import, import.LexicalInfo, entity); import.Entity = ImportedNamespaceFor(import, entity); } private bool HandledAsImportError(Import import, IEntity entity) { if (entity == null) { ImportError(import, CompilerErrorFactory.InvalidNamespace(import)); return true; } if (!IsValidImportTarget(entity)) { ImportError(import, CompilerErrorFactory.NotANamespace(import, entity)); return true; } return false; } private void ImportError(Import import, CompilerError error) { Errors.Add(error); BindError(import); } private void BindError(Import import) { Bind(import, Error.Default); } private static string EffectiveNameForImportedNamespace(Import import) { return null != import.Alias ? import.Alias.Name : import.Namespace; } private bool HandledAsDuplicatedNamespace(Import import) { var actualName = EffectiveNameForImportedNamespace(import); //only add unique namespaces Import cachedImport; if (!_namespaces.TryGetValue(actualName, out cachedImport)) { _namespaces[actualName] = import; return false; } //ignore for partial classes in separate files if (cachedImport.LexicalInfo.FileName == import.LexicalInfo.FileName) Warnings.Add(CompilerWarningFactory.DuplicateNamespace(import, import.Namespace)); BindError(import); return true; } private IEntity ImportedNamespaceFor(Import import, IEntity entity) { var ns = entity as INamespace; if (ns == null) return entity; var selectiveImportSpec = import.Expression as MethodInvocationExpression; var imported = selectiveImportSpec != null ? SelectiveImportFor(ns, selectiveImportSpec) : ns; var actualNamespace = null != import.Alias ? AliasedNamespaceFor(imported, import) : imported; return new ImportedNamespace(import, actualNamespace); } private INamespace SelectiveImportFor(INamespace ns, MethodInvocationExpression selectiveImportSpec) { var importedNames = selectiveImportSpec.Arguments; var entities = new List<IEntity>(importedNames.Count); var aliases = new Dictionary<string,string>(importedNames.Count); foreach (Expression nameExpression in importedNames) { string name; if (nameExpression is ReferenceExpression) { name = (nameExpression as ReferenceExpression).Name; aliases[name] = name; } else { var tce = nameExpression as TryCastExpression; var alias = (tce.Type as SimpleTypeReference).Name; name = (tce.Target as ReferenceExpression).Name; aliases[alias] = name; // Remove the trycast expression, otherwise it gets processed in later steps tce.Target.Annotate("alias", alias); importedNames.Replace(nameExpression, tce.Target); } if (!ns.Resolve(entities, name, EntityType.Any)) Errors.Add( CompilerErrorFactory.MemberNotFound( nameExpression, name, ns, NameResolutionService.GetMostSimilarMemberName(ns, name, EntityType.Any))); } return new SimpleNamespace(null, entities, aliases); } private static INamespace AliasedNamespaceFor(IEntity entity, Import import) { var aliasedNamespace = new AliasedNamespace(import.Alias.Name, entity); import.Alias.Entity = aliasedNamespace; return aliasedNamespace; } private void ImportFromAssemblyReference(Import import) { var resolvedNamespace = ResolveImportAgainstReferencedAssembly(import); if (HandledAsImportError(import, resolvedNamespace)) return; if (HandledAsDuplicatedNamespace(import)) return; import.Entity = ImportedNamespaceFor(import, resolvedNamespace); } private IEntity ResolveImportAgainstReferencedAssembly(Import import) { return NameResolutionService.ResolveQualifiedName(GetBoundReference(import.AssemblyReference).RootNamespace, import.Namespace); } private static bool IsAlreadyBound(Import import) { return import.Entity != null; } private IEntity ResolveImport(Import import) { var entity = ResolveImportOnParentNamespace(import) ?? NameResolutionService.ResolveQualifiedName(import.Namespace); if (null != entity) return entity; //if 'import X', try 'import X from X' if (!TryAutoAddAssemblyReference(import)) return null; return NameResolutionService.ResolveQualifiedName(import.Namespace); } private IEntity ResolveImportOnParentNamespace(Import import) { var current = NameResolutionService.CurrentNamespace; try { INamespace parentNamespace = NameResolutionService.CurrentNamespace.ParentNamespace; if (parentNamespace != null) { NameResolutionService.EnterNamespace(parentNamespace); return NameResolutionService.ResolveQualifiedName(import.Namespace); } } finally { NameResolutionService.EnterNamespace(current); } return null; } private bool TryAutoAddAssemblyReference(Import import) { var existingReference = Parameters.FindAssembly(import.Namespace); if (existingReference != null) return false; var asm = TryToLoadAssemblyContainingNamespace(import.Namespace); if (asm == null) return false; Parameters.References.Add(asm); import.AssemblyReference = new ReferenceExpression(import.LexicalInfo, asm.FullName).WithEntity(asm); NameResolutionService.ClearResolutionCacheFor(asm.Name); return true; } private ICompileUnit TryToLoadAssemblyContainingNamespace(string @namespace) { ICompileUnit asm = Parameters.LoadAssembly(@namespace, false); if (asm != null) return asm; //try to load assemblies name after the parent namespaces var namespaces = @namespace.Split('.'); if (namespaces.Length == 1) return null; for (var level = namespaces.Length - 1; level > 0; level--) { var parentNamespace = string.Join(".", namespaces, 0, level); var existingReference = Parameters.FindAssembly(parentNamespace); if (existingReference != null) return null; var parentNamespaceAssembly = Parameters.LoadAssembly(parentNamespace, false); if (parentNamespaceAssembly != null) return parentNamespaceAssembly; } return null; } private static bool IsValidImportTarget(IEntity entity) { var type = entity.EntityType; return type == EntityType.Namespace || type == EntityType.Type; } static ICompileUnit GetBoundReference(ReferenceExpression reference) { return ((ICompileUnit)TypeSystemServices.GetEntity(reference)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Rsvd; namespace Microsoft.Protocols.TestSuites.FileSharing.RSVD.TestSuite { /// <summary> /// Test Base for all RSVD test cases /// </summary> public abstract class RSVDTestBase : CommonTestBase { #region Variables /// <summary> /// Default Rsvd client /// The instance is created when the test case is initialized /// </summary> protected RsvdClient client; /// <summary> /// Suffix of the shared virtual disk file name /// </summary> protected const string fileNameSuffix = ":SharedVirtualDisk"; /// <summary> /// An unsigned 64-bit value assigned by the client for an outgoing request. /// </summary> protected ulong RequestIdentifier; #endregion public RSVDTestConfig TestConfig { get { return testConfig as RSVDTestConfig; } } protected override void TestInitialize() { base.TestInitialize(); testConfig = new RSVDTestConfig(BaseTestSite); BaseTestSite.DefaultProtocolDocShortName = "MS-RSVD"; client = new RsvdClient(TestConfig.Timeout); RequestIdentifier = 0; // Follow windows client behaviour. Initialize it to zero. // Copy the data used in test cases to the share of the SUT, e.g. the shared virtual disk files. sutProtocolController.CopyFile(TestConfig.FullPathShareContainingSharedVHD, @"data\*.*"); } protected override void TestCleanup() { try { client.Disconnect(); } catch (Exception ex) { BaseTestSite.Log.Add(LogEntryKind.Debug, "Unexpected exception when disconnect client: {0}", ex.ToString()); } client.Dispose(); base.TestCleanup(); } /// <summary> /// Open the shared virtual disk file. /// </summary> /// <param name="fileName">The virtual disk file name to be used</param> /// <param name="version">Version of the open device context</param> /// <param name="openRequestId">OpenRequestId, same with other operations' request id</param> /// <param name="hasInitiatorId">If the SVHDX_OPEN_DEVICE_CONTEXT contains InitiatorId</param> /// <param name="rsvdClient">The instance of rsvd client. NULL stands for the default client</param> public void OpenSharedVHD( string fileName, RSVD_PROTOCOL_VERSION version, ulong? openRequestId = null, bool hasInitiatorId = true, RsvdClient rsvdClient = null) { Smb2CreateContextResponse[] serverContextResponse; OpenSharedVHD(fileName, version, openRequestId, hasInitiatorId, rsvdClient, out serverContextResponse); } /// <summary> /// Open the shared virtual disk file. /// </summary> /// <param name="fileName">The virtual disk file name to be used</param> /// <param name="version">Version of the open device context</param> /// <param name="openRequestId">OpenRequestId, same with other operations' request id</param> /// <param name="hasInitiatorId">If the SVHDX_OPEN_DEVICE_CONTEXT contains InitiatorId</param> /// <param name="rsvdClient">The instance of rsvd client. NULL stands for the default client</param> /// <param name="serverContextResponse">The create context response returned by server</param> public void OpenSharedVHD( string fileName, RSVD_PROTOCOL_VERSION version, ulong? openRequestId, bool hasInitiatorId, RsvdClient rsvdClient, out Smb2CreateContextResponse[] serverContextResponse) { if (rsvdClient == null) rsvdClient = this.client; rsvdClient.Connect( TestConfig.FileServerNameContainingSharedVHD, TestConfig.FileServerIPContainingSharedVHD, TestConfig.DomainName, TestConfig.UserName, TestConfig.UserPassword, TestConfig.DefaultSecurityPackage, TestConfig.UseServerGssToken, TestConfig.ShareContainingSharedVHD); Smb2CreateContextRequest[] contexts = null; if (version == RSVD_PROTOCOL_VERSION.RSVD_PROTOCOL_VERSION_1) { contexts = new Smb2CreateContextRequest[] { new Smb2CreateSvhdxOpenDeviceContext { Version = (uint)version, OriginatorFlags = (uint)OriginatorFlag.SVHDX_ORIGINATOR_PVHDPARSER, InitiatorHostName = TestConfig.InitiatorHostName, InitiatorHostNameLength = (ushort)(TestConfig.InitiatorHostName.Length * 2), OpenRequestId = openRequestId == null ? RequestIdentifier : openRequestId.Value, InitiatorId = hasInitiatorId ? Guid.NewGuid():Guid.Empty, HasInitiatorId = hasInitiatorId } }; } else if (version == RSVD_PROTOCOL_VERSION.RSVD_PROTOCOL_VERSION_2) { contexts = new Smb2CreateContextRequest[] { new Smb2CreateSvhdxOpenDeviceContextV2 { Version = (uint)version, OriginatorFlags = (uint)OriginatorFlag.SVHDX_ORIGINATOR_PVHDPARSER, InitiatorHostName = TestConfig.InitiatorHostName, InitiatorHostNameLength = (ushort)(TestConfig.InitiatorHostName.Length * 2), OpenRequestId = openRequestId == null ? RequestIdentifier : openRequestId.Value, InitiatorId = hasInitiatorId ? Guid.NewGuid():Guid.Empty, HasInitiatorId = hasInitiatorId, VirtualDiskPropertiesInitialized = 0, ServerServiceVersion = 0, VirtualSize = 0, PhysicalSectorSize = 0, VirtualSectorSize = 0 } }; } else { throw new ArgumentException("The ServerServiceVersion {0} is not supported.", "Version"); } CREATE_Response response; uint status = rsvdClient.OpenSharedVirtualDisk( fileName + fileNameSuffix, FsCreateOption.FILE_NO_INTERMEDIATE_BUFFERING, contexts, out serverContextResponse, out response); BaseTestSite.Assert.AreEqual( (uint)Smb2Status.STATUS_SUCCESS, status, "Open shared virtual disk file should succeed, actual status: {0}", GetStatus(status)); } protected void CreateSnapshot(Guid snapshotId) { SVHDX_META_OPERATION_START_REQUEST startRequest = new SVHDX_META_OPERATION_START_REQUEST(); startRequest.TransactionId = Guid.NewGuid(); startRequest.OperationType = Operation_Type.SvhdxMetaOperationTypeCreateSnapshot; SVHDX_META_OPERATION_CREATE_SNAPSHOT createsnapshot = new SVHDX_META_OPERATION_CREATE_SNAPSHOT(); createsnapshot.SnapshotType = Snapshot_Type.SvhdxSnapshotTypeVM; createsnapshot.Flags = Snapshot_Flags.SVHDX_SNAPSHOT_DISK_FLAG_ENABLE_CHANGE_TRACKING; createsnapshot.Stage1 = Stage_Values.SvhdxSnapshotStageInitialize; createsnapshot.SnapshotId = snapshotId; createsnapshot.ParametersPayloadSize = (uint)0x00000000; createsnapshot.Padding = new byte[24]; byte[] payload = client.CreateTunnelMetaOperationStartCreateSnapshotRequest( startRequest, createsnapshot); SVHDX_TUNNEL_OPERATION_HEADER? header; SVHDX_TUNNEL_OPERATION_HEADER? response; //For RSVD_TUNNEL_META_OPERATION_START operation code, the IOCTL code should be FSCTL_SVHDX_ASYNC_TUNNEL_REQUEST uint status = client.TunnelOperation<SVHDX_TUNNEL_OPERATION_HEADER>( true,//true for Async operation, false for non-async operation RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_META_OPERATION_START, ++RequestIdentifier, payload, out header, out response); BaseTestSite.Assert.AreEqual( (uint)Smb2Status.STATUS_SUCCESS, status, "Ioctl should succeed, actual status: {0}", GetStatus(status)); VerifyTunnelOperationHeader(header.Value, RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_META_OPERATION_START, (uint)RsvdStatus.STATUS_SVHDX_SUCCESS, RequestIdentifier); // Add spaces in the beginning of the log to be align with the last test step. Since the steps in this function are only sub steps. BaseTestSite.Log.Add(LogEntryKind.TestStep, " Client sends the second tunnel operation SVHDX_META_OPERATION_START_REQUEST to create a snapshot and expects success."); createsnapshot.Flags = Snapshot_Flags.SVHDX_SNAPSHOT_FLAG_ZERO; createsnapshot.Stage1 = Stage_Values.SvhdxSnapshotStageBlockIO; createsnapshot.Stage2 = Stage_Values.SvhdxSnapshotStageSwitchObjectStore; createsnapshot.Stage3 = Stage_Values.SvhdxSnapshotStageUnblockIO; createsnapshot.Stage4 = Stage_Values.SvhdxSnapshotStageFinalize; payload = client.CreateTunnelMetaOperationStartCreateSnapshotRequest( startRequest, createsnapshot); //For RSVD_TUNNEL_META_OPERATION_START operation code, the IOCTL code should be FSCTL_SVHDX_ASYNC_TUNNEL_REQUEST status = client.TunnelOperation<SVHDX_TUNNEL_OPERATION_HEADER>( true,//true for Async operation, false for non-async operation RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_META_OPERATION_START, ++RequestIdentifier, payload, out header, out response); BaseTestSite.Assert.AreEqual( (uint)Smb2Status.STATUS_SUCCESS, status, "Ioctl should succeed, actual status: {0}", GetStatus(status)); VerifyTunnelOperationHeader(header.Value, RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_META_OPERATION_START, (uint)RsvdStatus.STATUS_SVHDX_SUCCESS, RequestIdentifier); BaseTestSite.Log.Add(LogEntryKind.TestStep, " Verify the snapshot has been created after the operation."); DoUntilSucceed( () => CheckSnapshotExisted(snapshotId), TestConfig.Timeout, "Retry getting the snapshot to make sure it has been created until succeed within timeout span"); } protected void DeleteSnapshot(Guid snapshotId) { SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST deleteRequest = new SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST(); deleteRequest.SnapshotId = snapshotId; deleteRequest.PersistReference = PersistReference_Flags.PersistReferenceFalse; deleteRequest.SnapshotType = Snapshot_Type.SvhdxSnapshotTypeVM; byte[] payload = client.CreateTunnelMetaOperationDeleteSnapshotRequest( deleteRequest); SVHDX_TUNNEL_OPERATION_HEADER? deleteResponse; SVHDX_TUNNEL_OPERATION_HEADER? header; uint status = client.TunnelOperation<SVHDX_TUNNEL_OPERATION_HEADER>( false,//true for Async operation, false for non-async operation RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_DELETE_SNAPSHOT, ++RequestIdentifier, payload, out header, out deleteResponse); BaseTestSite.Assert.AreEqual( (uint)Smb2Status.STATUS_SUCCESS, status, "Ioctl should succeed, actual status: {0}", GetStatus(status)); VerifyTunnelOperationHeader(header.Value, RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_DELETE_SNAPSHOT, (uint)RsvdStatus.STATUS_SVHDX_SUCCESS, RequestIdentifier); } private void CheckSnapshotExisted(Guid snapshotId) { SetFile_InformationType setFileInforType = SetFile_InformationType.SvhdxSetFileInformationTypeSnapshotEntry; Snapshot_Type snapshotType = Snapshot_Type.SvhdxSnapshotTypeVM; SVHDX_TUNNEL_OPERATION_HEADER? header; SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_SNAPSHOT_ENTRY_RESPONSE? snapshotEntryResponse; byte[] payload = client.CreateTunnelGetVHDSetFileInfoRequest( setFileInforType, snapshotType, snapshotId); uint status = client.TunnelOperation<SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_SNAPSHOT_ENTRY_RESPONSE>( false,//true for Async operation, false for non-async operation RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_VHDSET_QUERY_INFORMATION, ++RequestIdentifier, payload, out header, out snapshotEntryResponse); BaseTestSite.Assert.AreEqual( (uint)Smb2Status.STATUS_SUCCESS, status, "Ioctl should succeed, actual status: {0}", GetStatus(status)); VerifyTunnelOperationHeader(header.Value, RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_VHDSET_QUERY_INFORMATION, (uint)RsvdStatus.STATUS_SVHDX_SUCCESS, RequestIdentifier); } public SVHDX_TUNNEL_DISK_INFO_RESPONSE? GetVirtualDiskInfo() { byte[] payload = client.CreateTunnelDiskInfoRequest(); SVHDX_TUNNEL_OPERATION_HEADER? header; SVHDX_TUNNEL_DISK_INFO_RESPONSE? response; uint status = client.TunnelOperation<SVHDX_TUNNEL_DISK_INFO_RESPONSE>( false,//true for Async operation, false for non-async operation RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_GET_DISK_INFO_OPERATION, ++RequestIdentifier, payload, out header, out response); BaseTestSite.Assert.AreEqual( (uint)Smb2Status.STATUS_SUCCESS, status, "Ioctl should succeed, actual status: {0}", GetStatus(status)); VerifyTunnelOperationHeader(header.Value, RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_GET_DISK_INFO_OPERATION, (uint)RsvdStatus.STATUS_SVHDX_SUCCESS, RequestIdentifier); return response; } /// <summary> /// Verify the Tunnel Operation Header /// </summary> /// <param name="header">The received Tunnel Operation Header</param> /// <param name="code">The operation code</param> /// <param name="status">The received status</param> /// <param name="requestId">The request ID</param> public void VerifyTunnelOperationHeader(SVHDX_TUNNEL_OPERATION_HEADER header, RSVD_TUNNEL_OPERATION_CODE code, uint status, ulong requestId) { BaseTestSite.Assert.AreEqual( code, header.OperationCode, "Operation code should be {0}, actual is {1}", code, header.OperationCode); BaseTestSite.Assert.AreEqual( status, header.Status, "Status should be {0}, actual is {1}", GetStatus(status), GetStatus(header.Status)); BaseTestSite.Assert.AreEqual( requestId, header.RequestId, "The RequestId should be {0}, actual is {1}", requestId, header.RequestId); } /// <summary> /// Verify the specific field of response /// </summary> /// <typeparam name="T">The response type</typeparam> /// <param name="fieldName">The field name in response</param> /// <param name="expected">The expected value of the specific field</param> /// <param name="actual">The actual value of the specific field</param> public void VerifyFieldInResponse<T>(string fieldName, T expected, T actual) { BaseTestSite.Assert.AreEqual( expected, actual, fieldName + " should be {0}, actual is {1}", expected, actual); } /// <summary> /// Convert the status from uint to string /// </summary> /// <param name="status">The status in uint</param> /// <returns>The status in string format</returns> public string GetStatus(uint status) { if (Enum.IsDefined(typeof(RsvdStatus), status)) { return ((RsvdStatus)status).ToString(); } return Smb2Status.GetStatusCode(status); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Student History /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SXHI : EduHubEntity { #region Navigation Property Cache private ST Cache_SKEY_ST; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return null; } } #region Field Properties /// <summary> /// Transaction ID (internal) /// </summary> public int TID { get; internal set; } /// <summary> /// Student registration number /// </summary> public int? STREG { get; internal set; } /// <summary> /// Student ID (dynamic link that gets updated whenever ST.STKEY is also updated) /// [Uppercase Alphanumeric (10)] /// </summary> public string SKEY { get; internal set; } /// <summary> /// Student ID (static link that retains its value even if ST.STKEY is updated) /// [Uppercase Alphanumeric (10)] /// </summary> public string HKEY { get; internal set; } /// <summary> /// User ID of person creating the record /// [Uppercase Alphanumeric (128)] /// </summary> public string CREATION_USER { get; internal set; } /// <summary> /// Date of history record creation /// </summary> public DateTime? CREATION_DATE { get; internal set; } /// <summary> /// Time of history record creation /// </summary> public short? CREATION_TIME { get; internal set; } /// <summary> /// User ID of person making the record obsolete /// [Uppercase Alphanumeric (128)] /// </summary> public string OBSOLETE_USER { get; internal set; } /// <summary> /// End date of history record /// </summary> public DateTime? OBSOLETE_DATE { get; internal set; } /// <summary> /// End time of history record /// </summary> public short? OBSOLETE_TIME { get; internal set; } /// <summary> /// Surname /// [Uppercase Alphanumeric (30)] /// </summary> public string SURNAME { get; internal set; } /// <summary> /// First given name /// [Alphanumeric (20)] /// </summary> public string FIRST_NAME { get; internal set; } /// <summary> /// Student status: Active, Inactive, Future, Left school, Delete /// [Uppercase Alphanumeric (4)] /// </summary> public string STATUS { get; internal set; } /// <summary> /// Year level /// [Uppercase Alphanumeric (4)] /// </summary> public string SCHOOL_YEAR { get; internal set; } /// <summary> /// Student's home group + teacher name /// [Alphanumeric (40)] /// </summary> public string HOME_GROUP { get; internal set; } /// <summary> /// Student's prime family (ID + names) /// [Alphanumeric (60)] /// </summary> public string FAMILY { get; internal set; } /// <summary> /// Student's alternative family (ID + names) /// [Alphanumeric (60)] /// </summary> public string FAMB { get; internal set; } /// <summary> /// Student's additional contact family (ID + names) /// [Alphanumeric (60)] /// </summary> public string FAMC { get; internal set; } /// <summary> /// Australian residence status: P=Permanent, T=Temporary /// [Uppercase Alphanumeric (1)] /// </summary> public string RESIDENT_STATUS { get; internal set; } /// <summary> /// Basis of Australian permanent residence status: E=Eligible for Australian passport, A=Holds Australian passport, P=Holds permanent residency visa /// [Uppercase Alphanumeric (1)] /// </summary> public string PERMANENT_BASIS { get; internal set; } /// <summary> /// Visa Sub-class /// [Uppercase Alphanumeric (3)] /// </summary> public string VISA_SUBCLASS { get; internal set; } /// <summary> /// Visa statistical code /// [Uppercase Alphanumeric (4)] /// </summary> public string VISA_STAT_CODE { get; internal set; } /// <summary> /// Visa expiry date /// </summary> public DateTime? VISA_EXPIRY { get; internal set; } /// <summary> /// Student is counted for Student Resource Package (SRP) funding /// [Uppercase Alphanumeric (1)] /// </summary> public string SGB_FUNDED { get; internal set; } /// <summary> /// Time fraction SRP funding for current calendar year /// </summary> public double? SGB_TIME_FRACTION { get; internal set; } /// <summary> /// Time fraction of student's attendance /// </summary> public double? ACTUAL_TIME_FRACTION { get; internal set; } /// <summary> /// Access alert flag /// [Uppercase Alphanumeric (1)] /// </summary> public string ACCESS_ALERT { get; internal set; } /// <summary> /// Restricted access memo /// [Memo] /// </summary> public string ACCESS { get; internal set; } /// <summary> /// Type of access restriction /// [Uppercase Alphanumeric (20)] /// </summary> public string ACCESS_TYPE { get; internal set; } /// <summary> /// School (number + name) to which departed student has gone (if any) /// [Alphanumeric (50)] /// </summary> public string NEXT_SCHOOL { get; internal set; } /// <summary> /// Enrolment date /// </summary> public DateTime? ENTRY { get; internal set; } /// <summary> /// Date of exit from the school /// </summary> public DateTime? EXIT_DATE { get; internal set; } /// <summary> /// International Student Id (7 Numeric) /// [Uppercase Alphanumeric (7)] /// </summary> public string INTERNATIONAL_ST_ID { get; internal set; } /// <summary> /// Student second name /// [Uppercase Alphanumeric (20)] /// </summary> public string SECOND_NAME { get; internal set; } /// <summary> /// Student gender /// [Uppercase Alphanumeric (1)] /// </summary> public string GENDER { get; internal set; } /// <summary> /// Student date of birth /// </summary> public DateTime? BIRTHDATE { get; internal set; } /// <summary> /// Victorian Student Number /// [Uppercase Alphanumeric (12)] /// </summary> public string VSN { get; internal set; } /// <summary> /// One of E=Enrol, C=Change, X = Exit, D=Delete /// [Uppercase Alphanumeric (1)] /// </summary> public string VSR_TYPE { get; internal set; } /// <summary> /// The TID of the SXHI transaction superceded by this one /// </summary> public int? PREVIOUS_TID { get; internal set; } /// <summary> /// Change made to last record to produce this one /// [Alphanumeric (230)] /// </summary> public string CHANGE_MADE { get; internal set; } /// <summary> /// DHHS CRIS ID /// [Uppercase Alphanumeric (9)] /// </summary> public string CRIS_ID { get; internal set; } /// <summary> /// Student's living arrangement (At home with TWO parents/guardians,Home with ONE parent/guardian,Arranged by State - Out-of-home-care,Homeless,Independent) /// [Uppercase Alphanumeric (1)] /// </summary> public string LIVING_ARR { get; internal set; } /// <summary> /// Medical alert flag (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string MEDICAL_ALERT { get; internal set; } /// <summary> /// Unique ID across state (School ID+REGISTRATION) /// [Uppercase Alphanumeric (15)] /// </summary> public string FIRST_REG_NO { get; internal set; } /// <summary> /// Self-described Gender description /// [Alphanumeric (100)] /// </summary> public string GENDER_DESC { get; internal set; } #endregion #region Navigation Properties /// <summary> /// ST (Students) related entity by [SXHI.SKEY]-&gt;[ST.STKEY] /// Student ID (dynamic link that gets updated whenever ST.STKEY is also updated) /// </summary> public ST SKEY_ST { get { if (SKEY == null) { return null; } if (Cache_SKEY_ST == null) { Cache_SKEY_ST = Context.ST.FindBySTKEY(SKEY); } return Cache_SKEY_ST; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using Malware.MDKServices; using MDK.Build.Composers; using MDK.Build.Composers.Default; using MDK.Build.Composers.Minifying; using MDK.Build.Solution; using MDK.Build.TypeTrimming; using MDK.Resources; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.VisualStudio.Shell; using Task = System.Threading.Tasks.Task; namespace MDK.Build { /// <summary> /// A service designed to combine C# class files into a coherent Space Engineers script. /// </summary> public class BuildModule { readonly IProgress<float> _progress; Project[] _scriptProjects; int _steps; /// <summary> /// Creates a new instance of <see cref="BuildModule"/> /// </summary> /// <param name="package"></param> /// <param name="solutionFileName"></param> /// <param name="selectedProjectFullName"></param> /// <param name="progress"></param> public BuildModule(MDKPackage package, [NotNull] string solutionFileName, string selectedProjectFullName = null, IProgress<float> progress = null) { _progress = progress; Package = package; SolutionFileName = Path.GetFullPath(solutionFileName ?? throw new ArgumentNullException(nameof(solutionFileName))); SelectedProjectFileName = selectedProjectFullName != null ? Path.GetFullPath(selectedProjectFullName) : null; SynchronizationContext = SynchronizationContext.Current; } /// <summary> /// The synchronization context the service will use to invoke any callbacks, as it runs asynchronously. /// </summary> public SynchronizationContext SynchronizationContext { get; } /// <summary> /// The <see cref="MDKPackage"/> /// </summary> public MDKPackage Package { get; } /// <summary> /// The file name of the solution to build /// </summary> public string SolutionFileName { get; } /// <summary> /// The file name of the specific project to build, or <c>null</c> if the entire solution should be built /// </summary> public string SelectedProjectFileName { get; } /// <summary> /// The current step index for the build. Moves towards <see cref="TotalSteps"/>. /// </summary> protected int Steps { get => _steps; private set { if (_steps == value) return; _steps = value; FireProgressChange(); } } /// <summary> /// The total number of steps to reach before the build is complete. /// </summary> protected int TotalSteps { get; private set; } async Task<ProgramComposition> ComposeDocumentAsync(Project project, MDKProjectProperties config) { try { var documentComposer = new ProgramDocumentComposer(); return await documentComposer.ComposeAsync(project, config).ConfigureAwait(false); } catch (Exception e) { throw new BuildException(string.Format(Text.BuildModule_LoadContent_Error, project.FilePath), e); } } async void FireProgressChange() { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); OnProgressChanged(); } /// <summary> /// Starts the build. /// </summary> /// <returns>The number of deployed projects</returns> public Task<MDKProjectProperties[]> RunAsync() { return Task.Run(async () => { var scriptProjects = _scriptProjects ?? await LoadScriptProjectsAsync(); var builtScripts = (await Task.WhenAll(scriptProjects.Select(BuildAsync)).ConfigureAwait(false)) .Where(item => item != null) .ToArray(); _scriptProjects = null; return builtScripts; }); } async Task<Project[]> LoadScriptProjectsAsync() { try { var workspace = MSBuildWorkspace.Create(); var solution = await workspace.OpenSolutionAsync(SolutionFileName); var result = solution.Projects.ToArray(); TotalSteps = result.Length * 3; return result; } catch (Exception e) { throw new BuildException(string.Format(Text.BuildModule_LoadScriptProjects_Error, SolutionFileName), e); } } async Task<MDKProjectProperties> BuildAsync(Project project) { var config = LoadConfig(project); if (!config.IsValid) return null; if (SelectedProjectFileName != null) { if (!string.Equals(config.FileName, SelectedProjectFileName, StringComparison.CurrentCultureIgnoreCase)) return null; } if (config.Options.ExcludeFromDeployAll) { return null; } var composition = await ComposeDocumentAsync(project, config); Steps++; if (config.Options.TrimTypes) { var processor = new TypeTrimmer(); composition = await processor.ProcessAsync(composition, config); } ScriptComposer composer; switch (config.Options.MinifyLevel) { case MinifyLevel.Full: composer = new MinifyingComposer(); break; case MinifyLevel.StripComments: composer = new StripCommentsComposer(); break; case MinifyLevel.Lite: composer = new LiteComposer(); break; default: composer = new DefaultComposer(); break; } var script = await ComposeScriptAsync(composition, composer, config).ConfigureAwait(false); Steps++; if (composition.Readme != null) { script = composition.Readme + script; } WriteScript(project, config.Paths.OutputPath, script); Steps++; return config; } async Task<string> ComposeScriptAsync(ProgramComposition composition, ScriptComposer composer, MDKProjectProperties config) { try { var script = await composer.GenerateAsync(composition, config).ConfigureAwait(false); return script; } catch (Exception e) { throw new BuildException(string.Format(Text.BuildModule_GenerateScript_ErrorGeneratingScript, composition.Document.Project.FilePath), e); } } void WriteScript(Project project, string output, string script) { try { var outputInfo = new DirectoryInfo(ExpandMacros(project, Path.Combine(output, project.Name))); if (!outputInfo.Exists) outputInfo.Create(); File.WriteAllText(Path.Combine(outputInfo.FullName, "script.cs"), script.Replace("\r\n", "\n"), Encoding.UTF8); var thumbFile = new FileInfo(Path.Combine(Path.GetDirectoryName(project.FilePath) ?? ".", "thumb.png")); if (thumbFile.Exists) thumbFile.CopyTo(Path.Combine(outputInfo.FullName, "thumb.png"), true); } catch (UnauthorizedAccessException e) { throw new UnauthorizedAccessException(string.Format(Text.BuildModule_WriteScript_UnauthorizedAccess, project.FilePath), e); } catch (Exception e) { throw new BuildException(string.Format(Text.BuildModule_WriteScript_Error, project.FilePath), e); } } MDKProjectProperties LoadConfig(Project project) { try { return MDKProjectProperties.Load(project.FilePath, project.Name); } catch (Exception e) { throw new BuildException(string.Format(Text.BuildModule_LoadConfig_Error, project.FilePath), e); } } string ExpandMacros(Project project, string input) { var replacements = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase) { ["$(projectname)"] = project.Name ?? "" }; foreach (DictionaryEntry envVar in Environment.GetEnvironmentVariables()) replacements[$"%{envVar.Key}%"] = (string)envVar.Value; return Regex.Replace(input, @"\$\(ProjectName\)|%[^%]+%", match => { if (replacements.TryGetValue(match.Value, out var value)) { return value; } return match.Value; }, RegexOptions.IgnoreCase); } /// <summary> /// Called when the current build progress changes. /// </summary> protected virtual void OnProgressChanged() { var progress = (float)Steps / TotalSteps; _progress?.Report(progress); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AsSingle() { var test = new VectorAs__AsSingle(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorAs__AsSingle { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector256<Single> value; value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector256<Single> value; value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<byte> byteResult = value.As<Single, byte>(); ValidateResult(byteResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<double> doubleResult = value.As<Single, double>(); ValidateResult(doubleResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<short> shortResult = value.As<Single, short>(); ValidateResult(shortResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<int> intResult = value.As<Single, int>(); ValidateResult(intResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<long> longResult = value.As<Single, long>(); ValidateResult(longResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<sbyte> sbyteResult = value.As<Single, sbyte>(); ValidateResult(sbyteResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<float> floatResult = value.As<Single, float>(); ValidateResult(floatResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<ushort> ushortResult = value.As<Single, ushort>(); ValidateResult(ushortResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<uint> uintResult = value.As<Single, uint>(); ValidateResult(uintResult, value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); Vector256<ulong> ulongResult = value.As<Single, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector256<Single> value; value = Vector256.Create(TestLibrary.Generator.GetSingle()); object byteResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsByte)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<byte>)(byteResult), value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); object doubleResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsDouble)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<double>)(doubleResult), value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); object shortResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt16)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<short>)(shortResult), value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); object intResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt32)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<int>)(intResult), value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); object longResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt64)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<long>)(longResult), value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); object sbyteResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsSByte)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<sbyte>)(sbyteResult), value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); object floatResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsSingle)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<float>)(floatResult), value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); object ushortResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt16)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<ushort>)(ushortResult), value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); object uintResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt32)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<uint>)(uintResult), value); value = Vector256.Create(TestLibrary.Generator.GetSingle()); object ulongResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt64)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector256<T> result, Vector256<Single> value, [CallerMemberName] string method = "") where T : struct { Single[] resultElements = new Single[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result); Single[] valueElements = new Single[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(Single[] resultElements, Single[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Single>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the MamEstadioClinico class. /// </summary> [Serializable] public partial class MamEstadioClinicoCollection : ActiveList<MamEstadioClinico, MamEstadioClinicoCollection> { public MamEstadioClinicoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>MamEstadioClinicoCollection</returns> public MamEstadioClinicoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { MamEstadioClinico o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the MAM_EstadioClinico table. /// </summary> [Serializable] public partial class MamEstadioClinico : ActiveRecord<MamEstadioClinico>, IActiveRecord { #region .ctors and Default Settings public MamEstadioClinico() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public MamEstadioClinico(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public MamEstadioClinico(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public MamEstadioClinico(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("MAM_EstadioClinico", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdEstadioClinico = new TableSchema.TableColumn(schema); colvarIdEstadioClinico.ColumnName = "idEstadioClinico"; colvarIdEstadioClinico.DataType = DbType.Int32; colvarIdEstadioClinico.MaxLength = 0; colvarIdEstadioClinico.AutoIncrement = true; colvarIdEstadioClinico.IsNullable = false; colvarIdEstadioClinico.IsPrimaryKey = true; colvarIdEstadioClinico.IsForeignKey = false; colvarIdEstadioClinico.IsReadOnly = false; colvarIdEstadioClinico.DefaultSetting = @""; colvarIdEstadioClinico.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstadioClinico); TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema); colvarIdPaciente.ColumnName = "idPaciente"; colvarIdPaciente.DataType = DbType.Int32; colvarIdPaciente.MaxLength = 0; colvarIdPaciente.AutoIncrement = false; colvarIdPaciente.IsNullable = false; colvarIdPaciente.IsPrimaryKey = false; colvarIdPaciente.IsForeignKey = true; colvarIdPaciente.IsReadOnly = false; colvarIdPaciente.DefaultSetting = @"((0))"; colvarIdPaciente.ForeignKeyTableName = "Sys_Paciente"; schema.Columns.Add(colvarIdPaciente); TableSchema.TableColumn colvarIdCentroSalud = new TableSchema.TableColumn(schema); colvarIdCentroSalud.ColumnName = "idCentroSalud"; colvarIdCentroSalud.DataType = DbType.Int32; colvarIdCentroSalud.MaxLength = 0; colvarIdCentroSalud.AutoIncrement = false; colvarIdCentroSalud.IsNullable = false; colvarIdCentroSalud.IsPrimaryKey = false; colvarIdCentroSalud.IsForeignKey = true; colvarIdCentroSalud.IsReadOnly = false; colvarIdCentroSalud.DefaultSetting = @"((0))"; colvarIdCentroSalud.ForeignKeyTableName = "Sys_Efector"; schema.Columns.Add(colvarIdCentroSalud); TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema); colvarEdad.ColumnName = "edad"; colvarEdad.DataType = DbType.Int32; colvarEdad.MaxLength = 0; colvarEdad.AutoIncrement = false; colvarEdad.IsNullable = false; colvarEdad.IsPrimaryKey = false; colvarEdad.IsForeignKey = false; colvarEdad.IsReadOnly = false; colvarEdad.DefaultSetting = @"((0))"; colvarEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarEdad); TableSchema.TableColumn colvarFechaRegistro = new TableSchema.TableColumn(schema); colvarFechaRegistro.ColumnName = "fechaRegistro"; colvarFechaRegistro.DataType = DbType.DateTime; colvarFechaRegistro.MaxLength = 0; colvarFechaRegistro.AutoIncrement = false; colvarFechaRegistro.IsNullable = false; colvarFechaRegistro.IsPrimaryKey = false; colvarFechaRegistro.IsForeignKey = false; colvarFechaRegistro.IsReadOnly = false; colvarFechaRegistro.DefaultSetting = @"(((1)/(1))/(1900))"; colvarFechaRegistro.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaRegistro); TableSchema.TableColumn colvarIdIndicadorT = new TableSchema.TableColumn(schema); colvarIdIndicadorT.ColumnName = "idIndicadorT"; colvarIdIndicadorT.DataType = DbType.Int32; colvarIdIndicadorT.MaxLength = 0; colvarIdIndicadorT.AutoIncrement = false; colvarIdIndicadorT.IsNullable = false; colvarIdIndicadorT.IsPrimaryKey = false; colvarIdIndicadorT.IsForeignKey = false; colvarIdIndicadorT.IsReadOnly = false; colvarIdIndicadorT.DefaultSetting = @"((0))"; colvarIdIndicadorT.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdIndicadorT); TableSchema.TableColumn colvarIdIndicadorN = new TableSchema.TableColumn(schema); colvarIdIndicadorN.ColumnName = "idIndicadorN"; colvarIdIndicadorN.DataType = DbType.Int32; colvarIdIndicadorN.MaxLength = 0; colvarIdIndicadorN.AutoIncrement = false; colvarIdIndicadorN.IsNullable = false; colvarIdIndicadorN.IsPrimaryKey = false; colvarIdIndicadorN.IsForeignKey = false; colvarIdIndicadorN.IsReadOnly = false; colvarIdIndicadorN.DefaultSetting = @"((0))"; colvarIdIndicadorN.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdIndicadorN); TableSchema.TableColumn colvarIdIndicadorM = new TableSchema.TableColumn(schema); colvarIdIndicadorM.ColumnName = "idIndicadorM"; colvarIdIndicadorM.DataType = DbType.Int32; colvarIdIndicadorM.MaxLength = 0; colvarIdIndicadorM.AutoIncrement = false; colvarIdIndicadorM.IsNullable = false; colvarIdIndicadorM.IsPrimaryKey = false; colvarIdIndicadorM.IsForeignKey = false; colvarIdIndicadorM.IsReadOnly = false; colvarIdIndicadorM.DefaultSetting = @"((0))"; colvarIdIndicadorM.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdIndicadorM); TableSchema.TableColumn colvarIdEstadio = new TableSchema.TableColumn(schema); colvarIdEstadio.ColumnName = "idEstadio"; colvarIdEstadio.DataType = DbType.Int32; colvarIdEstadio.MaxLength = 0; colvarIdEstadio.AutoIncrement = false; colvarIdEstadio.IsNullable = false; colvarIdEstadio.IsPrimaryKey = false; colvarIdEstadio.IsForeignKey = false; colvarIdEstadio.IsReadOnly = false; colvarIdEstadio.DefaultSetting = @"((0))"; colvarIdEstadio.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstadio); TableSchema.TableColumn colvarIdProfesional = new TableSchema.TableColumn(schema); colvarIdProfesional.ColumnName = "idProfesional"; colvarIdProfesional.DataType = DbType.Int32; colvarIdProfesional.MaxLength = 0; colvarIdProfesional.AutoIncrement = false; colvarIdProfesional.IsNullable = false; colvarIdProfesional.IsPrimaryKey = false; colvarIdProfesional.IsForeignKey = true; colvarIdProfesional.IsReadOnly = false; colvarIdProfesional.DefaultSetting = @"((0))"; colvarIdProfesional.ForeignKeyTableName = "Sys_Profesional"; schema.Columns.Add(colvarIdProfesional); TableSchema.TableColumn colvarActivo = new TableSchema.TableColumn(schema); colvarActivo.ColumnName = "activo"; colvarActivo.DataType = DbType.Boolean; colvarActivo.MaxLength = 0; colvarActivo.AutoIncrement = false; colvarActivo.IsNullable = false; colvarActivo.IsPrimaryKey = false; colvarActivo.IsForeignKey = false; colvarActivo.IsReadOnly = false; colvarActivo.DefaultSetting = @"((1))"; colvarActivo.ForeignKeyTableName = ""; schema.Columns.Add(colvarActivo); TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema); colvarCreatedBy.ColumnName = "CreatedBy"; colvarCreatedBy.DataType = DbType.String; colvarCreatedBy.MaxLength = 50; colvarCreatedBy.AutoIncrement = false; colvarCreatedBy.IsNullable = false; colvarCreatedBy.IsPrimaryKey = false; colvarCreatedBy.IsForeignKey = false; colvarCreatedBy.IsReadOnly = false; colvarCreatedBy.DefaultSetting = @"('')"; colvarCreatedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedBy); TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema); colvarCreatedOn.ColumnName = "CreatedOn"; colvarCreatedOn.DataType = DbType.DateTime; colvarCreatedOn.MaxLength = 0; colvarCreatedOn.AutoIncrement = false; colvarCreatedOn.IsNullable = false; colvarCreatedOn.IsPrimaryKey = false; colvarCreatedOn.IsForeignKey = false; colvarCreatedOn.IsReadOnly = false; colvarCreatedOn.DefaultSetting = @"(((1)/(1))/(1900))"; colvarCreatedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedOn); TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema); colvarModifiedBy.ColumnName = "ModifiedBy"; colvarModifiedBy.DataType = DbType.String; colvarModifiedBy.MaxLength = 50; colvarModifiedBy.AutoIncrement = false; colvarModifiedBy.IsNullable = false; colvarModifiedBy.IsPrimaryKey = false; colvarModifiedBy.IsForeignKey = false; colvarModifiedBy.IsReadOnly = false; colvarModifiedBy.DefaultSetting = @"('')"; colvarModifiedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedBy); TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema); colvarModifiedOn.ColumnName = "ModifiedOn"; colvarModifiedOn.DataType = DbType.DateTime; colvarModifiedOn.MaxLength = 0; colvarModifiedOn.AutoIncrement = false; colvarModifiedOn.IsNullable = false; colvarModifiedOn.IsPrimaryKey = false; colvarModifiedOn.IsForeignKey = false; colvarModifiedOn.IsReadOnly = false; colvarModifiedOn.DefaultSetting = @"(((1)/(1))/(1900))"; colvarModifiedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedOn); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("MAM_EstadioClinico",schema); } } #endregion #region Props [XmlAttribute("IdEstadioClinico")] [Bindable(true)] public int IdEstadioClinico { get { return GetColumnValue<int>(Columns.IdEstadioClinico); } set { SetColumnValue(Columns.IdEstadioClinico, value); } } [XmlAttribute("IdPaciente")] [Bindable(true)] public int IdPaciente { get { return GetColumnValue<int>(Columns.IdPaciente); } set { SetColumnValue(Columns.IdPaciente, value); } } [XmlAttribute("IdCentroSalud")] [Bindable(true)] public int IdCentroSalud { get { return GetColumnValue<int>(Columns.IdCentroSalud); } set { SetColumnValue(Columns.IdCentroSalud, value); } } [XmlAttribute("Edad")] [Bindable(true)] public int Edad { get { return GetColumnValue<int>(Columns.Edad); } set { SetColumnValue(Columns.Edad, value); } } [XmlAttribute("FechaRegistro")] [Bindable(true)] public DateTime FechaRegistro { get { return GetColumnValue<DateTime>(Columns.FechaRegistro); } set { SetColumnValue(Columns.FechaRegistro, value); } } [XmlAttribute("IdIndicadorT")] [Bindable(true)] public int IdIndicadorT { get { return GetColumnValue<int>(Columns.IdIndicadorT); } set { SetColumnValue(Columns.IdIndicadorT, value); } } [XmlAttribute("IdIndicadorN")] [Bindable(true)] public int IdIndicadorN { get { return GetColumnValue<int>(Columns.IdIndicadorN); } set { SetColumnValue(Columns.IdIndicadorN, value); } } [XmlAttribute("IdIndicadorM")] [Bindable(true)] public int IdIndicadorM { get { return GetColumnValue<int>(Columns.IdIndicadorM); } set { SetColumnValue(Columns.IdIndicadorM, value); } } [XmlAttribute("IdEstadio")] [Bindable(true)] public int IdEstadio { get { return GetColumnValue<int>(Columns.IdEstadio); } set { SetColumnValue(Columns.IdEstadio, value); } } [XmlAttribute("IdProfesional")] [Bindable(true)] public int IdProfesional { get { return GetColumnValue<int>(Columns.IdProfesional); } set { SetColumnValue(Columns.IdProfesional, value); } } [XmlAttribute("Activo")] [Bindable(true)] public bool Activo { get { return GetColumnValue<bool>(Columns.Activo); } set { SetColumnValue(Columns.Activo, value); } } [XmlAttribute("CreatedBy")] [Bindable(true)] public string CreatedBy { get { return GetColumnValue<string>(Columns.CreatedBy); } set { SetColumnValue(Columns.CreatedBy, value); } } [XmlAttribute("CreatedOn")] [Bindable(true)] public DateTime CreatedOn { get { return GetColumnValue<DateTime>(Columns.CreatedOn); } set { SetColumnValue(Columns.CreatedOn, value); } } [XmlAttribute("ModifiedBy")] [Bindable(true)] public string ModifiedBy { get { return GetColumnValue<string>(Columns.ModifiedBy); } set { SetColumnValue(Columns.ModifiedBy, value); } } [XmlAttribute("ModifiedOn")] [Bindable(true)] public DateTime ModifiedOn { get { return GetColumnValue<DateTime>(Columns.ModifiedOn); } set { SetColumnValue(Columns.ModifiedOn, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysEfector ActiveRecord object related to this MamEstadioClinico /// /// </summary> public DalSic.SysEfector SysEfector { get { return DalSic.SysEfector.FetchByID(this.IdCentroSalud); } set { SetColumnValue("idCentroSalud", value.IdEfector); } } /// <summary> /// Returns a SysPaciente ActiveRecord object related to this MamEstadioClinico /// /// </summary> public DalSic.SysPaciente SysPaciente { get { return DalSic.SysPaciente.FetchByID(this.IdPaciente); } set { SetColumnValue("idPaciente", value.IdPaciente); } } /// <summary> /// Returns a SysProfesional ActiveRecord object related to this MamEstadioClinico /// /// </summary> public DalSic.SysProfesional SysProfesional { get { return DalSic.SysProfesional.FetchByID(this.IdProfesional); } set { SetColumnValue("idProfesional", value.IdProfesional); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdPaciente,int varIdCentroSalud,int varEdad,DateTime varFechaRegistro,int varIdIndicadorT,int varIdIndicadorN,int varIdIndicadorM,int varIdEstadio,int varIdProfesional,bool varActivo,string varCreatedBy,DateTime varCreatedOn,string varModifiedBy,DateTime varModifiedOn) { MamEstadioClinico item = new MamEstadioClinico(); item.IdPaciente = varIdPaciente; item.IdCentroSalud = varIdCentroSalud; item.Edad = varEdad; item.FechaRegistro = varFechaRegistro; item.IdIndicadorT = varIdIndicadorT; item.IdIndicadorN = varIdIndicadorN; item.IdIndicadorM = varIdIndicadorM; item.IdEstadio = varIdEstadio; item.IdProfesional = varIdProfesional; item.Activo = varActivo; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdEstadioClinico,int varIdPaciente,int varIdCentroSalud,int varEdad,DateTime varFechaRegistro,int varIdIndicadorT,int varIdIndicadorN,int varIdIndicadorM,int varIdEstadio,int varIdProfesional,bool varActivo,string varCreatedBy,DateTime varCreatedOn,string varModifiedBy,DateTime varModifiedOn) { MamEstadioClinico item = new MamEstadioClinico(); item.IdEstadioClinico = varIdEstadioClinico; item.IdPaciente = varIdPaciente; item.IdCentroSalud = varIdCentroSalud; item.Edad = varEdad; item.FechaRegistro = varFechaRegistro; item.IdIndicadorT = varIdIndicadorT; item.IdIndicadorN = varIdIndicadorN; item.IdIndicadorM = varIdIndicadorM; item.IdEstadio = varIdEstadio; item.IdProfesional = varIdProfesional; item.Activo = varActivo; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdEstadioClinicoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdPacienteColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdCentroSaludColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn EdadColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn FechaRegistroColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn IdIndicadorTColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn IdIndicadorNColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn IdIndicadorMColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn IdEstadioColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn IdProfesionalColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn ActivoColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn CreatedByColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn CreatedOnColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn ModifiedByColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn ModifiedOnColumn { get { return Schema.Columns[14]; } } #endregion #region Columns Struct public struct Columns { public static string IdEstadioClinico = @"idEstadioClinico"; public static string IdPaciente = @"idPaciente"; public static string IdCentroSalud = @"idCentroSalud"; public static string Edad = @"edad"; public static string FechaRegistro = @"fechaRegistro"; public static string IdIndicadorT = @"idIndicadorT"; public static string IdIndicadorN = @"idIndicadorN"; public static string IdIndicadorM = @"idIndicadorM"; public static string IdEstadio = @"idEstadio"; public static string IdProfesional = @"idProfesional"; public static string Activo = @"activo"; public static string CreatedBy = @"CreatedBy"; public static string CreatedOn = @"CreatedOn"; public static string ModifiedBy = @"ModifiedBy"; public static string ModifiedOn = @"ModifiedOn"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.EventGrid { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// EventSubscriptionsOperations operations. /// </summary> public partial interface IEventSubscriptionsOperations { /// <summary> /// Get an event subscription /// </summary> /// <remarks> /// Get properties of an event subscription /// </remarks> /// <param name='scope'> /// The scope of the event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscription>> GetWithHttpMessagesAsync(string scope, string eventSubscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create an event subscription /// </summary> /// <remarks> /// Asynchronously creates a new event subscription to the specified /// scope. Existing event subscriptions cannot be updated with this API /// and should instead use the Update event subscription API. /// </remarks> /// <param name='scope'> /// The scope of the resource to which the event subscription needs to /// be created. The scope can be a subscription, or a resource group, /// or a top level resource belonging to a resource provider namespace, /// or an EventGrid topic. For example, use /// '/subscriptions/{subscriptionId}/' for a subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription to be created. Event subscription /// names must be between 3 and 64 characters in length and use /// alphanumeric letters only. /// </param> /// <param name='eventSubscriptionInfo'> /// Event subscription properties containing the destination and filter /// information /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscription>> CreateWithHttpMessagesAsync(string scope, string eventSubscriptionName, EventSubscription eventSubscriptionInfo, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an event subscription /// </summary> /// <remarks> /// Delete an existing event subscription /// </remarks> /// <param name='scope'> /// The scope of the event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string scope, string eventSubscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update an event subscription /// </summary> /// <remarks> /// Asynchronously updates an existing event subscription. /// </remarks> /// <param name='scope'> /// The scope of existing event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription to be created /// </param> /// <param name='eventSubscriptionUpdateParameters'> /// Updated event subscription information /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscription>> UpdateWithHttpMessagesAsync(string scope, string eventSubscriptionName, EventSubscriptionUpdateParameters eventSubscriptionUpdateParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get full URL of an event subscription /// </summary> /// <remarks> /// Get the full endpoint URL for an event subscription /// </remarks> /// <param name='scope'> /// The scope of the event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscriptionFullUrl>> GetFullUrlWithHttpMessagesAsync(string scope, string eventSubscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an aggregated list of all global event subscriptions under an /// Azure subscription /// </summary> /// <remarks> /// List all aggregated global event subscriptions under a specific /// Azure subscription /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListGlobalBySubscriptionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all global event subscriptions for a topic type /// </summary> /// <remarks> /// List all global event subscriptions under an Azure subscription for /// a topic type. /// </remarks> /// <param name='topicTypeName'> /// Name of the topic type /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListGlobalBySubscriptionForTopicTypeWithHttpMessagesAsync(string topicTypeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all global event subscriptions under an Azure subscription and /// resource group /// </summary> /// <remarks> /// List all global event subscriptions under a specific Azure /// subscription and resource group /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListGlobalByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all global event subscriptions under a resource group for a /// topic type /// </summary> /// <remarks> /// List all global event subscriptions under a resource group for a /// specific topic type. /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='topicTypeName'> /// Name of the topic type /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListGlobalByResourceGroupForTopicTypeWithHttpMessagesAsync(string resourceGroupName, string topicTypeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all regional event subscriptions under an Azure subscription /// </summary> /// <remarks> /// List all event subscriptions from the given location under a /// specific Azure subscription /// </remarks> /// <param name='location'> /// Name of the location /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListRegionalBySubscriptionWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all regional event subscriptions under an Azure subscription /// and resource group /// </summary> /// <remarks> /// List all event subscriptions from the given location under a /// specific Azure subscription and resource group /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='location'> /// Name of the location /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListRegionalByResourceGroupWithHttpMessagesAsync(string resourceGroupName, string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all regional event subscriptions under an Azure subscription /// for a topic type /// </summary> /// <remarks> /// List all event subscriptions from the given location under a /// specific Azure subscription and topic type. /// </remarks> /// <param name='location'> /// Name of the location /// </param> /// <param name='topicTypeName'> /// Name of the topic type /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListRegionalBySubscriptionForTopicTypeWithHttpMessagesAsync(string location, string topicTypeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all regional event subscriptions under an Azure subscription /// and resource group for a topic type /// </summary> /// <remarks> /// List all event subscriptions from the given location under a /// specific Azure subscription and resource group and topic type /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='location'> /// Name of the location /// </param> /// <param name='topicTypeName'> /// Name of the topic type /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListRegionalByResourceGroupForTopicTypeWithHttpMessagesAsync(string resourceGroupName, string location, string topicTypeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all event subscriptions for a specific topic /// </summary> /// <remarks> /// List all event subscriptions that have been created for a specific /// topic /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='providerNamespace'> /// Namespace of the provider of the topic /// </param> /// <param name='resourceTypeName'> /// Name of the resource type /// </param> /// <param name='resourceName'> /// Name of the resource /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<EventSubscription>>> ListByResourceWithHttpMessagesAsync(string resourceGroupName, string providerNamespace, string resourceTypeName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create an event subscription /// </summary> /// <remarks> /// Asynchronously creates a new event subscription to the specified /// scope. Existing event subscriptions cannot be updated with this API /// and should instead use the Update event subscription API. /// </remarks> /// <param name='scope'> /// The scope of the resource to which the event subscription needs to /// be created. The scope can be a subscription, or a resource group, /// or a top level resource belonging to a resource provider namespace, /// or an EventGrid topic. For example, use /// '/subscriptions/{subscriptionId}/' for a subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription to be created. Event subscription /// names must be between 3 and 64 characters in length and use /// alphanumeric letters only. /// </param> /// <param name='eventSubscriptionInfo'> /// Event subscription properties containing the destination and filter /// information /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscription>> BeginCreateWithHttpMessagesAsync(string scope, string eventSubscriptionName, EventSubscription eventSubscriptionInfo, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an event subscription /// </summary> /// <remarks> /// Delete an existing event subscription /// </remarks> /// <param name='scope'> /// The scope of the event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string scope, string eventSubscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update an event subscription /// </summary> /// <remarks> /// Asynchronously updates an existing event subscription. /// </remarks> /// <param name='scope'> /// The scope of existing event subscription. The scope can be a /// subscription, or a resource group, or a top level resource /// belonging to a resource provider namespace, or an EventGrid topic. /// For example, use '/subscriptions/{subscriptionId}/' for a /// subscription, /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' /// for a resource group, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' /// for a resource, and /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' /// for an EventGrid topic. /// </param> /// <param name='eventSubscriptionName'> /// Name of the event subscription to be created /// </param> /// <param name='eventSubscriptionUpdateParameters'> /// Updated event subscription information /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EventSubscription>> BeginUpdateWithHttpMessagesAsync(string scope, string eventSubscriptionName, EventSubscriptionUpdateParameters eventSubscriptionUpdateParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The Windows Forms user interface layer for the DotSpatial.Symbology library. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 5/4/2009 1:56:04 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.ComponentModel; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// LineJoinControl /// </summary> [DefaultEvent("ValueChanged"), DefaultProperty("Value")] public class LineJoinControl : UserControl { #region Events /// <summary> /// Occurs when one of the radio buttons is clicked, changing the current value. /// </summary> public event EventHandler ValueChanged; #endregion #region Private Variables private LineJoinType _joinType; private GroupBox grpLineJoins; private RadioButton radBevel; private RadioButton radMiter; private RadioButton radRound; #endregion #region Constructors /// <summary> /// Creates a new instance of LineJoinControl /// </summary> public LineJoinControl() { InitializeComponent(); } #endregion #region Methods /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { ComponentResourceManager resources = new ComponentResourceManager(typeof(LineJoinControl)); this.grpLineJoins = new GroupBox(); this.radBevel = new RadioButton(); this.radRound = new RadioButton(); this.radMiter = new RadioButton(); this.grpLineJoins.SuspendLayout(); this.SuspendLayout(); // // grpLineJoins // this.grpLineJoins.AccessibleDescription = null; this.grpLineJoins.AccessibleName = null; resources.ApplyResources(this.grpLineJoins, "grpLineJoins"); this.grpLineJoins.BackgroundImage = null; this.grpLineJoins.Controls.Add(this.radBevel); this.grpLineJoins.Controls.Add(this.radRound); this.grpLineJoins.Controls.Add(this.radMiter); this.grpLineJoins.Font = null; this.grpLineJoins.Name = "grpLineJoins"; this.grpLineJoins.TabStop = false; this.grpLineJoins.Enter += this.grpLineJoins_Enter; // // radBevel // this.radBevel.AccessibleDescription = null; this.radBevel.AccessibleName = null; resources.ApplyResources(this.radBevel, "radBevel"); this.radBevel.BackgroundImage = null; this.radBevel.Font = null; this.radBevel.Name = "radBevel"; this.radBevel.UseVisualStyleBackColor = true; this.radBevel.CheckedChanged += this.radBevel_CheckedChanged; // // radRound // this.radRound.AccessibleDescription = null; this.radRound.AccessibleName = null; resources.ApplyResources(this.radRound, "radRound"); this.radRound.BackgroundImage = null; this.radRound.Checked = true; this.radRound.Font = null; this.radRound.Name = "radRound"; this.radRound.TabStop = true; this.radRound.UseVisualStyleBackColor = true; this.radRound.CheckedChanged += this.radRound_CheckedChanged; // // radMiter // this.radMiter.AccessibleDescription = null; this.radMiter.AccessibleName = null; resources.ApplyResources(this.radMiter, "radMiter"); this.radMiter.BackgroundImage = null; this.radMiter.Font = null; this.radMiter.Name = "radMiter"; this.radMiter.UseVisualStyleBackColor = true; this.radMiter.CheckedChanged += this.radMiter_CheckedChanged; // // LineJoinControl // this.AccessibleDescription = null; this.AccessibleName = null; resources.ApplyResources(this, "$this"); this.BackgroundImage = null; this.Controls.Add(this.grpLineJoins); this.Font = null; this.Name = "LineJoinControl"; this.grpLineJoins.ResumeLayout(false); this.grpLineJoins.PerformLayout(); this.ResumeLayout(false); } #endregion #region Properties /// <summary> /// Gets or sets the string text /// </summary> public override string Text { get { if (grpLineJoins != null) return grpLineJoins.Text; return null; } set { if (grpLineJoins != null) grpLineJoins.Text = value; } } /// <summary> /// Gets or sets the current line join type shown by the control. /// </summary> public LineJoinType Value { get { return _joinType; } set { _joinType = value; switch (value) { case LineJoinType.Bevel: radBevel.Checked = true; break; case LineJoinType.Mitre: radMiter.Checked = true; break; case LineJoinType.Round: radRound.Checked = true; break; } } } #endregion #region Protected Methods /// <summary> /// Fires the on value changed event /// </summary> protected virtual void OnValueChanged() { if (ValueChanged != null) ValueChanged(this, EventArgs.Empty); } #endregion private void radMiter_CheckedChanged(object sender, EventArgs e) { if (radMiter.Checked && _joinType != LineJoinType.Mitre) { _joinType = LineJoinType.Mitre; OnValueChanged(); } } private void radRound_CheckedChanged(object sender, EventArgs e) { if (radRound.Checked && _joinType != LineJoinType.Round) { _joinType = LineJoinType.Round; OnValueChanged(); } } private void radBevel_CheckedChanged(object sender, EventArgs e) { if (radBevel.Checked && _joinType != LineJoinType.Bevel) { _joinType = LineJoinType.Bevel; OnValueChanged(); } } private void grpLineJoins_Enter(object sender, EventArgs e) { } } }
using System.Collections.Generic; using System.Text.RegularExpressions; namespace HappyFunTimes { public interface IHFTArg { void Init(string name, HFTArgParser p); } public class HFTArgHelper<T> { public T Value { get { return value_; } } public bool IsSet { get { return isSet_; } } public bool GetIfSet(ref T variable) { if (IsSet) { variable = Value; } return IsSet; } protected T value_; protected bool isSet_ = false; } public class HFTArg<T> : HFTArgHelper<T> { public void Init(string name, HFTArgParser p) { isSet_ = p.TryGet<T>(name, ref value_); } } public class HFTArgBool : HFTArgHelper<bool> { public void Init(string name, HFTArgParser p) { isSet_ = p.TryGetBool(name, ref value_); } } public class HFTArgChecker { public HFTArgChecker(HFTLog log, string prefix) { log_ = log; prefix_ = prefix + "-"; dashPrefix_ = "--" + prefix; noPrefix_ = "--no-" + prefix; } public void AddArg(string arg) { validArgs_.Add(arg); } public bool CheckArgs() { bool good = true; #if (!UNITY_IOS) string[] args = System.Environment.GetCommandLineArgs(); foreach (string arg in args) { if (arg.StartsWith(dashPrefix_)) { int equalsNdx = arg.IndexOf('='); string checkArg = equalsNdx >= 0 ? arg.Substring(0, equalsNdx) : arg; if (!validArgs_.Contains(checkArg.Substring(2))) { good = false; log_.Warn("unknown option: " + arg); } } else if (arg.StartsWith(noPrefix_)) { int equalsNdx = arg.IndexOf('='); string checkArg = equalsNdx >= 0 ? arg.Substring(0, equalsNdx) : arg; if (!validArgs_.Contains(checkArg.Substring(5))) { good = false; log_.Warn("unknown option: " + arg); } } } #endif foreach (string evar in System.Environment.GetEnvironmentVariables().Keys) { string opt = evar.ToLowerInvariant().Replace("_", "-"); if (opt.StartsWith(prefix_)) { if (!validArgs_.Contains(opt)) { good = false; log_.Warn("unknown environment variable: " + evar); } } } return good; } public string GetHFTDashName(string camelCase) { return prefix_ + s_camelRE.Replace(camelCase, s_camelReplace).ToLower(); } HFTLog log_; string prefix_; string dashPrefix_; string noPrefix_; HashSet<string> validArgs_ = new HashSet<string>(); static string s_camelReplace = @"-$1$2"; static Regex s_camelRE = new Regex(@"([A-Z])([a-z0-9])", RegexOptions.Singleline); } // Is this a good thing? No idea. It's D.R.Y. It's also auto-completeable in the // editor where as using a dict or somethig is not. And it checks for bad arguments so uses // could possibly get help. public class HFTArgsBase { public HFTArgsBase(string prefix) { HFTLog log = new HFTLog("HFTArgs"); HFTArgChecker checker = new HFTArgChecker(log, prefix); HFTArgParser p = HFTArgParser.GetInstance(); System.Reflection.FieldInfo[] fields = this.GetType().GetFields(); foreach (System.Reflection.FieldInfo info in fields) { object field = System.Activator.CreateInstance(info.FieldType); string dashName = checker.GetHFTDashName(info.Name); checker.AddArg(dashName); info.FieldType.GetMethod("Init").Invoke(field, new object[]{ dashName, p }); info.SetValue(this, field); } checker.CheckArgs(); } } // This class fills in the args directly from public fields of // sub classes. Where as HFTArgsBase above gets the fields // but also records if they were set or not. Not sure that's a good thing public class HFTArgsToFields { public static bool Apply(string prefix, object obj) { HFTLog log = new HFTLog("HFTArgsDirect"); HFTArgChecker checker = new HFTArgChecker(log, prefix); HFTArgParser p = HFTArgParser.GetInstance(); System.Reflection.FieldInfo[] fields = obj.GetType().GetFields(); foreach (System.Reflection.FieldInfo info in fields) { //object field = System.Activator.CreateInstance(info.FieldType); object value = null; System.Type fieldType = info.FieldType; string dashName = checker.GetHFTDashName(info.Name); checker.AddArg(dashName); // Should do this with reflection but ... if (fieldType == typeof(string)) { string strValue = ""; if (p.TryGet<string>(dashName, ref strValue)) { value = strValue; } } else if (fieldType == typeof(int)) { int intValue = 0; if (p.TryGet<int>(dashName, ref intValue)) { value = intValue; } } else if (fieldType == typeof(bool)) { bool boolValue = false; if (p.TryGetBool(dashName, ref boolValue)) { value = boolValue; } } else if (fieldType == typeof(float)) { float floatValue = 0; if (p.TryGet<float>(dashName, ref floatValue)) { value = floatValue; } } else { throw new System.InvalidOperationException("no support for type: " + fieldType.Name); } if (value != null) { info.SetValue(obj, value); } } return checker.CheckArgs(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using System.IO; using System.Text; using System.Text.Encodings.Web; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.TagHelpers.Cache; using Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers; using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.Mvc.TagHelpers { /// <summary> /// <see cref="TagHelper"/> implementation targeting &lt;cache&gt; elements. /// </summary> public class CacheTagHelper : CacheTagHelperBase { /// <summary> /// Prefix used by <see cref="CacheTagHelper"/> instances when creating entries in <see cref="MemoryCache"/>. /// </summary> public static readonly string CacheKeyPrefix = nameof(CacheTagHelper); private const string CachePriorityAttributeName = "priority"; // We need to come up with a value for the size of entries when storing a gating Task on the cache. Any value // greater than 0 will suffice. We choose 56 bytes as an approximation of the size of the task that we store // in the cache. This size got calculated as an upper bound for the size of an actual task on an x64 architecture // and corresponds to 24 bytes for the object header block plus the 40 bytes added by the members of the task // object. private const int PlaceholderSize = 64; /// <summary> /// Creates a new <see cref="CacheTagHelper"/>. /// </summary> /// <param name="factory">The factory containing the private <see cref="IMemoryCache"/> instance /// used by the <see cref="CacheTagHelper"/>.</param> /// <param name="htmlEncoder">The <see cref="HtmlEncoder"/> to use.</param> public CacheTagHelper( CacheTagHelperMemoryCacheFactory factory, HtmlEncoder htmlEncoder) : base(htmlEncoder) { MemoryCache = factory.Cache; } /// <summary> /// Gets the <see cref="IMemoryCache"/> instance used to cache entries. /// </summary> protected IMemoryCache MemoryCache { get; } /// <summary> /// Gets or sets the <see cref="CacheItemPriority"/> policy for the cache entry. /// </summary> [HtmlAttributeName(CachePriorityAttributeName)] public CacheItemPriority? Priority { get; set; } /// <inheritdoc /> public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } IHtmlContent content; if (Enabled) { var cacheKey = new CacheTagKey(this, context); if (MemoryCache.TryGetValue(cacheKey, out Task<IHtmlContent> cachedResult)) { // There is either some value already cached (as a Task) or a worker processing the output. content = await cachedResult; } else { content = await CreateCacheEntry(cacheKey, output); } } else { content = await output.GetChildContentAsync(); } // Clear the contents of the "cache" element since we don't want to render it. output.SuppressOutput(); output.Content.SetHtmlContent(content); } private async Task<IHtmlContent> CreateCacheEntry(CacheTagKey cacheKey, TagHelperOutput output) { var tokenSource = new CancellationTokenSource(); var options = GetMemoryCacheEntryOptions(); options.AddExpirationToken(new CancellationChangeToken(tokenSource.Token)); options.SetSize(PlaceholderSize); var tcs = new TaskCompletionSource<IHtmlContent>(creationOptions: TaskCreationOptions.RunContinuationsAsynchronously); // The returned value is ignored, we only do this so that // the compiler doesn't complain about the returned task // not being awaited _ = MemoryCache.Set(cacheKey, tcs.Task, options); IHtmlContent content; try { // The entry is set instead of assigning a value to the // task so that the expiration options are not impacted // by the time it took to compute it. // Use the CreateEntry to ensure a cache scope is created that will copy expiration tokens from // cache entries created from the GetChildContentAsync call to the current entry. var entry = MemoryCache.CreateEntry(cacheKey); // The result is processed inside an entry // such that the tokens are inherited. var result = ProcessContentAsync(output); content = await result; options.SetSize(GetSize(content)); entry.SetOptions(options); entry.Value = result; // An entry gets committed to the cache when disposed gets called. We only want to do this when // the content has been correctly generated (didn't throw an exception). For that reason the entry // can't be put inside a using block. entry.Dispose(); // Set the result on the TCS once we've committed the entry to the cache since commiting to the cache // may throw. tcs.SetResult(content); return content; } catch (Exception ex) { // Remove the worker task from the cache in case it can't complete. tokenSource.Cancel(); // Fail the TCS so other awaiters see the exception. tcs.TrySetException(ex); throw; } finally { // The tokenSource needs to be disposed as the MemoryCache // will register a callback on the Token. tokenSource.Dispose(); } } private long GetSize(IHtmlContent content) { if (content is CharBufferHtmlContent charBuffer) { // We need to multiply the size of the buffer // by a factor of two due to the fact that // characters in .NET are UTF-16 which means // every character uses two bytes (surrogates // are represented as two characters) return charBuffer.Buffer.Length * sizeof(char); } Debug.Fail($"{nameof(content)} should be an {nameof(CharBufferHtmlContent)}."); return -1; } // Internal for unit testing internal MemoryCacheEntryOptions GetMemoryCacheEntryOptions() { var hasEvictionCriteria = false; var options = new MemoryCacheEntryOptions(); if (ExpiresOn != null) { hasEvictionCriteria = true; options.SetAbsoluteExpiration(ExpiresOn.Value); } if (ExpiresAfter != null) { hasEvictionCriteria = true; options.SetAbsoluteExpiration(ExpiresAfter.Value); } if (ExpiresSliding != null) { hasEvictionCriteria = true; options.SetSlidingExpiration(ExpiresSliding.Value); } if (Priority != null) { options.SetPriority(Priority.Value); } if (!hasEvictionCriteria) { options.SetSlidingExpiration(DefaultExpiration); } return options; } private async Task<IHtmlContent> ProcessContentAsync(TagHelperOutput output) { var content = await output.GetChildContentAsync(); using (var writer = new CharBufferTextWriter()) { content.WriteTo(writer, HtmlEncoder); return new CharBufferHtmlContent(writer.Buffer); } } private class CharBufferTextWriter : TextWriter { public CharBufferTextWriter() { Buffer = new PagedCharBuffer(CharArrayBufferSource.Instance); } public override Encoding Encoding => Null.Encoding; public PagedCharBuffer Buffer { get; } public override void Write(char value) { Buffer.Append(value); } public override void Write(char[] buffer, int index, int count) { Buffer.Append(buffer, index, count); } public override void Write(string value) { Buffer.Append(value); } } private class CharBufferHtmlContent : IHtmlContent { private readonly PagedCharBuffer _buffer; public CharBufferHtmlContent(PagedCharBuffer buffer) { _buffer = buffer; } public PagedCharBuffer Buffer => _buffer; public void WriteTo(TextWriter writer, HtmlEncoder encoder) { var length = Buffer.Length; if (length == 0) { return; } for (var i = 0; i < Buffer.Pages.Count; i++) { var page = Buffer.Pages[i]; var pageLength = Math.Min(length, page.Length); writer.Write(page, index: 0, count: pageLength); length -= pageLength; } Debug.Assert(length == 0); } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml; using System.Globalization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data. /// </summary> public class JsonTextReader : JsonReader, IJsonLineInfo { private enum ReadType { Read, ReadAsBytes, ReadAsDecimal, #if !NET20 ReadAsDateTimeOffset #endif } private readonly TextReader _reader; private readonly StringBuffer _buffer; private char? _lastChar; private int _currentLinePosition; private int _currentLineNumber; private bool _end; private ReadType _readType; /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> /// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param> public JsonTextReader(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); _reader = reader; _buffer = new StringBuffer(4096); _currentLineNumber = 1; } private void ParseString(char quote) { ReadStringIntoBuffer(quote); if (_readType == ReadType.ReadAsBytes) { byte[] data; if (_buffer.Position == 0) { data = new byte[0]; } else { data = Convert.FromBase64CharArray(_buffer.GetInternalBuffer(), 0, _buffer.Position); _buffer.Position = 0; } SetToken(JsonToken.Bytes, data); } else { string text = _buffer.ToString(); _buffer.Position = 0; if (text.StartsWith("/Date(", StringComparison.Ordinal) && text.EndsWith(")/", StringComparison.Ordinal)) { ParseDate(text); } else { SetToken(JsonToken.String, text); QuoteChar = quote; } } } private void ReadStringIntoBuffer(char quote) { while (true) { char currentChar = MoveNext(); switch (currentChar) { case '\0': if (_end) throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, _currentLineNumber, _currentLinePosition); _buffer.Append('\0'); break; case '\\': if ((currentChar = MoveNext()) != '\0' || !_end) { switch (currentChar) { case 'b': _buffer.Append('\b'); break; case 't': _buffer.Append('\t'); break; case 'n': _buffer.Append('\n'); break; case 'f': _buffer.Append('\f'); break; case 'r': _buffer.Append('\r'); break; case '\\': _buffer.Append('\\'); break; case '"': case '\'': case '/': _buffer.Append(currentChar); break; case 'u': char[] hexValues = new char[4]; for (int i = 0; i < hexValues.Length; i++) { if ((currentChar = MoveNext()) != '\0' || !_end) hexValues[i] = currentChar; else throw CreateJsonReaderException("Unexpected end while parsing unicode character. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } char hexChar = Convert.ToChar(int.Parse(new string(hexValues), NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo)); _buffer.Append(hexChar); break; default: throw CreateJsonReaderException("Bad JSON escape sequence: {0}. Line {1}, position {2}.", @"\" + currentChar, _currentLineNumber, _currentLinePosition); } } else { throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, _currentLineNumber, _currentLinePosition); } break; case '"': case '\'': if (currentChar == quote) { return; } else { _buffer.Append(currentChar); } break; default: _buffer.Append(currentChar); break; } } } private JsonReaderException CreateJsonReaderException(string format, params object[] args) { string message = format.FormatWith(CultureInfo.InvariantCulture, args); return new JsonReaderException(message, null, _currentLineNumber, _currentLinePosition); } private TimeSpan ReadOffset(string offsetText) { bool negative = (offsetText[0] == '-'); int hours = int.Parse(offsetText.Substring(1, 2), NumberStyles.Integer, CultureInfo.InvariantCulture); int minutes = 0; if (offsetText.Length >= 5) minutes = int.Parse(offsetText.Substring(3, 2), NumberStyles.Integer, CultureInfo.InvariantCulture); TimeSpan offset = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes); if (negative) offset = offset.Negate(); return offset; } private void ParseDate(string text) { string value = text.Substring(6, text.Length - 8); DateTimeKind kind = DateTimeKind.Utc; int index = value.IndexOf('+', 1); if (index == -1) index = value.IndexOf('-', 1); TimeSpan offset = TimeSpan.Zero; if (index != -1) { kind = DateTimeKind.Local; offset = ReadOffset(value.Substring(index)); value = value.Substring(0, index); } long javaScriptTicks = long.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture); DateTime utcDateTime = JsonConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks); #if !NET20 if (_readType == ReadType.ReadAsDateTimeOffset) { SetToken(JsonToken.Date, new DateTimeOffset(utcDateTime.Add(offset).Ticks, offset)); } else #endif { DateTime dateTime; switch (kind) { case DateTimeKind.Unspecified: dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified); break; case DateTimeKind.Local: dateTime = utcDateTime.ToLocalTime(); break; default: dateTime = utcDateTime; break; } SetToken(JsonToken.Date, dateTime); } } private const int LineFeedValue = StringUtils.LineFeed; private const int CarriageReturnValue = StringUtils.CarriageReturn; private char MoveNext() { int value = _reader.Read(); switch (value) { case -1: _end = true; return '\0'; case CarriageReturnValue: if (_reader.Peek() == LineFeedValue) _reader.Read(); _currentLineNumber++; _currentLinePosition = 0; break; case LineFeedValue: _currentLineNumber++; _currentLinePosition = 0; break; default: _currentLinePosition++; break; } return (char)value; } private bool HasNext() { return (_reader.Peek() != -1); } private int PeekNext() { return _reader.Peek(); } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns> /// true if the next token was read successfully; false if there are no more tokens to read. /// </returns> public override bool Read() { _readType = ReadType.Read; return ReadInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>. /// </summary> /// <returns> /// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. /// </returns> public override byte[] ReadAsBytes() { _readType = ReadType.ReadAsBytes; do { if (!ReadInternal()) throw CreateJsonReaderException("Unexpected end when reading bytes: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.Bytes) return (byte[]) Value; throw CreateJsonReaderException("Unexpected token when reading bytes: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>.</returns> public override decimal? ReadAsDecimal() { _readType = ReadType.ReadAsDecimal; do { if (!ReadInternal()) throw CreateJsonReaderException("Unexpected end when reading decimal: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.Float) return (decimal?)Value; decimal d; if (TokenType == JsonToken.String && decimal.TryParse((string)Value, NumberStyles.Number, CultureInfo.InvariantCulture, out d)) { SetToken(JsonToken.Float, d); return d; } throw CreateJsonReaderException("Unexpected token when reading decimal: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition); } #if !NET20 /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="DateTimeOffset"/>.</returns> public override DateTimeOffset? ReadAsDateTimeOffset() { _readType = ReadType.ReadAsDateTimeOffset; do { if (!ReadInternal()) throw CreateJsonReaderException("Unexpected end when reading date: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.Date) return (DateTimeOffset)Value; throw CreateJsonReaderException("Unexpected token when reading date: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition); } #endif private bool ReadInternal() { while (true) { char currentChar; if (_lastChar != null) { currentChar = _lastChar.Value; _lastChar = null; } else { currentChar = MoveNext(); } if (currentChar == '\0' && _end) return false; switch (CurrentState) { case State.Start: case State.Property: case State.Array: case State.ArrayStart: case State.Constructor: case State.ConstructorStart: return ParseValue(currentChar); case State.Complete: break; case State.Object: case State.ObjectStart: return ParseObject(currentChar); case State.PostValue: // returns true if it hits // end of object or array if (ParsePostValue(currentChar)) return true; break; case State.Closed: break; case State.Error: break; default: throw CreateJsonReaderException("Unexpected state: {0}. Line {1}, position {2}.", CurrentState, _currentLineNumber, _currentLinePosition); } } } private bool ParsePostValue(char currentChar) { do { switch (currentChar) { case '}': SetToken(JsonToken.EndObject); return true; case ']': SetToken(JsonToken.EndArray); return true; case ')': SetToken(JsonToken.EndConstructor); return true; case '/': ParseComment(); return true; case ',': // finished parsing SetStateBasedOnCurrent(); return false; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: // eat break; default: if (char.IsWhiteSpace(currentChar)) { // eat } else { throw CreateJsonReaderException("After parsing a value an unexpected character was encountered: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } break; } } while ((currentChar = MoveNext()) != '\0' || !_end); return false; } private bool ParseObject(char currentChar) { do { switch (currentChar) { case '}': SetToken(JsonToken.EndObject); return true; case '/': ParseComment(); return true; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: // eat break; default: if (char.IsWhiteSpace(currentChar)) { // eat } else { return ParseProperty(currentChar); } break; } } while ((currentChar = MoveNext()) != '\0' || !_end); return false; } private bool ParseProperty(char firstChar) { char currentChar = firstChar; char quoteChar; if (ValidIdentifierChar(currentChar)) { quoteChar = '\0'; currentChar = ParseUnquotedProperty(currentChar); } else if (currentChar == '"' || currentChar == '\'') { quoteChar = currentChar; ReadStringIntoBuffer(quoteChar); currentChar = MoveNext(); } else { throw CreateJsonReaderException("Invalid property identifier character: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } if (currentChar != ':') { currentChar = MoveNext(); // finished property. skip any whitespace and move to colon EatWhitespace(currentChar, false, out currentChar); if (currentChar != ':') throw CreateJsonReaderException("Invalid character after parsing property name. Expected ':' but got: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } SetToken(JsonToken.PropertyName, _buffer.ToString()); QuoteChar = quoteChar; _buffer.Position = 0; return true; } private bool ValidIdentifierChar(char value) { return (char.IsLetterOrDigit(value) || value == '_' || value == '$'); } private char ParseUnquotedProperty(char firstChar) { // parse unquoted property name until whitespace or colon _buffer.Append(firstChar); char currentChar; while ((currentChar = MoveNext()) != '\0' || !_end) { if (char.IsWhiteSpace(currentChar) || currentChar == ':') { return currentChar; } else if (ValidIdentifierChar(currentChar)) { _buffer.Append(currentChar); } else { throw CreateJsonReaderException("Invalid JavaScript property identifier character: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } } throw CreateJsonReaderException("Unexpected end when parsing unquoted property name. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } private bool ParseValue(char currentChar) { do { switch (currentChar) { case '"': case '\'': ParseString(currentChar); return true; case 't': ParseTrue(); return true; case 'f': ParseFalse(); return true; case 'n': if (HasNext()) { char next = (char)PeekNext(); if (next == 'u') ParseNull(); else if (next == 'e') ParseConstructor(); else throw CreateJsonReaderException("Unexpected character encountered while parsing value: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } else { throw CreateJsonReaderException("Unexpected end. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } return true; case 'N': ParseNumberNaN(); return true; case 'I': ParseNumberPositiveInfinity(); return true; case '-': if (PeekNext() == 'I') ParseNumberNegativeInfinity(); else ParseNumber(currentChar); return true; case '/': ParseComment(); return true; case 'u': ParseUndefined(); return true; case '{': SetToken(JsonToken.StartObject); return true; case '[': SetToken(JsonToken.StartArray); return true; case '}': SetToken(JsonToken.EndObject); return true; case ']': SetToken(JsonToken.EndArray); return true; case ',': SetToken(JsonToken.Undefined); return true; case ')': SetToken(JsonToken.EndConstructor); return true; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: // eat break; default: if (char.IsWhiteSpace(currentChar)) { // eat } else if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.') { ParseNumber(currentChar); return true; } else { throw CreateJsonReaderException("Unexpected character encountered while parsing value: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } break; } } while ((currentChar = MoveNext()) != '\0' || !_end); return false; } private bool EatWhitespace(char initialChar, bool oneOrMore, out char finalChar) { bool whitespace = false; char currentChar = initialChar; while (currentChar == ' ' || char.IsWhiteSpace(currentChar)) { whitespace = true; currentChar = MoveNext(); } finalChar = currentChar; return (!oneOrMore || whitespace); } private void ParseConstructor() { if (MatchValue('n', "new", true)) { char currentChar = MoveNext(); if (EatWhitespace(currentChar, true, out currentChar)) { while (char.IsLetter(currentChar)) { _buffer.Append(currentChar); currentChar = MoveNext(); } EatWhitespace(currentChar, false, out currentChar); if (currentChar != '(') throw CreateJsonReaderException("Unexpected character while parsing constructor: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); string constructorName = _buffer.ToString(); _buffer.Position = 0; SetToken(JsonToken.StartConstructor, constructorName); } } } private void ParseNumber(char firstChar) { char currentChar = firstChar; // parse until seperator character or end bool end = false; do { if (IsSeperator(currentChar)) { end = true; _lastChar = currentChar; } else { _buffer.Append(currentChar); } } while (!end && ((currentChar = MoveNext()) != '\0' || !_end)); string number = _buffer.ToString(); object numberValue; JsonToken numberType; bool nonBase10 = (firstChar == '0' && !number.StartsWith("0.", StringComparison.OrdinalIgnoreCase)); if (_readType == ReadType.ReadAsDecimal) { if (nonBase10) { // decimal.Parse doesn't support parsing hexadecimal values long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); numberValue = Convert.ToDecimal(integer); } else { numberValue = decimal.Parse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture); } numberType = JsonToken.Float; } else { if (nonBase10) { numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); numberType = JsonToken.Integer; } else if (number.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || number.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1) { numberValue = Convert.ToDouble(number, CultureInfo.InvariantCulture); numberType = JsonToken.Float; } else { try { numberValue = Convert.ToInt64(number, CultureInfo.InvariantCulture); } catch (OverflowException ex) { throw new JsonReaderException("JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, number), ex); } numberType = JsonToken.Integer; } } _buffer.Position = 0; SetToken(numberType, numberValue); } private void ParseComment() { // should have already parsed / character before reaching this method char currentChar = MoveNext(); if (currentChar == '*') { while ((currentChar = MoveNext()) != '\0' || !_end) { if (currentChar == '*') { if ((currentChar = MoveNext()) != '\0' || !_end) { if (currentChar == '/') { break; } else { _buffer.Append('*'); _buffer.Append(currentChar); } } } else { _buffer.Append(currentChar); } } } else { throw CreateJsonReaderException("Error parsing comment. Expected: *. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } SetToken(JsonToken.Comment, _buffer.ToString()); _buffer.Position = 0; } private bool MatchValue(char firstChar, string value) { char currentChar = firstChar; int i = 0; do { if (currentChar != value[i]) { break; } i++; } while (i < value.Length && ((currentChar = MoveNext()) != '\0' || !_end)); return (i == value.Length); } private bool MatchValue(char firstChar, string value, bool noTrailingNonSeperatorCharacters) { // will match value and then move to the next character, checking that it is a seperator character bool match = MatchValue(firstChar, value); if (!noTrailingNonSeperatorCharacters) { return match; } else { int c = PeekNext(); char next = (c != -1) ? (char) c : '\0'; bool matchAndNoTrainingNonSeperatorCharacters = (match && (next == '\0' || IsSeperator(next))); return matchAndNoTrainingNonSeperatorCharacters; } } private bool IsSeperator(char c) { switch (c) { case '}': case ']': case ',': return true; case '/': // check next character to see if start of a comment return (HasNext() && PeekNext() == '*'); case ')': if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart) return true; break; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: return true; default: if (char.IsWhiteSpace(c)) return true; break; } return false; } private void ParseTrue() { // check characters equal 'true' // and that it is followed by either a seperator character // or the text ends if (MatchValue('t', JsonConvert.True, true)) { SetToken(JsonToken.Boolean, true); } else { throw CreateJsonReaderException("Error parsing boolean value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNull() { if (MatchValue('n', JsonConvert.Null, true)) { SetToken(JsonToken.Null); } else { throw CreateJsonReaderException("Error parsing null value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseUndefined() { if (MatchValue('u', JsonConvert.Undefined, true)) { SetToken(JsonToken.Undefined); } else { throw CreateJsonReaderException("Error parsing undefined value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseFalse() { if (MatchValue('f', JsonConvert.False, true)) { SetToken(JsonToken.Boolean, false); } else { throw CreateJsonReaderException("Error parsing boolean value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNumberNegativeInfinity() { if (MatchValue('-', JsonConvert.NegativeInfinity, true)) { SetToken(JsonToken.Float, double.NegativeInfinity); } else { throw CreateJsonReaderException("Error parsing negative infinity value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNumberPositiveInfinity() { if (MatchValue('I', JsonConvert.PositiveInfinity, true)) { SetToken(JsonToken.Float, double.PositiveInfinity); } else { throw CreateJsonReaderException("Error parsing positive infinity value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNumberNaN() { if (MatchValue('N', JsonConvert.NaN, true)) { SetToken(JsonToken.Float, double.NaN); } else { throw CreateJsonReaderException("Error parsing NaN value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } /// <summary> /// Changes the state to closed. /// </summary> public override void Close() { base.Close(); if (CloseInput && _reader != null) _reader.Close(); if (_buffer != null) _buffer.Clear(); } /// <summary> /// Gets a value indicating whether the class can return line information. /// </summary> /// <returns> /// <c>true</c> if LineNumber and LinePosition can be provided; otherwise, <c>false</c>. /// </returns> public bool HasLineInfo() { return true; } /// <summary> /// Gets the current line number. /// </summary> /// <value> /// The current line number or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LineNumber { get { if (CurrentState == State.Start) return 0; return _currentLineNumber; } } /// <summary> /// Gets the current line position. /// </summary> /// <value> /// The current line position or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LinePosition { get { return _currentLinePosition; } } } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; namespace Oranikle.DesignBase.UI.Docking { public class DockContent : Form, IDockContent { public DockContent() { m_dockHandler = new DockContentHandler(this, new GetPersistStringCallback(GetPersistString)); m_dockHandler.DockStateChanged += new EventHandler(DockHandler_DockStateChanged); //Suggested as a fix by bensty regarding form resize this.ParentChanged += new EventHandler(DockContent_ParentChanged); } //Suggested as a fix by bensty regarding form resize private void DockContent_ParentChanged(object Sender, EventArgs e) { if (this.Parent != null) this.Font = this.Parent.Font; } private DockContentHandler m_dockHandler = null; [Browsable(false)] public DockContentHandler DockHandler { get { return m_dockHandler; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_AllowEndUserDocking_Description")] [DefaultValue(true)] public bool AllowEndUserDocking { get { return DockHandler.AllowEndUserDocking; } set { DockHandler.AllowEndUserDocking = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_DockAreas_Description")] [DefaultValue(DockAreas.DockLeft|DockAreas.DockRight|DockAreas.DockTop|DockAreas.DockBottom|DockAreas.Document|DockAreas.Float)] public DockAreas DockAreas { get { return DockHandler.DockAreas; } set { DockHandler.DockAreas = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_AutoHidePortion_Description")] [DefaultValue(0.25)] public double AutoHidePortion { get { return DockHandler.AutoHidePortion; } set { DockHandler.AutoHidePortion = value; } } [Localizable(true)] [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_TabText_Description")] [DefaultValue(null)] private string m_tabText = null; public string TabText { get { return m_tabText; } set { DockHandler.TabText = m_tabText = value; } } private bool ShouldSerializeTabText() { return (m_tabText != null); } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_CloseButton_Description")] [DefaultValue(true)] public bool CloseButton { get { return DockHandler.CloseButton; } set { DockHandler.CloseButton = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_CloseButtonVisible_Description")] [DefaultValue(true)] public bool CloseButtonVisible { get { return DockHandler.CloseButtonVisible; } set { DockHandler.CloseButtonVisible = value; } } [Browsable(false)] public DockPanel DockPanel { get { return DockHandler.DockPanel; } set { DockHandler.DockPanel = value; } } [Browsable(false)] public DockState DockState { get { return DockHandler.DockState; } set { DockHandler.DockState = value; } } [Browsable(false)] public DockPane Pane { get { return DockHandler.Pane; } set { DockHandler.Pane = value; } } [Browsable(false)] public bool IsHidden { get { return DockHandler.IsHidden; } set { DockHandler.IsHidden = value; } } [Browsable(false)] public DockState VisibleState { get { return DockHandler.VisibleState; } set { DockHandler.VisibleState = value; } } [Browsable(false)] public bool IsFloat { get { return DockHandler.IsFloat; } set { DockHandler.IsFloat = value; } } [Browsable(false)] public DockPane PanelPane { get { return DockHandler.PanelPane; } set { DockHandler.PanelPane = value; } } [Browsable(false)] public DockPane FloatPane { get { return DockHandler.FloatPane; } set { DockHandler.FloatPane = value; } } [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] protected virtual string GetPersistString() { return GetType().ToString(); } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_HideOnClose_Description")] [DefaultValue(false)] public bool HideOnClose { get { return DockHandler.HideOnClose; } set { DockHandler.HideOnClose = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_ShowHint_Description")] [DefaultValue(DockState.Unknown)] public DockState ShowHint { get { return DockHandler.ShowHint; } set { DockHandler.ShowHint = value; } } [Browsable(false)] public bool IsActivated { get { return DockHandler.IsActivated; } } public bool IsDockStateValid(DockState dockState) { return DockHandler.IsDockStateValid(dockState); } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_TabPageContextMenu_Description")] [DefaultValue(null)] public ContextMenu TabPageContextMenu { get { return DockHandler.TabPageContextMenu; } set { DockHandler.TabPageContextMenu = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_TabPageContextMenuStrip_Description")] [DefaultValue(null)] public ContextMenuStrip TabPageContextMenuStrip { get { return DockHandler.TabPageContextMenuStrip; } set { DockHandler.TabPageContextMenuStrip = value; } } [Localizable(true)] [Category("Appearance")] [LocalizedDescription("DockContent_ToolTipText_Description")] [DefaultValue(null)] public string ToolTipText { get { return DockHandler.ToolTipText; } set { DockHandler.ToolTipText = value; } } public new void Activate() { DockHandler.Activate(); } public new void Hide() { DockHandler.Hide(); } public new void Show() { DockHandler.Show(); } public void Show(DockPanel dockPanel) { DockHandler.Show(dockPanel); } public void Show(DockPanel dockPanel, DockState dockState) { DockHandler.Show(dockPanel, dockState); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public void Show(DockPanel dockPanel, Rectangle floatWindowBounds) { DockHandler.Show(dockPanel, floatWindowBounds); } public void Show(DockPane pane, IDockContent beforeContent) { DockHandler.Show(pane, beforeContent); } public void Show(DockPane previousPane, DockAlignment alignment, double proportion) { DockHandler.Show(previousPane, alignment, proportion); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public void FloatAt(Rectangle floatWindowBounds) { DockHandler.FloatAt(floatWindowBounds); } public void DockTo(DockPane paneTo, DockStyle dockStyle, int contentIndex) { DockHandler.DockTo(paneTo, dockStyle, contentIndex); } public void DockTo(DockPanel panel, DockStyle dockStyle) { DockHandler.DockTo(panel, dockStyle); } #region IDockContent Members void IDockContent.OnActivated(EventArgs e) { this.OnActivated(e); } void IDockContent.OnDeactivate(EventArgs e) { this.OnDeactivate(e); } #endregion #region Events private void DockHandler_DockStateChanged(object sender, EventArgs e) { OnDockStateChanged(e); } private static readonly object DockStateChangedEvent = new object(); [LocalizedCategory("Category_PropertyChanged")] [LocalizedDescription("Pane_DockStateChanged_Description")] public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="SiteMapProvider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * Copyright (c) 2002 Microsoft Corporation */ namespace System.Web { using System; using System.Collections; using System.Collections.Specialized; using System.Configuration.Provider; using System.Web.Security; using System.Web.UI; using System.Web.Util; using System.Security.Permissions; public abstract class SiteMapProvider : ProviderBase { private bool _securityTrimmingEnabled; private bool _enableLocalization; private String _resourceKey; internal const String _securityTrimmingEnabledAttrName = "securityTrimmingEnabled"; private const string _allRoles = "*"; private SiteMapProvider _rootProvider; private SiteMapProvider _parentProvider; private object _resolutionTicket = new object(); internal readonly object _lock = new Object(); public virtual SiteMapNode CurrentNode { get { HttpContext context = HttpContext.Current; SiteMapNode result = null; // First check the SiteMap resolve events. result = ResolveSiteMapNode(context); if (result == null) { result = FindSiteMapNode(context); } return ReturnNodeIfAccessible(result); } } public bool EnableLocalization { get { return _enableLocalization; } set { _enableLocalization = value; } } // Parent provider public virtual SiteMapProvider ParentProvider { get { return _parentProvider; } set { _parentProvider = value; } } public string ResourceKey { get { return _resourceKey; } set { _resourceKey = value; } } public virtual SiteMapProvider RootProvider { get { if (_rootProvider == null) { lock (_lock) { if (_rootProvider == null) { Hashtable providers = new Hashtable(); SiteMapProvider candidate = this; providers.Add(candidate, null); while (candidate.ParentProvider != null) { if (providers.Contains(candidate.ParentProvider)) throw new ProviderException(SR.GetString(SR.SiteMapProvider_Circular_Provider)); candidate = candidate.ParentProvider; providers.Add(candidate, null); } _rootProvider = candidate; } } } return _rootProvider; } } public virtual SiteMapNode RootNode { get { SiteMapNode node = GetRootNodeCore(); return ReturnNodeIfAccessible(node); } } public bool SecurityTrimmingEnabled { get { return _securityTrimmingEnabled; } } public event SiteMapResolveEventHandler SiteMapResolve; /// <devdoc> /// <para>Add single node to provider.</para> /// </devdoc> protected virtual void AddNode(SiteMapNode node) { AddNode(node, null); } protected internal virtual void AddNode(SiteMapNode node, SiteMapNode parentNode) { throw new NotImplementedException(); } public virtual SiteMapNode FindSiteMapNode(HttpContext context) { if (context == null) { return null; } string rawUrl = context.Request.RawUrl; SiteMapNode result = null; // First check the RawUrl result = FindSiteMapNode(rawUrl); if (result == null) { int queryStringIndex = rawUrl.IndexOf("?", StringComparison.Ordinal); if (queryStringIndex != -1) { // check the RawUrl without querystring result = FindSiteMapNode(rawUrl.Substring(0, queryStringIndex)); } if (result == null) { Page page = context.CurrentHandler as Page; if (page != null) { // Try without server side query strings string qs = page.ClientQueryString; if (qs.Length > 0) { result = FindSiteMapNode(context.Request.Path + "?" + qs); } } if (result == null) { // Check the request path result = FindSiteMapNode(context.Request.Path); } } } return result; } public virtual SiteMapNode FindSiteMapNodeFromKey(string key) { return FindSiteMapNode(key); } public abstract SiteMapNode FindSiteMapNode(string rawUrl); public abstract SiteMapNodeCollection GetChildNodes(SiteMapNode node); public virtual SiteMapNode GetCurrentNodeAndHintAncestorNodes(int upLevel) { if (upLevel < -1) { throw new ArgumentOutOfRangeException("upLevel"); } return CurrentNode; } public virtual SiteMapNode GetCurrentNodeAndHintNeighborhoodNodes(int upLevel, int downLevel) { if (upLevel < -1) { throw new ArgumentOutOfRangeException("upLevel"); } if (downLevel < -1) { throw new ArgumentOutOfRangeException("downLevel"); } return CurrentNode; } public abstract SiteMapNode GetParentNode(SiteMapNode node); public virtual SiteMapNode GetParentNodeRelativeToCurrentNodeAndHintDownFromParent ( int walkupLevels, int relativeDepthFromWalkup) { if (walkupLevels < 0) { throw new ArgumentOutOfRangeException("walkupLevels"); } if (relativeDepthFromWalkup < 0) { throw new ArgumentOutOfRangeException("relativeDepthFromWalkup"); } // First get current nodes and hints about its ancestors. SiteMapNode currentNode = GetCurrentNodeAndHintAncestorNodes(walkupLevels); // Simply return if the currentNode is null. if (currentNode == null) { return null; } // Find the target node by walk up the parent tree. SiteMapNode targetNode = GetParentNodesInternal(currentNode, walkupLevels); if (targetNode == null) { return null; } // Get hints about its lower neighborhood nodes. HintNeighborhoodNodes(targetNode, 0, relativeDepthFromWalkup); return targetNode; } public virtual SiteMapNode GetParentNodeRelativeToNodeAndHintDownFromParent( SiteMapNode node, int walkupLevels, int relativeDepthFromWalkup) { if (walkupLevels < 0) { throw new ArgumentOutOfRangeException("walkupLevels"); } if (relativeDepthFromWalkup < 0) { throw new ArgumentOutOfRangeException("relativeDepthFromWalkup"); } if (node == null) { throw new ArgumentNullException("node"); } // First get hints about ancestor nodes; HintAncestorNodes(node, walkupLevels); // walk up the parent node until the target node is found. SiteMapNode ancestorNode = GetParentNodesInternal(node, walkupLevels); if (ancestorNode == null) { return null; } // Get hints about its neighthood nodes HintNeighborhoodNodes(ancestorNode, 0, relativeDepthFromWalkup); return ancestorNode; } private SiteMapNode GetParentNodesInternal(SiteMapNode node, int walkupLevels) { Debug.Assert(node != null); if (walkupLevels <= 0) { return node; } do { node = node.ParentNode; walkupLevels--; } while (node != null && walkupLevels != 0); return node; } /* * A reference node that must be returned by all sitemap providers, this is * required for the parent provider to keep track of the relations between * two providers. * For example, the parent provider uses this method to keep track of the parent * node of child provider's root node. */ protected internal abstract SiteMapNode GetRootNodeCore(); protected static SiteMapNode GetRootNodeCoreFromProvider(SiteMapProvider provider) { return provider.GetRootNodeCore(); } public virtual void HintAncestorNodes(SiteMapNode node, int upLevel) { if (node == null) { throw new ArgumentNullException("node"); } if (upLevel < -1) { throw new ArgumentOutOfRangeException("upLevel"); } } public virtual void HintNeighborhoodNodes(SiteMapNode node, int upLevel, int downLevel) { if (node == null) { throw new ArgumentNullException("node"); } if (upLevel < -1) { throw new ArgumentOutOfRangeException("upLevel"); } if (downLevel < -1) { throw new ArgumentOutOfRangeException("downLevel"); } } public override void Initialize(string name, NameValueCollection attributes) { if (attributes != null) { if (string.IsNullOrEmpty(attributes["description"])) { attributes.Remove("description"); attributes.Add("description", this.GetType().Name); } ProviderUtil.GetAndRemoveBooleanAttribute(attributes, _securityTrimmingEnabledAttrName, Name, ref _securityTrimmingEnabled); } base.Initialize(name, attributes); } public virtual bool IsAccessibleToUser(HttpContext context, SiteMapNode node) { if (node == null) { throw new ArgumentNullException("node"); } if (context == null) { throw new ArgumentNullException("context"); } if (!SecurityTrimmingEnabled) { return true; } if (node.Roles != null) { foreach (string role in node.Roles) { // Grant access if one of the roles is a "*". if (role == _allRoles || context.User != null && context.User.IsInRole(role)) { return true; } } } VirtualPath virtualPath = node.VirtualPath; if (virtualPath == null || !virtualPath.IsWithinAppRoot) { return false; } return System.Web.UI.Util.IsUserAllowedToPath(context, virtualPath); } protected internal virtual void RemoveNode(SiteMapNode node) { throw new NotImplementedException(); } protected SiteMapNode ResolveSiteMapNode(HttpContext context) { SiteMapResolveEventHandler eventHandler = SiteMapResolve; if (eventHandler == null) return null; if (!context.Items.Contains(_resolutionTicket)) { context.Items.Add(_resolutionTicket, true); try { Delegate[] ds = eventHandler.GetInvocationList(); int len = ds.Length; for (int i = 0; i < len; i++) { SiteMapNode ret = ((SiteMapResolveEventHandler)ds[i])(this, new SiteMapResolveEventArgs(context, this)); if (ret != null) { return ret; } } } finally { context.Items.Remove(_resolutionTicket); } } return null; } internal SiteMapNode ReturnNodeIfAccessible(SiteMapNode node) { if (node != null && node.IsAccessibleToUser(HttpContext.Current)) { return node; } return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.MachineLearning.WebServices { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for WebServicesOperations. /// </summary> public static partial class WebServicesOperationsExtensions { /// <summary> /// Create or update a web service. This call will overwrite an existing web /// service. Note that there is no warning or confirmation. This is a /// nonrecoverable operation. If your intent is to create a new web service, /// call the Get operation first to verify that it does not exist. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='createOrUpdatePayload'> /// The payload that is used to create or update the web service. /// </param> public static WebService CreateOrUpdate(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, WebService createOrUpdatePayload) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).CreateOrUpdateAsync(resourceGroupName, webServiceName, createOrUpdatePayload), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or update a web service. This call will overwrite an existing web /// service. Note that there is no warning or confirmation. This is a /// nonrecoverable operation. If your intent is to create a new web service, /// call the Get operation first to verify that it does not exist. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='createOrUpdatePayload'> /// The payload that is used to create or update the web service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<WebService> CreateOrUpdateAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, WebService createOrUpdatePayload, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, webServiceName, createOrUpdatePayload, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create or update a web service. This call will overwrite an existing web /// service. Note that there is no warning or confirmation. This is a /// nonrecoverable operation. If your intent is to create a new web service, /// call the Get operation first to verify that it does not exist. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='createOrUpdatePayload'> /// The payload that is used to create or update the web service. /// </param> public static WebService BeginCreateOrUpdate(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, WebService createOrUpdatePayload) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, webServiceName, createOrUpdatePayload), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or update a web service. This call will overwrite an existing web /// service. Note that there is no warning or confirmation. This is a /// nonrecoverable operation. If your intent is to create a new web service, /// call the Get operation first to verify that it does not exist. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='createOrUpdatePayload'> /// The payload that is used to create or update the web service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<WebService> BeginCreateOrUpdateAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, WebService createOrUpdatePayload, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, webServiceName, createOrUpdatePayload, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the Web Service Definiton as specified by a subscription, resource /// group, and name. Note that the storage credentials and web service keys /// are not returned by this call. To get the web service access keys, call /// List Keys. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> public static WebService Get(this IWebServicesOperations operations, string resourceGroupName, string webServiceName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).GetAsync(resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the Web Service Definiton as specified by a subscription, resource /// group, and name. Note that the storage credentials and web service keys /// are not returned by this call. To get the web service access keys, call /// List Keys. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<WebService> GetAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Modifies an existing web service resource. The PATCH API call is an /// asynchronous operation. To determine whether it has completed /// successfully, you must perform a Get operation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='patchPayload'> /// The payload to use to patch the web service. /// </param> public static WebService Patch(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, WebService patchPayload) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).PatchAsync(resourceGroupName, webServiceName, patchPayload), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Modifies an existing web service resource. The PATCH API call is an /// asynchronous operation. To determine whether it has completed /// successfully, you must perform a Get operation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='patchPayload'> /// The payload to use to patch the web service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<WebService> PatchAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, WebService patchPayload, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PatchWithHttpMessagesAsync(resourceGroupName, webServiceName, patchPayload, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Modifies an existing web service resource. The PATCH API call is an /// asynchronous operation. To determine whether it has completed /// successfully, you must perform a Get operation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='patchPayload'> /// The payload to use to patch the web service. /// </param> public static WebService BeginPatch(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, WebService patchPayload) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).BeginPatchAsync(resourceGroupName, webServiceName, patchPayload), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Modifies an existing web service resource. The PATCH API call is an /// asynchronous operation. To determine whether it has completed /// successfully, you must perform a Get operation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='patchPayload'> /// The payload to use to patch the web service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<WebService> BeginPatchAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, WebService patchPayload, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginPatchWithHttpMessagesAsync(resourceGroupName, webServiceName, patchPayload, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified web service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> public static void Remove(this IWebServicesOperations operations, string resourceGroupName, string webServiceName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).RemoveAsync(resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified web service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task RemoveAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.RemoveWithHttpMessagesAsync(resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes the specified web service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> public static void BeginRemove(this IWebServicesOperations operations, string resourceGroupName, string webServiceName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).BeginRemoveAsync(resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified web service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task BeginRemoveAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.BeginRemoveWithHttpMessagesAsync(resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the access keys for the specified web service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> public static WebServiceKeys ListKeys(this IWebServicesOperations operations, string resourceGroupName, string webServiceName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).ListKeysAsync(resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the access keys for the specified web service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='webServiceName'> /// The name of the web service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<WebServiceKeys> ListKeysAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the web services in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='skiptoken'> /// Continuation token for pagination. /// </param> public static Microsoft.Rest.Azure.IPage<WebService> ListByResourceGroup(this IWebServicesOperations operations, string resourceGroupName, string skiptoken = default(string)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).ListByResourceGroupAsync(resourceGroupName, skiptoken), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the web services in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the web service is located. /// </param> /// <param name='skiptoken'> /// Continuation token for pagination. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<WebService>> ListByResourceGroupAsync(this IWebServicesOperations operations, string resourceGroupName, string skiptoken = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, skiptoken, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the web services in the specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='skiptoken'> /// Continuation token for pagination. /// </param> public static Microsoft.Rest.Azure.IPage<WebService> List(this IWebServicesOperations operations, string skiptoken = default(string)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).ListAsync(skiptoken), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the web services in the specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='skiptoken'> /// Continuation token for pagination. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<WebService>> ListAsync(this IWebServicesOperations operations, string skiptoken = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(skiptoken, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the web services in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<WebService> ListByResourceGroupNext(this IWebServicesOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the web services in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<WebService>> ListByResourceGroupNextAsync(this IWebServicesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the web services in the specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<WebService> ListNext(this IWebServicesOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the web services in the specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<WebService>> ListNextAsync(this IWebServicesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using Xunit.Abstractions; using System.IO; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_GlobalTypes", Desc = "")] public class TC_SchemaSet_GlobalTypes : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_GlobalTypes(ITestOutputHelper output) { _output = output; } public XmlSchema GetSchema(string ns, string type1, string type2) { string xsd = String.Empty; if (ns.Equals(String.Empty)) xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema'><complexType name='" + type1 + "'><sequence><element name='local'/></sequence></complexType><simpleType name='" + type2 + "'><restriction base='int'/></simpleType></schema>"; else xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema' targetNamespace='" + ns + "'><complexType name='" + type1 + "'><sequence><element name='local'/></sequence></complexType><simpleType name='" + type2 + "'><restriction base='int'/></simpleType></schema>"; XmlSchema schema = XmlSchema.Read(new StringReader(xsd), null); return schema; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v1 - GlobalTypes on empty collection")] [InlineData()] [Theory] public void v1() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchemaObjectTable table = sc.GlobalTypes; CError.Compare(table == null, false, "Count"); return; } //----------------------------------------------------------------------------------- // params is a pair of the following info: (namaespace, type1 type2) two schemas are made from this info //[Variation(Desc = "v2.1 - GlobalTypes with set with two schemas, both without NS", Params = new object[] { "", "t1", "t2", "", "t3", "t4" })] [InlineData("", "t1", "t2", "", "t3", "t4")] //[Variation(Desc = "v2.2 - GlobalTypes with set with two schemas, one without NS one with NS", Params = new object[] { "a", "t1", "t2", "", "t3", "t4" })] [InlineData("a", "t1", "t2", "", "t3", "t4")] //[Variation(Desc = "v2.2 - GlobalTypes with set with two schemas, both with NS", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4" })] [InlineData("a", "t1", "t2", "b", "t3", "t4")] [Theory] public void v2(object param0, object param1, object param2, object param3, object param4, object param5) { string ns1 = param0.ToString(); string ns2 = param3.ToString(); string type1 = param1.ToString(); string type2 = param2.ToString(); string type3 = param4.ToString(); string type4 = param5.ToString(); XmlSchema s1 = GetSchema(ns1, type1, type2); XmlSchema s2 = GetSchema(ns2, type3, type4); XmlSchemaSet ss = new XmlSchemaSet(); ss.Add(s1); CError.Compare(ss.GlobalTypes.Count, 0, "Types Count after add"); ss.Compile(); ss.Add(s2); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after add/compile"); //+1 for anyType ss.Compile(); //Verify CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after add/compile/add/compile"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns1)), true, "Contains2"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type3, ns2)), true, "Contains3"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type4, ns2)), true, "Contains4"); //Now reprocess one schema and check ss.Reprocess(s1); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after repr"); //+1 for anyType ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after repr/comp"); //+1 for anyType //Now Remove one schema and check ss.Remove(s1); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove"); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove/comp"); return; } // params is a pair of the following info: (namaespace, type1 type2)*, doCompile? //[Variation(Desc = "v3.1 - GlobalTypes with a set having schema (nons) to another set with schema(nons)", Params = new object[] { "", "t1", "t2", "", "t3", "t4", true })] [InlineData("", "t1", "t2", "", "t3", "t4", true)] //[Variation(Desc = "v3.2 - GlobalTypes with a set having schema (ns) to another set with schema(nons)", Params = new object[] { "a", "t1", "t2", "", "t3", "t4", true })] [InlineData("a", "t1", "t2", "", "t3", "t4", true)] //[Variation(Desc = "v3.3 - GlobalTypes with a set having schema (nons) to another set with schema(ns)", Params = new object[] { "", "t1", "t2", "a", "t3", "t4", true })] [InlineData("", "t1", "t2", "a", "t3", "t4", true)] //[Variation(Desc = "v3.4 - GlobalTypes with a set having schema (ns) to another set with schema(ns)", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4", true })] [InlineData("a", "t1", "t2", "b", "t3", "t4", true)] //[Variation(Desc = "v3.5 - GlobalTypes with a set having schema (nons) to another set with schema(nons), no compile", Params = new object[] { "", "t1", "t2", "", "t3", "t4", false })] [InlineData("", "t1", "t2", "", "t3", "t4", false)] //[Variation(Desc = "v3.6 - GlobalTypes with a set having schema (ns) to another set with schema(nons), no compile", Params = new object[] { "a", "t1", "t2", "", "t3", "t4", false })] [InlineData("a", "t1", "t2", "", "t3", "t4", false)] //[Variation(Desc = "v3.7 - GlobalTypes with a set having schema (nons) to another set with schema(ns), no compile", Params = new object[] { "", "t1", "t2", "a", "t3", "t4", false })] [InlineData("", "t1", "t2", "a", "t3", "t4", false)] //[Variation(Desc = "v3.8 - GlobalTypes with a set having schema (ns) to another set with schema(ns), no compile", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4", false })] [InlineData("a", "t1", "t2", "b", "t3", "t4", false)] [Theory] public void v3(object param0, object param1, object param2, object param3, object param4, object param5, object param6) { string ns1 = param0.ToString(); string ns2 = param3.ToString(); string type1 = param1.ToString(); string type2 = param2.ToString(); string type3 = param4.ToString(); string type4 = param5.ToString(); bool doCompile = (bool)param6; XmlSchema s1 = GetSchema(ns1, type1, type2); XmlSchema s2 = GetSchema(ns2, type3, type4); XmlSchemaSet ss1 = new XmlSchemaSet(); XmlSchemaSet ss2 = new XmlSchemaSet(); ss1.Add(s1); ss1.Compile(); ss2.Add(s2); if (doCompile) ss2.Compile(); // add one schemaset to another ss1.Add(ss2); if (!doCompile) ss1.Compile(); //Verify CError.Compare(ss1.GlobalTypes.Count, 5, "Types Count after add/comp"); //+1 for anyType CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type2, ns1)), true, "Contains2"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type3, ns2)), true, "Contains3"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type4, ns2)), true, "Contains4"); //Now reprocess one schema and check ss1.Reprocess(s1); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count repr"); //+1 for anyType ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 5, "Types Count repr/comp"); //+1 for anyType //Now Remove one schema and check ss1.Remove(s1); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count after remove"); ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count after rem/comp"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v4.1 - GlobalTypes with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B" })] [InlineData("import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B")] //[Variation(Desc = "v4.2 - GlobalTypes with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B" })] [InlineData("import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B")] [Theory] public void v4(object param0, object param1, object param2, object param3, object param4) { string uri1 = param0.ToString(); string ns1 = param1.ToString(); string type1 = param2.ToString(); string ns2 = param3.ToString(); string type2 = param4.ToString(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); XmlSchema schema1 = ss.Add(null, Path.Combine(TestData._Root, uri1)); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), true, "Contains2"); //get the SOM for the imported schema foreach (XmlSchema s in ss.Schemas(ns2)) { ss.Remove(s); } ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 2, "Types Count after Remove"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), false, "Contains2"); return; } //[Variation(Desc = "v5.1 - GlobalTypes with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B" })] [InlineData("import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B")] //[Variation(Desc = "v5.2 - GlobalTypes with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B" })] [InlineData("import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B")] [Theory] public void v5(object param0, object param1, object param2, object param3, object param4) { string uri1 = param0.ToString(); string ns1 = param1.ToString(); string type1 = param2.ToString(); string ns2 = param3.ToString(); string type2 = param4.ToString(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "xsdauthor.xsd")); XmlSchema schema1 = ss.Add(null, Path.Combine(TestData._Root, uri1)); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), true, "Contains2"); ss.RemoveRecursive(schema1); // should not need to compile for RemoveRecursive to take effect CError.Compare(ss.GlobalTypes.Count, 1, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), false, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), false, "Contains2"); return; } //----------------------------------------------------------------------------------- //REGRESSIONS //[Variation(Desc = "v100 - XmlSchemaSet: Components are not added to the global tabels if it is already compiled", Priority = 1)] [InlineData()] [Theory] public void v100() { try { // anytype t1 t2 XmlSchema schema1 = XmlSchema.Read(new StringReader("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='a'><xs:element name='e1' type='xs:anyType'/><xs:complexType name='t1'/><xs:complexType name='t2'/></xs:schema>"), null); // anytype t3 t4 XmlSchema schema2 = XmlSchema.Read(new StringReader("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' ><xs:element name='e1' type='xs:anyType'/><xs:complexType name='t3'/><xs:complexType name='t4'/></xs:schema>"), null); XmlSchemaSet ss1 = new XmlSchemaSet(); XmlSchemaSet ss2 = new XmlSchemaSet(); ss1.Add(schema1); ss2.Add(schema2); ss2.Compile(); ss1.Add(ss2); ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 5, "Count"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName("t1", "a")), true, "Contains"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName("t2", "a")), true, "Contains"); } catch (Exception e) { _output.WriteLine(e.Message); Assert.True(false); } return; } } }
using System; using Sep.Git.Tfs.Core.TfsInterop; using Sep.Git.Tfs.Commands; namespace Sep.Git.Tfs.Core { class DerivedGitTfsRemote : IGitTfsRemote { private readonly string _tfsUrl; private readonly string _tfsRepositoryPath; public DerivedGitTfsRemote(string tfsUrl, string tfsRepositoryPath) { _tfsUrl = tfsUrl; _tfsRepositoryPath = tfsRepositoryPath; } public bool IsDerived { get { return true; } } public string Id { get { return "(derived)"; } set { throw new NotImplementedException(); } } public string TfsUrl { get { return _tfsUrl; } set { throw new NotImplementedException(); } } public bool Autotag { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string TfsUsername { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string TfsPassword { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string TfsRepositoryPath { get { return _tfsRepositoryPath; } set { throw new NotImplementedException(); } } public string[] TfsSubtreePaths { get { throw new NotImplementedException(); } } #region Equality public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(DerivedGitTfsRemote)) return false; return Equals((DerivedGitTfsRemote)obj); } private bool Equals(DerivedGitTfsRemote other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other._tfsUrl, _tfsUrl) && Equals(other._tfsRepositoryPath, _tfsRepositoryPath); } public override int GetHashCode() { unchecked { return ((_tfsUrl != null ? _tfsUrl.GetHashCode() : 0) * 397) ^ (_tfsRepositoryPath != null ? _tfsRepositoryPath.GetHashCode() : 0); } } public static bool operator ==(DerivedGitTfsRemote left, DerivedGitTfsRemote right) { return Equals(left, right); } public static bool operator !=(DerivedGitTfsRemote left, DerivedGitTfsRemote right) { return !Equals(left, right); } #endregion #region All this is not implemented public string IgnoreRegexExpression { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string IgnoreExceptRegexExpression { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public IGitRepository Repository { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public ITfsHelper Tfs { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public long MaxChangesetId { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string MaxCommitHash { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string RemoteRef { get { throw new NotImplementedException(); } } public bool IsSubtree { get { return false; } } public bool IsSubtreeOwner { get { return false; } } public string OwningRemoteId { get { return null; } } public string Prefix { get { return null; } } public bool ExportMetadatas { get; set; } public bool ShouldSkip(string path) { throw new NotImplementedException(); } public string GetPathInGitRepo(string tfsPath) { throw new NotImplementedException(); } public IFetchResult Fetch(bool stopOnFailMergeCommit = false) { throw new NotImplementedException(); } public IFetchResult FetchWithMerge(long mergeChangesetId, bool stopOnFailMergeCommit = false, params string[] parentCommitsHashes) { throw new NotImplementedException(); } public void QuickFetch() { throw new NotImplementedException(); } public void QuickFetch(int changesetId) { throw new NotImplementedException(); } public void Unshelve(string a, string b, string c) { throw new NotImplementedException(); } public void Shelve(string shelvesetName, string treeish, TfsChangesetInfo parentChangeset, bool evaluateCheckinPolicies) { throw new NotImplementedException(); } public bool HasShelveset(string shelvesetName) { throw new NotImplementedException(); } public long CheckinTool(string head, TfsChangesetInfo parentChangeset) { throw new NotImplementedException(); } public long Checkin(string treeish, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null) { throw new NotImplementedException(); } public long Checkin(string head, string parent, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null) { throw new NotImplementedException(); } public void CleanupWorkspace() { throw new NotImplementedException(); } public void CleanupWorkspaceDirectory() { throw new NotImplementedException(); } public ITfsChangeset GetChangeset(long changesetId) { throw new NotImplementedException(); } public void UpdateTfsHead(string commitHash, long changesetId) { throw new NotImplementedException(); } public void EnsureTfsAuthenticated() { throw new NotImplementedException(); } public bool MatchesUrlAndRepositoryPath(string tfsUrl, string tfsRepositoryPath) { throw new NotImplementedException(); } public RemoteInfo RemoteInfo { get { throw new NotImplementedException(); } } public void Merge(string sourceTfsPath, string targetTfsPath) { throw new NotImplementedException(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using PopForums.Configuration; using PopForums.Extensions; using PopForums.Messaging; using PopForums.Models; using PopForums.Repositories; using PopForums.ScoringGame; namespace PopForums.Services { public class TopicService : ITopicService { public TopicService(IForumRepository forumRepository, ITopicRepository topicRepository, IPostRepository postRepository, IProfileRepository profileRepository, ITextParsingService textParsingService, ISettingsManager settingsManager, ISubscribedTopicsService subscribedTopicsService, IModerationLogService moderationLogService, IForumService forumService, IEventPublisher eventPublisher, IBroker broker) { _forumRepository = forumRepository; _topicRepository = topicRepository; _postRepository = postRepository; _profileRepository = profileRepository; _settingsManager = settingsManager; _textParsingService = textParsingService; _subscribedTopicService = subscribedTopicsService; _moderationLogService = moderationLogService; _forumService = forumService; _eventPublisher = eventPublisher; _broker = broker; } private readonly IForumRepository _forumRepository; private readonly ITopicRepository _topicRepository; private readonly IPostRepository _postRepository; private readonly IProfileRepository _profileRepository; private readonly ISettingsManager _settingsManager; private readonly ITextParsingService _textParsingService; private readonly ISubscribedTopicsService _subscribedTopicService; private readonly IModerationLogService _moderationLogService; private readonly IForumService _forumService; private readonly IEventPublisher _eventPublisher; private readonly IBroker _broker; public List<Topic> GetTopics(Forum forum, bool includeDeleted, int pageIndex, out PagerContext pagerContext) { var pageSize = _settingsManager.Current.TopicsPerPage; var startRow = ((pageIndex - 1) * pageSize) + 1; var topics = _topicRepository.Get(forum.ForumID, includeDeleted, startRow, pageSize); int topicCount; if (includeDeleted) topicCount = _topicRepository.GetTopicCount(forum.ForumID, true); else topicCount = forum.TopicCount; var totalPages = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(topicCount) / Convert.ToDouble(pageSize))); pagerContext = new PagerContext { PageCount = totalPages, PageIndex = pageIndex, PageSize = pageSize }; return topics; } public List<Topic> GetTopics(User viewingUser, Forum forum, bool includeDeleted) { var nonViewableForumIDs = _forumService.GetNonViewableForumIDs(viewingUser); var topics = _topicRepository.Get(forum.ForumID, includeDeleted, nonViewableForumIDs); return topics; } public List<Topic> GetTopics(User viewingUser, User postUser, bool includeDeleted, int pageIndex, out PagerContext pagerContext) { var nonViewableForumIDs = _forumService.GetNonViewableForumIDs(viewingUser); var pageSize = _settingsManager.Current.TopicsPerPage; var startRow = ((pageIndex - 1) * pageSize) + 1; var topics = _topicRepository.GetTopicsByUser(postUser.UserID, includeDeleted, nonViewableForumIDs, startRow, pageSize); var topicCount = _topicRepository.GetTopicCountByUser(postUser.UserID, includeDeleted, nonViewableForumIDs); var totalPages = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(topicCount) / Convert.ToDouble(pageSize))); pagerContext = new PagerContext { PageCount = totalPages, PageIndex = pageIndex, PageSize = pageSize }; return topics; } public Dictionary<int, int> GetFirstPostIDsFromTopics(List<Topic> topics) { return _postRepository.GetFirstPostIDsFromTopicIDs(topics.Select(x => x.TopicID).ToList()); } public Topic Get(string urlName) { return _topicRepository.Get(urlName); } public Topic Get(int topicID) { return _topicRepository.Get(topicID); } public Post PostReply(Topic topic, User user, int parentPostID, string ip, bool isFirstInTopic, NewPost newPost, DateTime postTime, string topicLink, Func<User, string> unsubscribeLinkGenerator, string userUrl, Func<Post, string> postLinkGenerator) { newPost.Title = _textParsingService.EscapeHtmlAndCensor(newPost.Title); if (newPost.IsPlainText) newPost.FullText = _textParsingService.ForumCodeToHtml(newPost.FullText); else newPost.FullText = _textParsingService.ClientHtmlToHtml(newPost.FullText); var postID = _postRepository.Create(topic.TopicID, parentPostID, ip, isFirstInTopic, newPost.IncludeSignature, user.UserID, user.Name, newPost.Title, newPost.FullText, postTime, false, user.Name, null, false, 0); var post = new Post(postID) { FullText = newPost.FullText, IP = ip, IsDeleted = false, IsEdited = false, IsFirstInTopic = isFirstInTopic, LastEditName = user.Name, LastEditTime = null, Name = user.Name, ParentPostID = parentPostID, PostTime = postTime, ShowSig = newPost.IncludeSignature, Title = newPost.Title, TopicID = topic.TopicID, UserID = user.UserID }; _topicRepository.IncrementReplyCount(topic.TopicID); _topicRepository.UpdateLastTimeAndUser(topic.TopicID, user.UserID, user.Name, postTime); _forumRepository.UpdateLastTimeAndUser(topic.ForumID, postTime, user.Name); _forumRepository.IncrementPostCount(topic.ForumID); _profileRepository.SetLastPostID(user.UserID, postID); if (unsubscribeLinkGenerator != null) _subscribedTopicService.NotifySubscribers(topic, user, topicLink, unsubscribeLinkGenerator); // <a href="{0}">{1}</a> made a post in the topic: <a href="{2}">{3}</a> var message = String.Format(Resources.NewReplyPublishMessage, userUrl, user.Name, postLinkGenerator(post), topic.Title); var forumHasViewRestrictions = _forumRepository.GetForumViewRoles(topic.ForumID).Count > 0; _eventPublisher.ProcessEvent(message, user, EventDefinitionService.StaticEventIDs.NewPost, forumHasViewRestrictions); _broker.NotifyNewPosts(topic, post.PostID); _broker.NotifyNewPost(topic, post.PostID); var forum = _forumRepository.Get(topic.ForumID); _broker.NotifyForumUpdate(forum); topic = _topicRepository.Get(topic.TopicID); _broker.NotifyTopicUpdate(topic, forum, topicLink); return post; } public void CloseTopic(Topic topic, User user) { if (user.IsInRole(PermanentRoles.Moderator)) { _moderationLogService.LogTopic(user, ModerationType.TopicClose, topic, null); _topicRepository.CloseTopic(topic.TopicID); } else throw new InvalidOperationException("User must be Moderator to close topic."); } public void OpenTopic(Topic topic, User user) { if (user.IsInRole(PermanentRoles.Moderator)) { _moderationLogService.LogTopic(user, ModerationType.TopicOpen, topic, null); _topicRepository.OpenTopic(topic.TopicID); } else throw new InvalidOperationException("User must be Moderator to open topic."); } public void PinTopic(Topic topic, User user) { if (user.IsInRole(PermanentRoles.Moderator)) { _moderationLogService.LogTopic(user, ModerationType.TopicPin, topic, null); _topicRepository.PinTopic(topic.TopicID); } else throw new InvalidOperationException("User must be Moderator to pin topic."); } public void UnpinTopic(Topic topic, User user) { if (user.IsInRole(PermanentRoles.Moderator)) { _moderationLogService.LogTopic(user, ModerationType.TopicUnpin, topic, null); _topicRepository.UnpinTopic(topic.TopicID); } else throw new InvalidOperationException("User must be Moderator to unpin topic."); } public void DeleteTopic(Topic topic, User user) { if (user.IsInRole(PermanentRoles.Moderator) || user.UserID == topic.StartedByUserID) { _moderationLogService.LogTopic(user, ModerationType.TopicDelete, topic, null); _topicRepository.DeleteTopic(topic.TopicID); RecalculateReplyCount(topic); var forum = _forumService.Get(topic.ForumID); _forumService.UpdateCounts(forum); _forumService.UpdateLast(forum); } else throw new InvalidOperationException("User must be Moderator or topic starter to delete topic."); } public void UndeleteTopic(Topic topic, User user) { if (user.IsInRole(PermanentRoles.Moderator)) { _moderationLogService.LogTopic(user, ModerationType.TopicUndelete, topic, null); _topicRepository.UndeleteTopic(topic.TopicID); RecalculateReplyCount(topic); var forum = _forumService.Get(topic.ForumID); _forumService.UpdateCounts(forum); _forumService.UpdateLast(forum); } else throw new InvalidOperationException("User must be Moderator to undelete topic."); } public void UpdateTitleAndForum(Topic topic, Forum forum, string newTitle, User user) { if (user.IsInRole(PermanentRoles.Moderator)) { var oldTopic = _topicRepository.Get(topic.TopicID); if (oldTopic.ForumID != forum.ForumID) _moderationLogService.LogTopic(user, ModerationType.TopicMoved, topic, forum, String.Format("Moved from {0} to {1}", oldTopic.ForumID, forum.ForumID)); if (oldTopic.Title != newTitle) _moderationLogService.LogTopic(user, ModerationType.TopicRenamed, topic, forum, String.Format("Renamed from \"{0}\" to \"{1}\"", oldTopic.Title, newTitle)); var urlName = newTitle.ToUniqueUrlName(_topicRepository.GetUrlNamesThatStartWith(newTitle.ToUrlName())); topic.UrlName = urlName; _topicRepository.UpdateTitleAndForum(topic.TopicID, forum.ForumID, newTitle, urlName); _forumService.UpdateCounts(forum); _forumService.UpdateLast(forum); var oldForum = _forumService.Get(oldTopic.ForumID); _forumService.UpdateCounts(oldForum); _forumService.UpdateLast(oldForum); } else throw new InvalidOperationException("User must be Moderator to update topic title or move topic."); } public void RecalculateReplyCount(Topic topic) { var replyCount = _postRepository.GetReplyCount(topic.TopicID, false); _topicRepository.UpdateReplyCount(topic.TopicID, replyCount); } public DateTime? TopicLastPostTime(int topicID) { return _topicRepository.GetLastPostTime(topicID); } public void UpdateLast(Topic topic) { var post = _postRepository.GetLastInTopic(topic.TopicID); _topicRepository.UpdateLastTimeAndUser(topic.TopicID, post.UserID, post.Name, post.PostTime); } public int TopicLastPostID(int topicID) { var post = _postRepository.GetLastInTopic(topicID); if (post == null) return 0; return post.PostID; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; using System.Threading; using Xunit; public partial class NotifyFilterTests { [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_NotifyFilter_Attributes() { using (var file = Utility.CreateTestFile()) using (var watcher = new FileSystemWatcher(".")) { watcher.NotifyFilter = NotifyFilters.Attributes; watcher.Filter = Path.GetFileName(file.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; var attributes = File.GetAttributes(file.Path); attributes |= FileAttributes.ReadOnly; File.SetAttributes(file.Path, attributes); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] [PlatformSpecific(PlatformID.Windows | PlatformID.OSX)] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_NotifyFilter_CreationTime() { using (var file = Utility.CreateTestFile()) using (var watcher = new FileSystemWatcher(".")) { watcher.NotifyFilter = NotifyFilters.CreationTime; watcher.Filter = Path.GetFileName(file.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; File.SetCreationTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] public static void FileSystemWatcher_NotifyFilter_DirectoryName() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher(".")) { watcher.NotifyFilter = NotifyFilters.DirectoryName; watcher.Filter = Path.GetFileName(dir.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Renamed); string newName = dir.Path + "_rename"; Utility.EnsureDelete(newName); watcher.EnableRaisingEvents = true; dir.Move(newName); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_NotifyFilter_LastAccessTime() { using (var file = Utility.CreateTestFile()) using (var watcher = new FileSystemWatcher(".")) { watcher.NotifyFilter = NotifyFilters.LastAccess; watcher.Filter = Path.GetFileName(file.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; File.SetLastAccessTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_NotifyFilter_LastWriteTime() { using (var file = Utility.CreateTestFile()) using (var watcher = new FileSystemWatcher(".")) { watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.Filter = Path.GetFileName(file.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_NotifyFilter_Size() { using (var file = Utility.CreateTestFile()) using (var watcher = new FileSystemWatcher(".")) { watcher.NotifyFilter = NotifyFilters.Size; watcher.Filter = Path.GetFileName(file.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; byte[] buffer = new byte[16 * 1024]; file.Write(buffer, 0, buffer.Length); // Size changes only occur when the file is written to disk file.Flush(flushToDisk: true); Utility.ExpectEvent(eventOccured, "changed"); } } [DllImport( "api-ms-win-security-provider-l1-1-0.dll", EntryPoint = "SetNamedSecurityInfoW", CallingConvention = CallingConvention.Winapi, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)] private static extern uint SetSecurityInfoByHandle( string name, uint objectType, uint securityInformation, IntPtr owner, IntPtr group, IntPtr dacl, IntPtr sacl); private const uint ERROR_SUCCESS = 0; private const uint DACL_SECURITY_INFORMATION = 0x00000004; private const uint SE_FILE_OBJECT = 0x1; [Fact] [PlatformSpecific(PlatformID.Windows)] public static void FileSystemWatcher_NotifyFilter_Security() { using (var file = Utility.CreateTestFile()) using (var watcher = new FileSystemWatcher(".")) { watcher.NotifyFilter = NotifyFilters.Security; watcher.Filter = Path.GetFileName(file.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; // ACL support is not yet available, so pinvoke directly. uint result = SetSecurityInfoByHandle(file.Path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, // Only setting the DACL owner: IntPtr.Zero, group: IntPtr.Zero, dacl: IntPtr.Zero, // full access to everyone sacl: IntPtr.Zero); Assert.Equal(ERROR_SUCCESS, result); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_NotifyFilter_Negative() { using (var file = Utility.CreateTestFile()) using (var watcher = new FileSystemWatcher(".")) { // only detect name. watcher.NotifyFilter = NotifyFilters.FileName; watcher.Filter = Path.GetFileName(file.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.All); string newName = file.Path + "_rename"; Utility.EnsureDelete(newName); watcher.EnableRaisingEvents = true; // Change attributes var attributes = File.GetAttributes(file.Path); File.SetAttributes(file.Path, attributes | FileAttributes.ReadOnly); File.SetAttributes(file.Path, attributes); // Change creation time File.SetCreationTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); // Change access time File.SetLastAccessTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); // Change write time File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); // Change size byte[] buffer = new byte[16 * 1024]; file.Write(buffer, 0, buffer.Length); file.Flush(flushToDisk: true); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Change security uint result = SetSecurityInfoByHandle(file.Path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, // Only setting the DACL owner: IntPtr.Zero, group: IntPtr.Zero, dacl: IntPtr.Zero, // full access to everyone sacl: IntPtr.Zero); Assert.Equal(ERROR_SUCCESS, result); } // None of these should trigger any events Utility.ExpectNoEvent(eventOccured, "any"); } } }
using System; using System.Linq; using System.Runtime.InteropServices; namespace AllJoynDotNet { public partial class MsgArg : AllJoynWrapper { static MsgArg() { Init.Initialize(); } IntPtr _bytePtr; public MsgArg() : base(alljoyn_msgarg_create()) { } public MsgArg(string value) : this() { Set(value); } protected override void Dispose(bool disposing) { if (!IsDisposed) { if (_bytePtr != IntPtr.Zero) { Marshal.FreeCoTaskMem(_bytePtr); _bytePtr = IntPtr.Zero; } //alljoyn_msgarg_destroy(Handle); } base.Dispose(disposing); } private void Set(object value) { UIntPtr numArgs = (UIntPtr)1; string signature = ""; #if DEBUG //we don't cache the value in debug to provoke potential bugs. TODO: Remove later _value = null; _valueInitialized = false; #else _value = value; _valueInitialized = true; #endif if (_bytePtr != IntPtr.Zero) { Marshal.FreeCoTaskMem(_bytePtr); _bytePtr = IntPtr.Zero; } /* ALLJOYN_ARRAY = 'a', ///< AllJoyn array container type ALLJOYN_DICT_ENTRY = 'e', ///< AllJoyn dictionary or map container type - an array of key-value pairs ALLJOYN_SIGNATURE = 'g', ///< AllJoyn signature basic type ALLJOYN_HANDLE = 'h', ///< AllJoyn socket handle basic type ALLJOYN_STRUCT = 'r', ///< AllJoyn struct container type */ if (value.GetType() == typeof(string)) { signature = "s"; _bytePtr = Marshal.StringToCoTaskMemAnsi((string)value); alljoyn_msgarg_set(Handle, signature, __arglist(_bytePtr)); } else if (value.GetType() == typeof(bool)) { signature = "b"; int newValue = ((bool)value ? 1 : 0); alljoyn_msgarg_set(Handle, signature, __arglist(newValue)); } else if (value.GetType() == typeof(double) || value.GetType() == typeof(float)) { signature = "d"; alljoyn_msgarg_set(Handle, signature, __arglist((double)value)); } else if (value.GetType() == typeof(int)) { signature = "i"; alljoyn_msgarg_set(Handle, signature, __arglist((int)value)); } else if (value.GetType() == typeof(uint)) { signature = "u"; alljoyn_msgarg_set(Handle, signature, __arglist((uint)value)); } else if (value.GetType() == typeof(short)) { signature = "n"; alljoyn_msgarg_set(Handle, signature, __arglist((short)value)); } else if (value.GetType() == typeof(ushort)) { signature = "q"; alljoyn_msgarg_set(Handle, signature, __arglist((ushort)value)); } else if (value.GetType() == typeof(long)) { signature = "x"; alljoyn_msgarg_set(Handle, signature, __arglist((long)value)); } else if (value.GetType() == typeof(ulong)) { signature = "t"; alljoyn_msgarg_set(Handle, signature, __arglist((ulong)value)); } else if (value.GetType() == typeof(byte)) { signature = "y"; alljoyn_msgarg_set(Handle, signature, __arglist((byte)value)); } else if(value is Array) { SetArrayValue((Array)value); } else throw new NotSupportedException(); } private void SetArrayValue(Array elements) { var eType = elements.GetType().GetElementType(); if (eType == typeof(byte)) { var arr = (byte[])elements; alljoyn_msgarg_set_uint8_array(Handle, (UIntPtr)arr.Length, arr); } else if (eType == typeof(bool)) { var arr = (bool[])elements; alljoyn_msgarg_set_bool_array(Handle, (UIntPtr)arr.Length, arr.Select(t => t.ToQccBool()).ToArray()); } else if (eType == typeof(short)) { var arr = (short[])elements; alljoyn_msgarg_set_int16_array(Handle, (UIntPtr)arr.Length, arr); } else if (eType == typeof(ushort)) { var arr = (ushort[])elements; alljoyn_msgarg_set_uint16_array(Handle, (UIntPtr)arr.Length, arr); } else if (eType == typeof(int)) { var arr = (int[])elements; alljoyn_msgarg_set_int32_array(Handle, (UIntPtr)arr.Length, arr); } else if (eType == typeof(uint)) { var arr = (uint[])elements; alljoyn_msgarg_set_uint32_array(Handle, (UIntPtr)arr.Length, arr); } else if (eType == typeof(long)) { var arr = (long[])elements; alljoyn_msgarg_set_int64_array(Handle, (UIntPtr)arr.Length, arr); } else if (eType == typeof(ulong)) { var arr = (ulong[])elements; alljoyn_msgarg_set_uint64_array(Handle, (UIntPtr)arr.Length, arr); } else throw new NotImplementedException(); } public void Clear() { alljoyn_msgarg_clear(Handle); } private object _value; private bool _valueInitialized; private object _thisLock = new object(); public object Value { get { return System.Threading.LazyInitializer.EnsureInitialized(ref _value, ref _valueInitialized, ref _thisLock, () => { return TypeConversionHelpers.GetValueFromVariant(this, this.Signature); }); } set { Set(value); } } public string Signature { get { UIntPtr size = (UIntPtr)16; System.Text.StringBuilder sb = new System.Text.StringBuilder(256); var resultLength = (UInt64)alljoyn_msgarg_signature(Handle, sb, size + 1); return sb.ToString(); } } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace SIL.WritingSystems.Tests { public abstract class WritingSystemRepositoryTests { private IWritingSystemRepository _repositoryUnderTest; private WritingSystemDefinition _writingSystem; private WritingSystemIdChangedEventArgs _writingSystemIdChangedEventArgs; private WritingSystemDeletedEventArgs _writingSystemDeletedEventArgs; private WritingSystemConflatedEventArgs _writingSystemConflatedEventArgs; public IWritingSystemRepository RepositoryUnderTest { get { if (_repositoryUnderTest == null) { throw new InvalidOperationException("RepositoryUnderTest must be set before the tests are run."); } return _repositoryUnderTest; } set { _repositoryUnderTest = value; } } public abstract IWritingSystemRepository CreateNewStore(); [SetUp] public virtual void SetUp() { _writingSystem = new WritingSystemDefinition(); RepositoryUnderTest = CreateNewStore(); _writingSystemIdChangedEventArgs = null; _writingSystemDeletedEventArgs = null; _writingSystemConflatedEventArgs = null; } [TearDown] public virtual void TearDown() { } // Disabled because linux nunit-test runner can't handle Tests in abastract base class // TODO: refactor or fix nunit-runner #if !MONO [Test] public void SetTwoDefinitions_CountEquals2() { _writingSystem.Language = "one"; RepositoryUnderTest.Set(_writingSystem); var ws2 = new WritingSystemDefinition(); ws2.Language = "two"; RepositoryUnderTest.Set(ws2); Assert.AreEqual(2, RepositoryUnderTest.Count); } [Test] public void Conflate_TwoWritingSystemsOneIsConflatedIntoOther_OneWritingSystemRemains() { RepositoryUnderTest.Set(new WritingSystemDefinition("en")); RepositoryUnderTest.Set(new WritingSystemDefinition("de")); RepositoryUnderTest.Conflate("en", "de"); Assert.That(RepositoryUnderTest.Contains("de"), Is.True); Assert.That(RepositoryUnderTest.Contains("en"), Is.False); } [Test] public void Conflate_WritingSystemsIsConflated_FiresWritingSystemsIsConflatedEvent() { RepositoryUnderTest.WritingSystemConflated += OnWritingSystemConflated; RepositoryUnderTest.Set(new WritingSystemDefinition("en")); RepositoryUnderTest.Set(new WritingSystemDefinition("de")); RepositoryUnderTest.Conflate("en", "de"); Assert.That(RepositoryUnderTest.Contains("de"), Is.True); Assert.That(RepositoryUnderTest.Contains("en"), Is.False); Assert.That(_writingSystemConflatedEventArgs, Is.Not.Null); Assert.That(_writingSystemConflatedEventArgs.OldId, Is.EqualTo("en")); Assert.That(_writingSystemConflatedEventArgs.NewId, Is.EqualTo("de")); } [Test] public void Conflate_WritingSystemsIsConflated_FiresWritingSystemsIsDeletedEventIsNotFired() { RepositoryUnderTest.WritingSystemDeleted += OnWritingsystemDeleted; RepositoryUnderTest.Set(new WritingSystemDefinition("en")); RepositoryUnderTest.Set(new WritingSystemDefinition("de")); RepositoryUnderTest.Conflate("en", "de"); Assert.That(RepositoryUnderTest.Contains("de"), Is.True); Assert.That(RepositoryUnderTest.Contains("en"), Is.False); Assert.That(_writingSystemDeletedEventArgs, Is.Null); } private void OnWritingSystemConflated(object sender, WritingSystemConflatedEventArgs e) { _writingSystemConflatedEventArgs = e; } [Test] public void Remove_TwoWritingSystemsOneIsDeleted_OneWritingSystemRemains() { RepositoryUnderTest.Set(new WritingSystemDefinition("en")); RepositoryUnderTest.Set(new WritingSystemDefinition("de")); RepositoryUnderTest.Remove("en"); Assert.That(RepositoryUnderTest.Contains("de"), Is.True); Assert.That(RepositoryUnderTest.Contains("en"), Is.False); } [Test] public void CreateNewDefinition_CountEquals0() { RepositoryUnderTest.WritingSystemFactory.Create(); Assert.AreEqual(0, RepositoryUnderTest.Count); } [Test] public void SetDefinitionTwice_OnlySetOnce() { _writingSystem.Language = "one"; RepositoryUnderTest.Set(_writingSystem); Assert.AreEqual(1, RepositoryUnderTest.Count); var ws = new WritingSystemDefinition {Id = _writingSystem.Id}; RepositoryUnderTest.Set(ws); Assert.AreEqual(1, RepositoryUnderTest.Count); } [Test] public void Set_ClonedWritingSystemWithChangedId_CanGetWithNewId() { _writingSystem.Language = "one"; RepositoryUnderTest.Set(_writingSystem); Assert.AreEqual(1, RepositoryUnderTest.Count); var ws = new WritingSystemDefinition(_writingSystem); ws.Language = "de"; RepositoryUnderTest.Set(ws); Assert.AreEqual(2, RepositoryUnderTest.Count); Assert.AreEqual("de", ws.LanguageTag); } [Test] public void CreateNewDefinitionThenSet_CountEquals1() { RepositoryUnderTest.Set(RepositoryUnderTest.WritingSystemFactory.Create()); Assert.AreEqual(1, RepositoryUnderTest.Count); } [Test] public void SetSameDefinitionTwice_UpdatesStore() { _writingSystem.Language = "one"; RepositoryUnderTest.Set(_writingSystem); Assert.AreEqual(1, RepositoryUnderTest.Count); Assert.AreNotEqual("lang1", _writingSystem.Language.Name); _writingSystem.Language = new LanguageSubtag((LanguageSubtag) "two", "lang1"); RepositoryUnderTest.Set(_writingSystem); WritingSystemDefinition ws2 = RepositoryUnderTest.Get("two"); Assert.AreEqual("lang1", ws2.Language.Name); Assert.AreEqual(1, RepositoryUnderTest.Count); } /// <summary> /// Language tags should be case insensitive, as required by RFC 5646 /// </summary> [Test] public void Get_StoredWithUpperCaseButRequestedUsingLowerCase_Finds() { _writingSystem.Language = "sr"; _writingSystem.Script = "Latn"; _writingSystem.Variants.Add("RS"); RepositoryUnderTest.Set(_writingSystem); Assert.IsNotNull(RepositoryUnderTest.Get("sr-Latn-x-rs")); } /// <summary> /// Language tags should be case insensitive, as required by RFC 5646 /// </summary> [Test] public void Get_StoredWithLowerCaseButRequestedUsingUpperCase_Finds() { _writingSystem.Language = "sR"; _writingSystem.Script = "LaTn"; _writingSystem.Variants.Add("rs"); RepositoryUnderTest.Set(_writingSystem); Assert.IsNotNull(RepositoryUnderTest.Get("sr-Latn-x-RS")); } [Test] public void Contains_FalseThenTrue() { Assert.IsFalse(RepositoryUnderTest.Contains("one")); _writingSystem.Language = "one"; RepositoryUnderTest.Set(_writingSystem); Assert.IsTrue(RepositoryUnderTest.Contains("one")); } [Test] public void Remove_CountDecreases() { _writingSystem.Language = "one"; RepositoryUnderTest.Set(_writingSystem); Assert.AreEqual(1, RepositoryUnderTest.Count); RepositoryUnderTest.Remove(_writingSystem.LanguageTag); Assert.AreEqual(0, RepositoryUnderTest.Count); } [Test] public void CanStoreVariants_CountTwo() { var ws1 = new WritingSystemDefinition(); ws1.Language = "en"; Assert.AreEqual("en", ws1.LanguageTag); WritingSystemDefinition ws2 = ws1.Clone(); ws2.Variants.Add("1901"); Assert.AreEqual("en-1901", ws2.LanguageTag); RepositoryUnderTest.Set(ws1); Assert.AreEqual(1, RepositoryUnderTest.Count); RepositoryUnderTest.Set(ws2); Assert.AreEqual(2, RepositoryUnderTest.Count); } [Test] public void StoreTwoOfSame_Throws() { var ws1 = new WritingSystemDefinition("en"); var ws2 = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(ws1); Assert.Throws<ArgumentException>( () => RepositoryUnderTest.Set(ws2) ); } [Test] public void GetNewIdWhenSet_Null_Throws() { Assert.Throws<ArgumentNullException>( () => RepositoryUnderTest.GetNewIdWhenSet(null) ); } [Test] public void GetNewIdWhenSet_NewWritingSystem_ReturnsSameIdAsSet() { var ws = new WritingSystemDefinition("de"); string newId = RepositoryUnderTest.GetNewIdWhenSet(ws); RepositoryUnderTest.Set(ws); Assert.AreEqual(ws.Id, newId); } [Test] public void GetNewIdWhenSet_WritingSystemIsAlreadyRegisteredWithRepo_ReturnsSameIdAsSet() { var ws = new WritingSystemDefinition("de"); RepositoryUnderTest.Set(ws); ws.Language = "en"; string newId = RepositoryUnderTest.GetNewIdWhenSet(ws); Assert.AreEqual(ws.Id, newId); } [Test] public void CanSetAfterSetting_True() { RepositoryUnderTest.Set(_writingSystem); Assert.IsTrue(RepositoryUnderTest.CanSet(_writingSystem)); } [Test] public void CanSetNewWritingSystem_True() { Assert.IsTrue(RepositoryUnderTest.CanSet(_writingSystem)); } [Test] public void CanSetSecondNew_False() { RepositoryUnderTest.Set(_writingSystem); _writingSystem = RepositoryUnderTest.WritingSystemFactory.Create(); Assert.IsFalse(RepositoryUnderTest.CanSet(_writingSystem)); } [Test] public void CanSetNull_False() { Assert.IsFalse(RepositoryUnderTest.CanSet(null)); } [Test] public void GetNull_Throws() { Assert.Throws<ArgumentNullException>( () => RepositoryUnderTest.Get(null) ); } [Test] public void Get_NotInStore_Throws() { Assert.Throws<ArgumentOutOfRangeException>( () => RepositoryUnderTest.Get("I sure hope this isn't in the store.") ); } [Test] public void SetNull_Throws() { Assert.Throws<ArgumentNullException>( () => RepositoryUnderTest.Set(null) ); } [Test] public void RemoveNull_Throws() { Assert.Throws<ArgumentNullException>( () => RepositoryUnderTest.Remove(null) ); } [Test] public void Remove_NotInStore_Throws() { Assert.Throws<ArgumentOutOfRangeException>( () => RepositoryUnderTest.Remove("This isn't in the store!") ); } [Test] public void AllWritingSystems_HasAllWritingSystems_ReturnsAllWritingSystems() { var ws1 = new WritingSystemDefinition("fr"); ws1.IsVoice = true; RepositoryUnderTest.Set(ws1); RepositoryUnderTest.Set(new WritingSystemDefinition("de")); RepositoryUnderTest.Set(new WritingSystemDefinition("es")); Assert.IsTrue(RepositoryUnderTest.AllWritingSystems.Count() == 3); } [Test] public void VoiceWritingSystems_HasAllWritingSystems_ReturnsVoiceWritingSystems() { var ws1 = new WritingSystemDefinition("fr"); ws1.IsVoice = true; RepositoryUnderTest.Set(ws1); RepositoryUnderTest.Set(new WritingSystemDefinition("de")); RepositoryUnderTest.Set(new WritingSystemDefinition("es")); Assert.IsTrue(RepositoryUnderTest.VoiceWritingSystems().Count() == 1); } [Test] public void TextWritingSystems_HasAllWritingSystems_ReturnsTextWritingSystems() { var ws1 = new WritingSystemDefinition("fr"); ws1.IsVoice = true; RepositoryUnderTest.Set(ws1); RepositoryUnderTest.Set(new WritingSystemDefinition("de")); RepositoryUnderTest.Set(new WritingSystemDefinition("es")); Assert.IsTrue(RepositoryUnderTest.TextWritingSystems().Count() == 2); } [Test] public void FilterForTextLanguageTags_LanguageTagIsNotText_ReturnsEmpty() { var ws = new WritingSystemDefinition("en") {IsVoice = true}; RepositoryUnderTest.Set(ws); Assert.That(RepositoryUnderTest.FilterForTextLanguageTags(new[] {ws.LanguageTag}), Is.Empty); } [Test] public void FilterForTextLanguageTags_LanguageTagIsText_ReturnsIetfLanguageTag() { var ws = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(ws); Assert.That(RepositoryUnderTest.FilterForTextLanguageTags(new[] {ws.LanguageTag}), Is.EqualTo(new[] {"en"})); } [Test] public void FilterForTextLanguageTags_LanguageTagsAreMixOfTextAndNotText_ReturnsOnlyTextLanguageTags() { var ws = new WritingSystemDefinition("en"); var ws1 = new WritingSystemDefinition("de"); var ws2 = new WritingSystemDefinition("th"); ws2.IsVoice = true; var ws3 = new WritingSystemDefinition("pt"); ws3.IsVoice = true; RepositoryUnderTest.Set(ws); RepositoryUnderTest.Set(ws1); RepositoryUnderTest.Set(ws2); RepositoryUnderTest.Set(ws3); IEnumerable<string> langTagsToFilter = RepositoryUnderTest.AllWritingSystems.Select(wsinRepo => wsinRepo.LanguageTag); Assert.That(RepositoryUnderTest.FilterForTextLanguageTags(langTagsToFilter), Is.EqualTo(new[] {"en", "de"})); } [Test] public void FilterForTextIetfLanguageTags_PreservesOrderGivenByParameter() { RepositoryUnderTest.Set(new WritingSystemDefinition("ar")); RepositoryUnderTest.Set(new WritingSystemDefinition("en")); RepositoryUnderTest.Set(new WritingSystemDefinition("th")); string[] langTags = {"en", "ar", "th"}; Assert.That(RepositoryUnderTest.FilterForTextLanguageTags(langTags), Is.EqualTo(langTags)); langTags = new[] {"th", "ar", "en"}; Assert.That(RepositoryUnderTest.FilterForTextLanguageTags(langTags), Is.EqualTo(langTags)); } private void OnWritingSystemIdChanged(object sender, WritingSystemIdChangedEventArgs e) { _writingSystemIdChangedEventArgs = e; } [Test] public void Set_IdOfWritingSystemChanged_EventArgsAreCorrect() { RepositoryUnderTest.WritingSystemIdChanged += OnWritingSystemIdChanged; var ws = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(ws); ws.Language = "de"; RepositoryUnderTest.Set(ws); Assert.That(_writingSystemIdChangedEventArgs.OldId, Is.EqualTo("en")); Assert.That(_writingSystemIdChangedEventArgs.NewId, Is.EqualTo("de")); } [Test] public void Set_IdOfNewWritingSystemIsSetToOldIdOfOtherWritingSystem_GetReturnsCorrectWritingSystems() { var ws = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(ws); RepositoryUnderTest.Save(); ws.Variants.Add("orig"); RepositoryUnderTest.Set(ws); var newWs = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(newWs); Assert.That(RepositoryUnderTest.Get("en-x-orig"), Is.EqualTo(ws)); } [Test] public void Set_IdOfWritingSystemIsUnChanged_EventIsNotFired() { RepositoryUnderTest.WritingSystemIdChanged += OnWritingSystemIdChanged; var ws = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(ws); ws.Language = "en"; RepositoryUnderTest.Set(ws); Assert.That(_writingSystemIdChangedEventArgs, Is.Null); } [Test] public void Set_NewWritingSystem_EventIsNotFired() { RepositoryUnderTest.WritingSystemIdChanged += OnWritingSystemIdChanged; var ws = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(ws); Assert.That(_writingSystemIdChangedEventArgs, Is.Null); } public WritingSystemDeletedEventArgs WritingSystemDeletedEventArgs { get { return _writingSystemDeletedEventArgs; } } public void OnWritingsystemDeleted(object sender, WritingSystemDeletedEventArgs args) { _writingSystemDeletedEventArgs = args; } [Test] public void Remove_WritingsystemIdExists_FiresEventAndEventArgIsSetToIdOfDeletedWritingSystem() { RepositoryUnderTest.WritingSystemDeleted += OnWritingsystemDeleted; var ws = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(ws); RepositoryUnderTest.Remove(ws.LanguageTag); Assert.That(_writingSystemDeletedEventArgs.Id, Is.EqualTo(ws.LanguageTag)); } [Test] [Ignore("WritingSystemIdHasBeenChanged has not been implmented on LdmlInStreamWritingSystemRepository. A copy of this test exists in LdmlInFolderWritingSystemRepositoryTests")] public void WritingSystemIdHasBeenChanged_IdChanged_ReturnsTrue() { //Add a writing system to the repo var ws = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(ws); RepositoryUnderTest.Save(); //Now change the Id ws.Variants.Add("bogus"); RepositoryUnderTest.Save(); Assert.That(RepositoryUnderTest.WritingSystemIdHasChanged("en"), Is.True); } [Test] [Ignore("WritingSystemIdHasBeenChanged has not been implmented on LdmlInStreamWritingSystemRepository. A copy of this test exists in LdmlInFolderWritingSystemRepositoryTests")] public void WritingSystemIdHasBeenChanged_IdChangedToMultipleDifferentNewIds_ReturnsTrue() { //Add a writing system to the repo var wsEn = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(wsEn); RepositoryUnderTest.Save(); //Now change the Id and create a duplicate of the original Id wsEn.Variants.Add("bogus"); RepositoryUnderTest.Set(wsEn); var wsEnDup = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(wsEnDup); RepositoryUnderTest.Save(); //Now change the duplicate's Id as well wsEnDup.Variants.Add("bogus2"); RepositoryUnderTest.Set(wsEnDup); RepositoryUnderTest.Save(); Assert.That(RepositoryUnderTest.WritingSystemIdHasChanged("en"), Is.True); } [Test] [Ignore("WritingSystemIdHasBeenChanged has not been implmented on LdmlInStreamWritingSystemRepository. A copy of this test exists in LdmlInFolderWritingSystemRepositoryTests")] public void WritingSystemIdHasBeenChanged_IdExistsAndHasNeverChanged_ReturnsFalse() { //Add a writing system to the repo var ws = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(ws); RepositoryUnderTest.Save(); Assert.That(RepositoryUnderTest.WritingSystemIdHasChanged("en"), Is.False); } [Test] [Ignore("WritingSystemIdHasChangedTo has not been implmented on LdmlInStreamWritingSystemRepository. A copy of this test exists in LdmlInFolderWritingSystemRepositoryTests")] public void WritingSystemIdHasChangedTo_IdNeverExisted_ReturnsNull() { //Add a writing system to the repo Assert.That(RepositoryUnderTest.WritingSystemIdHasChangedTo("en"), Is.Null); } [Test] [Ignore("WritingSystemIdHasChangedTo has not been implmented on LdmlInStreamWritingSystemRepository. A copy of this test exists in LdmlInFolderWritingSystemRepositoryTests")] public void WritingSystemIdHasChangedTo_IdChanged_ReturnsNewId() { //Add a writing system to the repo var ws = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(ws); RepositoryUnderTest.Save(); //Now change the Id ws.Variants.Add("bogus"); RepositoryUnderTest.Save(); Assert.That(RepositoryUnderTest.WritingSystemIdHasChangedTo("en"), Is.EqualTo("en-x-bogus")); } [Test] [Ignore("WritingSystemIdHasChangedTo has not been implmented on LdmlInStreamWritingSystemRepository. A copy of this test exists in LdmlInFolderWritingSystemRepositoryTests")] public void WritingSystemIdHasChangedTo_IdChangedToMultipleDifferentNewIds_ReturnsNull() { //Add a writing system to the repo var wsEn = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(wsEn); RepositoryUnderTest.Save(); //Now change the Id and create a duplicate of the original Id wsEn.Variants.Add("bogus"); RepositoryUnderTest.Set(wsEn); var wsEnDup = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(wsEnDup); RepositoryUnderTest.Save(); //Now change the duplicate's Id as well wsEnDup.Variants.Add("bogus2"); RepositoryUnderTest.Set(wsEnDup); RepositoryUnderTest.Save(); Assert.That(RepositoryUnderTest.WritingSystemIdHasChangedTo("en"), Is.Null); } [Test] [Ignore("WritingSystemIdHasChangedTo has not been implmented on LdmlInStreamWritingSystemRepository. A copy of this test exists in LdmlInFolderWritingSystemRepositoryTests")] public void WritingSystemIdHasChangedTo_IdExistsAndHasNeverChanged_ReturnsId() { //Add a writing system to the repo var ws = new WritingSystemDefinition("en"); RepositoryUnderTest.Set(ws); RepositoryUnderTest.Save(); Assert.That(RepositoryUnderTest.WritingSystemIdHasChangedTo("en"), Is.EqualTo("en")); } #endif } }