context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using Lucene.Net.Documents; using Lucene.Net.Support; using NUnit.Framework; using System; using System.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Search { /* * 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IBits = Lucene.Net.Util.IBits; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; [TestFixture] public class TestDocIdSet : LuceneTestCase { [Test] public virtual void TestFilteredDocIdSet() { const int maxdoc = 10; DocIdSet innerSet = new DocIdSetAnonymousInnerClassHelper(this, maxdoc); DocIdSet filteredSet = new FilteredDocIdSetAnonymousInnerClassHelper(this, innerSet); DocIdSetIterator iter = filteredSet.GetIterator(); List<int?> list = new List<int?>(); int doc = iter.Advance(3); if (doc != DocIdSetIterator.NO_MORE_DOCS) { list.Add(Convert.ToInt32(doc)); while ((doc = iter.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { list.Add(Convert.ToInt32(doc)); } } int[] docs = new int[list.Count]; int c = 0; IEnumerator<int?> intIter = list.GetEnumerator(); while (intIter.MoveNext()) { docs[c++] = (int)intIter.Current; } int[] answer = new int[] { 4, 6, 8 }; bool same = Arrays.Equals(answer, docs); if (!same) { Console.WriteLine("answer: " + Arrays.ToString(answer)); Console.WriteLine("gotten: " + Arrays.ToString(docs)); Assert.Fail(); } } private class DocIdSetAnonymousInnerClassHelper : DocIdSet { private readonly TestDocIdSet outerInstance; private readonly int maxdoc; public DocIdSetAnonymousInnerClassHelper(TestDocIdSet outerInstance, int maxdoc) { this.outerInstance = outerInstance; this.maxdoc = maxdoc; } public override DocIdSetIterator GetIterator() { return new DocIdSetIteratorAnonymousInnerClassHelper(this); } private class DocIdSetIteratorAnonymousInnerClassHelper : DocIdSetIterator { private readonly DocIdSetAnonymousInnerClassHelper outerInstance; public DocIdSetIteratorAnonymousInnerClassHelper(DocIdSetAnonymousInnerClassHelper outerInstance) { this.outerInstance = outerInstance; docid = -1; } internal int docid; public override int DocID => docid; public override int NextDoc() { docid++; return docid < outerInstance.maxdoc ? docid : (docid = NO_MORE_DOCS); } public override int Advance(int target) { return SlowAdvance(target); } public override long GetCost() { return 1; } } } private class FilteredDocIdSetAnonymousInnerClassHelper : FilteredDocIdSet { private readonly TestDocIdSet outerInstance; public FilteredDocIdSetAnonymousInnerClassHelper(TestDocIdSet outerInstance, DocIdSet innerSet) : base(innerSet) { this.outerInstance = outerInstance; } protected override bool Match(int docid) { return docid % 2 == 0; //validate only even docids } } [Test] public virtual void TestNullDocIdSet() { // Tests that if a Filter produces a null DocIdSet, which is given to // IndexSearcher, everything works fine. this came up in LUCENE-1754. Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); doc.Add(NewStringField("c", "val", Field.Store.NO)); writer.AddDocument(doc); IndexReader reader = writer.GetReader(); writer.Dispose(); // First verify the document is searchable. IndexSearcher searcher = NewSearcher(reader); Assert.AreEqual(1, searcher.Search(new MatchAllDocsQuery(), 10).TotalHits); // Now search w/ a Filter which returns a null DocIdSet Filter f = new FilterAnonymousInnerClassHelper(this); Assert.AreEqual(0, searcher.Search(new MatchAllDocsQuery(), f, 10).TotalHits); reader.Dispose(); dir.Dispose(); } private class FilterAnonymousInnerClassHelper : Filter { private readonly TestDocIdSet outerInstance; public FilterAnonymousInnerClassHelper(TestDocIdSet outerInstance) { this.outerInstance = outerInstance; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { return null; } } [Test] public virtual void TestNullIteratorFilteredDocIdSet() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); doc.Add(NewStringField("c", "val", Field.Store.NO)); writer.AddDocument(doc); IndexReader reader = writer.GetReader(); writer.Dispose(); // First verify the document is searchable. IndexSearcher searcher = NewSearcher(reader); Assert.AreEqual(1, searcher.Search(new MatchAllDocsQuery(), 10).TotalHits); // Now search w/ a Filter which returns a null DocIdSet Filter f = new FilterAnonymousInnerClassHelper2(this); Assert.AreEqual(0, searcher.Search(new MatchAllDocsQuery(), f, 10).TotalHits); reader.Dispose(); dir.Dispose(); } private class FilterAnonymousInnerClassHelper2 : Filter { private readonly TestDocIdSet outerInstance; public FilterAnonymousInnerClassHelper2(TestDocIdSet outerInstance) { this.outerInstance = outerInstance; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { DocIdSet innerNullIteratorSet = new DocIdSetAnonymousInnerClassHelper2(this); return new FilteredDocIdSetAnonymousInnerClassHelper2(this, innerNullIteratorSet); } private class DocIdSetAnonymousInnerClassHelper2 : DocIdSet { private readonly FilterAnonymousInnerClassHelper2 outerInstance; public DocIdSetAnonymousInnerClassHelper2(FilterAnonymousInnerClassHelper2 outerInstance) { this.outerInstance = outerInstance; } public override DocIdSetIterator GetIterator() { return null; } } private class FilteredDocIdSetAnonymousInnerClassHelper2 : FilteredDocIdSet { private readonly FilterAnonymousInnerClassHelper2 outerInstance; public FilteredDocIdSetAnonymousInnerClassHelper2(FilterAnonymousInnerClassHelper2 outerInstance, DocIdSet innerNullIteratorSet) : base(innerNullIteratorSet) { this.outerInstance = outerInstance; } protected override bool Match(int docid) { return true; } } } } }
/** * Couchbase Lite for .NET * * Original iOS version by Jens Alfke * Android Port by Marty Schoch, Traun Leyden * C# Port by Zack Gramana * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections.Generic; using Couchbase.Lite; using Couchbase.Lite.Internal; using Couchbase.Lite.Util; using NUnit.Framework; using Sharpen; namespace Couchbase.Lite { public class ViewsTest : LiteTestCase { public const string Tag = "Views"; public virtual void TestQueryDefaultIndexUpdateMode() { View view = database.GetView("aview"); Query query = view.CreateQuery(); NUnit.Framework.Assert.AreEqual(Query.IndexUpdateMode.Before, query.GetIndexUpdateMode ()); } public virtual void TestViewCreation() { NUnit.Framework.Assert.IsNull(database.GetExistingView("aview")); View view = database.GetView("aview"); NUnit.Framework.Assert.IsNotNull(view); NUnit.Framework.Assert.AreEqual(database, view.GetDatabase()); NUnit.Framework.Assert.AreEqual("aview", view.GetName()); NUnit.Framework.Assert.IsNull(view.GetMap()); NUnit.Framework.Assert.AreEqual(view, database.GetExistingView("aview")); bool changed = view.SetMapReduce(new _Mapper_55(), null, "1"); //no-op NUnit.Framework.Assert.IsTrue(changed); NUnit.Framework.Assert.AreEqual(1, database.GetAllViews().Count); NUnit.Framework.Assert.AreEqual(view, database.GetAllViews()[0]); changed = view.SetMapReduce(new _Mapper_67(), null, "1"); //no-op NUnit.Framework.Assert.IsFalse(changed); changed = view.SetMapReduce(new _Mapper_77(), null, "2"); //no-op NUnit.Framework.Assert.IsTrue(changed); } private sealed class _Mapper_55 : Mapper { public _Mapper_55() { } public void Map(IDictionary<string, object> document, Emitter emitter) { } } private sealed class _Mapper_67 : Mapper { public _Mapper_67() { } public void Map(IDictionary<string, object> document, Emitter emitter) { } } private sealed class _Mapper_77 : Mapper { public _Mapper_77() { } public void Map(IDictionary<string, object> document, Emitter emitter) { } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> private RevisionInternal PutDoc(Database db, IDictionary<string, object> props) { RevisionInternal rev = new RevisionInternal(props, db); Status status = new Status(); rev = db.PutRevision(rev, null, false, status); NUnit.Framework.Assert.IsTrue(status.IsSuccessful()); return rev; } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> private void PutDocViaUntitledDoc(Database db, IDictionary<string, object> props) { Document document = db.CreateDocument(); document.PutProperties(props); } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual IList<RevisionInternal> PutDocs(Database db) { IList<RevisionInternal> result = new AList<RevisionInternal>(); IDictionary<string, object> dict2 = new Dictionary<string, object>(); dict2.Put("_id", "22222"); dict2.Put("key", "two"); result.AddItem(PutDoc(db, dict2)); IDictionary<string, object> dict4 = new Dictionary<string, object>(); dict4.Put("_id", "44444"); dict4.Put("key", "four"); result.AddItem(PutDoc(db, dict4)); IDictionary<string, object> dict1 = new Dictionary<string, object>(); dict1.Put("_id", "11111"); dict1.Put("key", "one"); result.AddItem(PutDoc(db, dict1)); IDictionary<string, object> dict3 = new Dictionary<string, object>(); dict3.Put("_id", "33333"); dict3.Put("key", "three"); result.AddItem(PutDoc(db, dict3)); IDictionary<string, object> dict5 = new Dictionary<string, object>(); dict5.Put("_id", "55555"); dict5.Put("key", "five"); result.AddItem(PutDoc(db, dict5)); return result; } // http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views#Linked_documents /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual IList<RevisionInternal> PutLinkedDocs(Database db) { IList<RevisionInternal> result = new AList<RevisionInternal>(); IDictionary<string, object> dict1 = new Dictionary<string, object>(); dict1.Put("_id", "11111"); result.AddItem(PutDoc(db, dict1)); IDictionary<string, object> dict2 = new Dictionary<string, object>(); dict2.Put("_id", "22222"); dict2.Put("value", "hello"); dict2.Put("ancestors", new string[] { "11111" }); result.AddItem(PutDoc(db, dict2)); IDictionary<string, object> dict3 = new Dictionary<string, object>(); dict3.Put("_id", "33333"); dict3.Put("value", "world"); dict3.Put("ancestors", new string[] { "22222", "11111" }); result.AddItem(PutDoc(db, dict3)); return result; } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void PutNDocs(Database db, int n) { for (int i = 0; i < n; i++) { IDictionary<string, object> doc = new Dictionary<string, object>(); doc.Put("_id", string.Format("%d", i)); IList<string> key = new AList<string>(); for (int j = 0; j < 256; j++) { key.AddItem("key"); } key.AddItem(string.Format("key-%d", i)); doc.Put("key", key); PutDocViaUntitledDoc(db, doc); } } public static View CreateView(Database db) { View view = db.GetView("aview"); view.SetMapReduce(new _Mapper_172(), null, "1"); return view; } private sealed class _Mapper_172 : Mapper { public _Mapper_172() { } public void Map(IDictionary<string, object> document, Emitter emitter) { NUnit.Framework.Assert.IsNotNull(document.Get("_id")); NUnit.Framework.Assert.IsNotNull(document.Get("_rev")); if (document.Get("key") != null) { emitter.Emit(document.Get("key"), null); } } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestViewIndex() { int numTimesMapFunctionInvoked = 0; IDictionary<string, object> dict1 = new Dictionary<string, object>(); dict1.Put("key", "one"); IDictionary<string, object> dict2 = new Dictionary<string, object>(); dict2.Put("key", "two"); IDictionary<string, object> dict3 = new Dictionary<string, object>(); dict3.Put("key", "three"); IDictionary<string, object> dictX = new Dictionary<string, object>(); dictX.Put("clef", "quatre"); RevisionInternal rev1 = PutDoc(database, dict1); RevisionInternal rev2 = PutDoc(database, dict2); RevisionInternal rev3 = PutDoc(database, dict3); PutDoc(database, dictX); View view = database.GetView("aview"); _T1975167965 mapBlock = new _T1975167965(this); view.SetMap(mapBlock, "1"); NUnit.Framework.Assert.AreEqual(1, view.GetViewId()); NUnit.Framework.Assert.IsTrue(view.IsStale()); view.UpdateIndex(); IList<IDictionary<string, object>> dumpResult = view.Dump(); Log.V(Tag, "View dump: " + dumpResult); NUnit.Framework.Assert.AreEqual(3, dumpResult.Count); NUnit.Framework.Assert.AreEqual("\"one\"", dumpResult[0].Get("key")); NUnit.Framework.Assert.AreEqual(1, dumpResult[0].Get("seq")); NUnit.Framework.Assert.AreEqual("\"two\"", dumpResult[2].Get("key")); NUnit.Framework.Assert.AreEqual(2, dumpResult[2].Get("seq")); NUnit.Framework.Assert.AreEqual("\"three\"", dumpResult[1].Get("key")); NUnit.Framework.Assert.AreEqual(3, dumpResult[1].Get("seq")); //no-op reindex NUnit.Framework.Assert.IsFalse(view.IsStale()); view.UpdateIndex(); // Now add a doc and update a doc: RevisionInternal threeUpdated = new RevisionInternal(rev3.GetDocId(), rev3.GetRevId (), false, database); numTimesMapFunctionInvoked = mapBlock.GetNumTimesInvoked(); IDictionary<string, object> newdict3 = new Dictionary<string, object>(); newdict3.Put("key", "3hree"); threeUpdated.SetProperties(newdict3); Status status = new Status(); rev3 = database.PutRevision(threeUpdated, rev3.GetRevId(), false, status); NUnit.Framework.Assert.IsTrue(status.IsSuccessful()); // Reindex again: NUnit.Framework.Assert.IsTrue(view.IsStale()); view.UpdateIndex(); // Make sure the map function was only invoked one more time (for the document that was added) NUnit.Framework.Assert.AreEqual(mapBlock.GetNumTimesInvoked(), numTimesMapFunctionInvoked + 1); IDictionary<string, object> dict4 = new Dictionary<string, object>(); dict4.Put("key", "four"); RevisionInternal rev4 = PutDoc(database, dict4); RevisionInternal twoDeleted = new RevisionInternal(rev2.GetDocId(), rev2.GetRevId (), true, database); database.PutRevision(twoDeleted, rev2.GetRevId(), false, status); NUnit.Framework.Assert.IsTrue(status.IsSuccessful()); // Reindex again: NUnit.Framework.Assert.IsTrue(view.IsStale()); view.UpdateIndex(); dumpResult = view.Dump(); Log.V(Tag, "View dump: " + dumpResult); NUnit.Framework.Assert.AreEqual(3, dumpResult.Count); NUnit.Framework.Assert.AreEqual("\"one\"", dumpResult[2].Get("key")); NUnit.Framework.Assert.AreEqual(1, dumpResult[2].Get("seq")); NUnit.Framework.Assert.AreEqual("\"3hree\"", dumpResult[0].Get("key")); NUnit.Framework.Assert.AreEqual(5, dumpResult[0].Get("seq")); NUnit.Framework.Assert.AreEqual("\"four\"", dumpResult[1].Get("key")); NUnit.Framework.Assert.AreEqual(6, dumpResult[1].Get("seq")); // Now do a real query: IList<QueryRow> rows = view.QueryWithOptions(null); NUnit.Framework.Assert.AreEqual(3, rows.Count); NUnit.Framework.Assert.AreEqual("one", rows[2].GetKey()); NUnit.Framework.Assert.AreEqual(rev1.GetDocId(), rows[2].GetDocumentId()); NUnit.Framework.Assert.AreEqual("3hree", rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(rev3.GetDocId(), rows[0].GetDocumentId()); NUnit.Framework.Assert.AreEqual("four", rows[1].GetKey()); NUnit.Framework.Assert.AreEqual(rev4.GetDocId(), rows[1].GetDocumentId()); view.DeleteIndex(); } internal class _T1975167965 : Mapper { internal int numTimesInvoked = 0; public virtual void Map(IDictionary<string, object> document, Emitter emitter) { this.numTimesInvoked += 1; NUnit.Framework.Assert.IsNotNull(document.Get("_id")); NUnit.Framework.Assert.IsNotNull(document.Get("_rev")); if (document.Get("key") != null) { emitter.Emit(document.Get("key"), null); } } public virtual int GetNumTimesInvoked() { return this.numTimesInvoked; } internal _T1975167965(ViewsTest _enclosing) { this._enclosing = _enclosing; } private readonly ViewsTest _enclosing; } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestViewQuery() { PutDocs(database); View view = CreateView(database); view.UpdateIndex(); // Query all rows: QueryOptions options = new QueryOptions(); IList<QueryRow> rows = view.QueryWithOptions(options); IList<object> expectedRows = new AList<object>(); IDictionary<string, object> dict5 = new Dictionary<string, object>(); dict5.Put("id", "55555"); dict5.Put("key", "five"); expectedRows.AddItem(dict5); IDictionary<string, object> dict4 = new Dictionary<string, object>(); dict4.Put("id", "44444"); dict4.Put("key", "four"); expectedRows.AddItem(dict4); IDictionary<string, object> dict1 = new Dictionary<string, object>(); dict1.Put("id", "11111"); dict1.Put("key", "one"); expectedRows.AddItem(dict1); IDictionary<string, object> dict3 = new Dictionary<string, object>(); dict3.Put("id", "33333"); dict3.Put("key", "three"); expectedRows.AddItem(dict3); IDictionary<string, object> dict2 = new Dictionary<string, object>(); dict2.Put("id", "22222"); dict2.Put("key", "two"); expectedRows.AddItem(dict2); NUnit.Framework.Assert.AreEqual(5, rows.Count); NUnit.Framework.Assert.AreEqual(dict5.Get("key"), rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(dict5.Get("value"), rows[0].GetValue()); NUnit.Framework.Assert.AreEqual(dict4.Get("key"), rows[1].GetKey()); NUnit.Framework.Assert.AreEqual(dict4.Get("value"), rows[1].GetValue()); NUnit.Framework.Assert.AreEqual(dict1.Get("key"), rows[2].GetKey()); NUnit.Framework.Assert.AreEqual(dict1.Get("value"), rows[2].GetValue()); NUnit.Framework.Assert.AreEqual(dict3.Get("key"), rows[3].GetKey()); NUnit.Framework.Assert.AreEqual(dict3.Get("value"), rows[3].GetValue()); NUnit.Framework.Assert.AreEqual(dict2.Get("key"), rows[4].GetKey()); NUnit.Framework.Assert.AreEqual(dict2.Get("value"), rows[4].GetValue()); // Start/end key query: options = new QueryOptions(); options.SetStartKey("a"); options.SetEndKey("one"); rows = view.QueryWithOptions(options); expectedRows = new AList<object>(); expectedRows.AddItem(dict5); expectedRows.AddItem(dict4); expectedRows.AddItem(dict1); NUnit.Framework.Assert.AreEqual(3, rows.Count); NUnit.Framework.Assert.AreEqual(dict5.Get("key"), rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(dict5.Get("value"), rows[0].GetValue()); NUnit.Framework.Assert.AreEqual(dict4.Get("key"), rows[1].GetKey()); NUnit.Framework.Assert.AreEqual(dict4.Get("value"), rows[1].GetValue()); NUnit.Framework.Assert.AreEqual(dict1.Get("key"), rows[2].GetKey()); NUnit.Framework.Assert.AreEqual(dict1.Get("value"), rows[2].GetValue()); // Start/end query without inclusive end: options.SetInclusiveEnd(false); rows = view.QueryWithOptions(options); expectedRows = new AList<object>(); expectedRows.AddItem(dict5); expectedRows.AddItem(dict4); NUnit.Framework.Assert.AreEqual(2, rows.Count); NUnit.Framework.Assert.AreEqual(dict5.Get("key"), rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(dict5.Get("value"), rows[0].GetValue()); NUnit.Framework.Assert.AreEqual(dict4.Get("key"), rows[1].GetKey()); NUnit.Framework.Assert.AreEqual(dict4.Get("value"), rows[1].GetValue()); // Reversed: options.SetDescending(true); options.SetStartKey("o"); options.SetEndKey("five"); options.SetInclusiveEnd(true); rows = view.QueryWithOptions(options); expectedRows = new AList<object>(); expectedRows.AddItem(dict4); expectedRows.AddItem(dict5); NUnit.Framework.Assert.AreEqual(2, rows.Count); NUnit.Framework.Assert.AreEqual(dict4.Get("key"), rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(dict4.Get("value"), rows[0].GetValue()); NUnit.Framework.Assert.AreEqual(dict5.Get("key"), rows[1].GetKey()); NUnit.Framework.Assert.AreEqual(dict5.Get("value"), rows[1].GetValue()); // Reversed, no inclusive end: options.SetInclusiveEnd(false); rows = view.QueryWithOptions(options); expectedRows = new AList<object>(); expectedRows.AddItem(dict4); NUnit.Framework.Assert.AreEqual(1, rows.Count); NUnit.Framework.Assert.AreEqual(dict4.Get("key"), rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(dict4.Get("value"), rows[0].GetValue()); // Specific keys: options = new QueryOptions(); IList<object> keys = new AList<object>(); keys.AddItem("two"); keys.AddItem("four"); options.SetKeys(keys); rows = view.QueryWithOptions(options); expectedRows = new AList<object>(); expectedRows.AddItem(dict4); expectedRows.AddItem(dict2); NUnit.Framework.Assert.AreEqual(2, rows.Count); NUnit.Framework.Assert.AreEqual(dict4.Get("key"), rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(dict4.Get("value"), rows[0].GetValue()); NUnit.Framework.Assert.AreEqual(dict2.Get("key"), rows[1].GetKey()); NUnit.Framework.Assert.AreEqual(dict2.Get("value"), rows[1].GetValue()); } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestAllDocsQuery() { IList<RevisionInternal> docs = PutDocs(database); IList<QueryRow> expectedRow = new AList<QueryRow>(); foreach (RevisionInternal rev in docs) { IDictionary<string, object> value = new Dictionary<string, object>(); value.Put("rev", rev.GetRevId()); value.Put("_conflicts", new AList<string>()); QueryRow queryRow = new QueryRow(rev.GetDocId(), 0, rev.GetDocId(), value, null); queryRow.SetDatabase(database); expectedRow.AddItem(queryRow); } QueryOptions options = new QueryOptions(); IDictionary<string, object> allDocs = database.GetAllDocs(options); IList<QueryRow> expectedRows = new AList<QueryRow>(); expectedRows.AddItem(expectedRow[2]); expectedRows.AddItem(expectedRow[0]); expectedRows.AddItem(expectedRow[3]); expectedRows.AddItem(expectedRow[1]); expectedRows.AddItem(expectedRow[4]); IDictionary<string, object> expectedQueryResult = CreateExpectedQueryResult(expectedRows , 0); NUnit.Framework.Assert.AreEqual(expectedQueryResult, allDocs); // Start/end key query: options = new QueryOptions(); options.SetStartKey("2"); options.SetEndKey("44444"); allDocs = database.GetAllDocs(options); expectedRows = new AList<QueryRow>(); expectedRows.AddItem(expectedRow[0]); expectedRows.AddItem(expectedRow[3]); expectedRows.AddItem(expectedRow[1]); expectedQueryResult = CreateExpectedQueryResult(expectedRows, 0); NUnit.Framework.Assert.AreEqual(expectedQueryResult, allDocs); // Start/end query without inclusive end: options.SetInclusiveEnd(false); allDocs = database.GetAllDocs(options); expectedRows = new AList<QueryRow>(); expectedRows.AddItem(expectedRow[0]); expectedRows.AddItem(expectedRow[3]); expectedQueryResult = CreateExpectedQueryResult(expectedRows, 0); NUnit.Framework.Assert.AreEqual(expectedQueryResult, allDocs); // Get all documents: with default QueryOptions options = new QueryOptions(); allDocs = database.GetAllDocs(options); expectedRows = new AList<QueryRow>(); expectedRows.AddItem(expectedRow[2]); expectedRows.AddItem(expectedRow[0]); expectedRows.AddItem(expectedRow[3]); expectedRows.AddItem(expectedRow[1]); expectedRows.AddItem(expectedRow[4]); expectedQueryResult = CreateExpectedQueryResult(expectedRows, 0); NUnit.Framework.Assert.AreEqual(expectedQueryResult, allDocs); // Get specific documents: options = new QueryOptions(); IList<object> docIds = new AList<object>(); QueryRow expected2 = expectedRow[2]; docIds.AddItem(expected2.GetDocument().GetId()); options.SetKeys(docIds); allDocs = database.GetAllDocs(options); expectedRows = new AList<QueryRow>(); expectedRows.AddItem(expected2); expectedQueryResult = CreateExpectedQueryResult(expectedRows, 0); NUnit.Framework.Assert.AreEqual(expectedQueryResult, allDocs); } private IDictionary<string, object> CreateExpectedQueryResult(IList<QueryRow> rows , int offset) { IDictionary<string, object> result = new Dictionary<string, object>(); result.Put("rows", rows); result.Put("total_rows", rows.Count); result.Put("offset", offset); return result; } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestViewReduce() { IDictionary<string, object> docProperties1 = new Dictionary<string, object>(); docProperties1.Put("_id", "CD"); docProperties1.Put("cost", 8.99); PutDoc(database, docProperties1); IDictionary<string, object> docProperties2 = new Dictionary<string, object>(); docProperties2.Put("_id", "App"); docProperties2.Put("cost", 1.95); PutDoc(database, docProperties2); IDictionary<string, object> docProperties3 = new Dictionary<string, object>(); docProperties3.Put("_id", "Dessert"); docProperties3.Put("cost", 6.50); PutDoc(database, docProperties3); View view = database.GetView("totaler"); view.SetMapReduce(new _Mapper_544(), new _Reducer_555(), "1"); view.UpdateIndex(); IList<IDictionary<string, object>> dumpResult = view.Dump(); Log.V(Tag, "View dump: " + dumpResult); NUnit.Framework.Assert.AreEqual(3, dumpResult.Count); NUnit.Framework.Assert.AreEqual("\"App\"", dumpResult[0].Get("key")); NUnit.Framework.Assert.AreEqual("1.95", dumpResult[0].Get("value")); NUnit.Framework.Assert.AreEqual(2, dumpResult[0].Get("seq")); NUnit.Framework.Assert.AreEqual("\"CD\"", dumpResult[1].Get("key")); NUnit.Framework.Assert.AreEqual("8.99", dumpResult[1].Get("value")); NUnit.Framework.Assert.AreEqual(1, dumpResult[1].Get("seq")); NUnit.Framework.Assert.AreEqual("\"Dessert\"", dumpResult[2].Get("key")); NUnit.Framework.Assert.AreEqual("6.5", dumpResult[2].Get("value")); NUnit.Framework.Assert.AreEqual(3, dumpResult[2].Get("seq")); QueryOptions options = new QueryOptions(); options.SetReduce(true); IList<QueryRow> reduced = view.QueryWithOptions(options); NUnit.Framework.Assert.AreEqual(1, reduced.Count); object value = reduced[0].GetValue(); Number numberValue = (Number)value; NUnit.Framework.Assert.IsTrue(Math.Abs(numberValue - 17.44) < 0.001); } private sealed class _Mapper_544 : Mapper { public _Mapper_544() { } public void Map(IDictionary<string, object> document, Emitter emitter) { NUnit.Framework.Assert.IsNotNull(document.Get("_id")); NUnit.Framework.Assert.IsNotNull(document.Get("_rev")); object cost = document.Get("cost"); if (cost != null) { emitter.Emit(document.Get("_id"), cost); } } } private sealed class _Reducer_555 : Reducer { public _Reducer_555() { } public object Reduce(IList<object> keys, IList<object> values, bool rereduce) { return View.TotalValues(values); } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestIndexUpdateMode() { View view = CreateView(database); Query query = view.CreateQuery(); query.SetIndexUpdateMode(Query.IndexUpdateMode.Before); int numRowsBefore = query.Run().GetCount(); NUnit.Framework.Assert.AreEqual(0, numRowsBefore); // do a query and force re-indexing, number of results should be +4 PutNDocs(database, 1); query.SetIndexUpdateMode(Query.IndexUpdateMode.Before); NUnit.Framework.Assert.AreEqual(1, query.Run().GetCount()); // do a query without re-indexing, number of results should be the same PutNDocs(database, 4); query.SetIndexUpdateMode(Query.IndexUpdateMode.Never); NUnit.Framework.Assert.AreEqual(1, query.Run().GetCount()); // do a query and force re-indexing, number of results should be +4 query.SetIndexUpdateMode(Query.IndexUpdateMode.Before); NUnit.Framework.Assert.AreEqual(5, query.Run().GetCount()); // do a query which will kick off an async index PutNDocs(database, 1); query.SetIndexUpdateMode(Query.IndexUpdateMode.After); query.Run().GetCount(); // wait until indexing is (hopefully) done try { Sharpen.Thread.Sleep(1 * 1000); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } NUnit.Framework.Assert.AreEqual(6, query.Run().GetCount()); } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestViewGrouped() { IDictionary<string, object> docProperties1 = new Dictionary<string, object>(); docProperties1.Put("_id", "1"); docProperties1.Put("artist", "Gang Of Four"); docProperties1.Put("album", "Entertainment!"); docProperties1.Put("track", "Ether"); docProperties1.Put("time", 231); PutDoc(database, docProperties1); IDictionary<string, object> docProperties2 = new Dictionary<string, object>(); docProperties2.Put("_id", "2"); docProperties2.Put("artist", "Gang Of Four"); docProperties2.Put("album", "Songs Of The Free"); docProperties2.Put("track", "I Love A Man In Uniform"); docProperties2.Put("time", 248); PutDoc(database, docProperties2); IDictionary<string, object> docProperties3 = new Dictionary<string, object>(); docProperties3.Put("_id", "3"); docProperties3.Put("artist", "Gang Of Four"); docProperties3.Put("album", "Entertainment!"); docProperties3.Put("track", "Natural's Not In It"); docProperties3.Put("time", 187); PutDoc(database, docProperties3); IDictionary<string, object> docProperties4 = new Dictionary<string, object>(); docProperties4.Put("_id", "4"); docProperties4.Put("artist", "PiL"); docProperties4.Put("album", "Metal Box"); docProperties4.Put("track", "Memories"); docProperties4.Put("time", 309); PutDoc(database, docProperties4); IDictionary<string, object> docProperties5 = new Dictionary<string, object>(); docProperties5.Put("_id", "5"); docProperties5.Put("artist", "Gang Of Four"); docProperties5.Put("album", "Entertainment!"); docProperties5.Put("track", "Not Great Men"); docProperties5.Put("time", 187); PutDoc(database, docProperties5); View view = database.GetView("grouper"); view.SetMapReduce(new _Mapper_671(), new _Reducer_681(), "1"); Status status = new Status(); view.UpdateIndex(); QueryOptions options = new QueryOptions(); options.SetReduce(true); IList<QueryRow> rows = view.QueryWithOptions(options); IList<IDictionary<string, object>> expectedRows = new AList<IDictionary<string, object >>(); IDictionary<string, object> row1 = new Dictionary<string, object>(); row1.Put("key", null); row1.Put("value", 1162.0); expectedRows.AddItem(row1); NUnit.Framework.Assert.AreEqual(row1.Get("key"), rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(row1.Get("value"), rows[0].GetValue()); //now group options.SetGroup(true); status = new Status(); rows = view.QueryWithOptions(options); expectedRows = new AList<IDictionary<string, object>>(); row1 = new Dictionary<string, object>(); IList<string> key1 = new AList<string>(); key1.AddItem("Gang Of Four"); key1.AddItem("Entertainment!"); key1.AddItem("Ether"); row1.Put("key", key1); row1.Put("value", 231.0); expectedRows.AddItem(row1); IDictionary<string, object> row2 = new Dictionary<string, object>(); IList<string> key2 = new AList<string>(); key2.AddItem("Gang Of Four"); key2.AddItem("Entertainment!"); key2.AddItem("Natural's Not In It"); row2.Put("key", key2); row2.Put("value", 187.0); expectedRows.AddItem(row2); IDictionary<string, object> row3 = new Dictionary<string, object>(); IList<string> key3 = new AList<string>(); key3.AddItem("Gang Of Four"); key3.AddItem("Entertainment!"); key3.AddItem("Not Great Men"); row3.Put("key", key3); row3.Put("value", 187.0); expectedRows.AddItem(row3); IDictionary<string, object> row4 = new Dictionary<string, object>(); IList<string> key4 = new AList<string>(); key4.AddItem("Gang Of Four"); key4.AddItem("Songs Of The Free"); key4.AddItem("I Love A Man In Uniform"); row4.Put("key", key4); row4.Put("value", 248.0); expectedRows.AddItem(row4); IDictionary<string, object> row5 = new Dictionary<string, object>(); IList<string> key5 = new AList<string>(); key5.AddItem("PiL"); key5.AddItem("Metal Box"); key5.AddItem("Memories"); row5.Put("key", key5); row5.Put("value", 309.0); expectedRows.AddItem(row5); NUnit.Framework.Assert.AreEqual(row1.Get("key"), rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(row1.Get("value"), rows[0].GetValue()); NUnit.Framework.Assert.AreEqual(row2.Get("key"), rows[1].GetKey()); NUnit.Framework.Assert.AreEqual(row2.Get("value"), rows[1].GetValue()); NUnit.Framework.Assert.AreEqual(row3.Get("key"), rows[2].GetKey()); NUnit.Framework.Assert.AreEqual(row3.Get("value"), rows[2].GetValue()); NUnit.Framework.Assert.AreEqual(row4.Get("key"), rows[3].GetKey()); NUnit.Framework.Assert.AreEqual(row4.Get("value"), rows[3].GetValue()); NUnit.Framework.Assert.AreEqual(row5.Get("key"), rows[4].GetKey()); NUnit.Framework.Assert.AreEqual(row5.Get("value"), rows[4].GetValue()); //group level 1 options.SetGroupLevel(1); status = new Status(); rows = view.QueryWithOptions(options); expectedRows = new AList<IDictionary<string, object>>(); row1 = new Dictionary<string, object>(); key1 = new AList<string>(); key1.AddItem("Gang Of Four"); row1.Put("key", key1); row1.Put("value", 853.0); expectedRows.AddItem(row1); row2 = new Dictionary<string, object>(); key2 = new AList<string>(); key2.AddItem("PiL"); row2.Put("key", key2); row2.Put("value", 309.0); expectedRows.AddItem(row2); NUnit.Framework.Assert.AreEqual(row1.Get("key"), rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(row1.Get("value"), rows[0].GetValue()); NUnit.Framework.Assert.AreEqual(row2.Get("key"), rows[1].GetKey()); NUnit.Framework.Assert.AreEqual(row2.Get("value"), rows[1].GetValue()); //group level 2 options.SetGroupLevel(2); status = new Status(); rows = view.QueryWithOptions(options); expectedRows = new AList<IDictionary<string, object>>(); row1 = new Dictionary<string, object>(); key1 = new AList<string>(); key1.AddItem("Gang Of Four"); key1.AddItem("Entertainment!"); row1.Put("key", key1); row1.Put("value", 605.0); expectedRows.AddItem(row1); row2 = new Dictionary<string, object>(); key2 = new AList<string>(); key2.AddItem("Gang Of Four"); key2.AddItem("Songs Of The Free"); row2.Put("key", key2); row2.Put("value", 248.0); expectedRows.AddItem(row2); row3 = new Dictionary<string, object>(); key3 = new AList<string>(); key3.AddItem("PiL"); key3.AddItem("Metal Box"); row3.Put("key", key3); row3.Put("value", 309.0); expectedRows.AddItem(row3); NUnit.Framework.Assert.AreEqual(row1.Get("key"), rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(row1.Get("value"), rows[0].GetValue()); NUnit.Framework.Assert.AreEqual(row2.Get("key"), rows[1].GetKey()); NUnit.Framework.Assert.AreEqual(row2.Get("value"), rows[1].GetValue()); NUnit.Framework.Assert.AreEqual(row3.Get("key"), rows[2].GetKey()); NUnit.Framework.Assert.AreEqual(row3.Get("value"), rows[2].GetValue()); } private sealed class _Mapper_671 : Mapper { public _Mapper_671() { } public void Map(IDictionary<string, object> document, Emitter emitter) { IList<object> key = new AList<object>(); key.AddItem(document.Get("artist")); key.AddItem(document.Get("album")); key.AddItem(document.Get("track")); emitter.Emit(key, document.Get("time")); } } private sealed class _Reducer_681 : Reducer { public _Reducer_681() { } public object Reduce(IList<object> keys, IList<object> values, bool rereduce) { return View.TotalValues(values); } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestViewGroupedStrings() { IDictionary<string, object> docProperties1 = new Dictionary<string, object>(); docProperties1.Put("name", "Alice"); PutDoc(database, docProperties1); IDictionary<string, object> docProperties2 = new Dictionary<string, object>(); docProperties2.Put("name", "Albert"); PutDoc(database, docProperties2); IDictionary<string, object> docProperties3 = new Dictionary<string, object>(); docProperties3.Put("name", "Naomi"); PutDoc(database, docProperties3); IDictionary<string, object> docProperties4 = new Dictionary<string, object>(); docProperties4.Put("name", "Jens"); PutDoc(database, docProperties4); IDictionary<string, object> docProperties5 = new Dictionary<string, object>(); docProperties5.Put("name", "Jed"); PutDoc(database, docProperties5); View view = database.GetView("default/names"); view.SetMapReduce(new _Mapper_859(), new _Reducer_869(), "1.0"); view.UpdateIndex(); QueryOptions options = new QueryOptions(); options.SetGroupLevel(1); IList<QueryRow> rows = view.QueryWithOptions(options); IList<IDictionary<string, object>> expectedRows = new AList<IDictionary<string, object >>(); IDictionary<string, object> row1 = new Dictionary<string, object>(); row1.Put("key", "A"); row1.Put("value", 2); expectedRows.AddItem(row1); IDictionary<string, object> row2 = new Dictionary<string, object>(); row2.Put("key", "J"); row2.Put("value", 2); expectedRows.AddItem(row2); IDictionary<string, object> row3 = new Dictionary<string, object>(); row3.Put("key", "N"); row3.Put("value", 1); expectedRows.AddItem(row3); NUnit.Framework.Assert.AreEqual(row1.Get("key"), rows[0].GetKey()); NUnit.Framework.Assert.AreEqual(row1.Get("value"), rows[0].GetValue()); NUnit.Framework.Assert.AreEqual(row2.Get("key"), rows[1].GetKey()); NUnit.Framework.Assert.AreEqual(row2.Get("value"), rows[1].GetValue()); NUnit.Framework.Assert.AreEqual(row3.Get("key"), rows[2].GetKey()); NUnit.Framework.Assert.AreEqual(row3.Get("value"), rows[2].GetValue()); } private sealed class _Mapper_859 : Mapper { public _Mapper_859() { } public void Map(IDictionary<string, object> document, Emitter emitter) { string name = (string)document.Get("name"); if (name != null) { emitter.Emit(Sharpen.Runtime.Substring(name, 0, 1), 1); } } } private sealed class _Reducer_869 : Reducer { public _Reducer_869() { } public object Reduce(IList<object> keys, IList<object> values, bool rereduce) { return values.Count; } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestViewCollation() { IList<object> list1 = new AList<object>(); list1.AddItem("a"); IList<object> list2 = new AList<object>(); list2.AddItem("b"); IList<object> list3 = new AList<object>(); list3.AddItem("b"); list3.AddItem("c"); IList<object> list4 = new AList<object>(); list4.AddItem("b"); list4.AddItem("c"); list4.AddItem("a"); IList<object> list5 = new AList<object>(); list5.AddItem("b"); list5.AddItem("d"); IList<object> list6 = new AList<object>(); list6.AddItem("b"); list6.AddItem("d"); list6.AddItem("e"); // Based on CouchDB's "view_collation.js" test IList<object> testKeys = new AList<object>(); testKeys.AddItem(null); testKeys.AddItem(false); testKeys.AddItem(true); testKeys.AddItem(0); testKeys.AddItem(2.5); testKeys.AddItem(10); testKeys.AddItem(" "); testKeys.AddItem("_"); testKeys.AddItem("~"); testKeys.AddItem("a"); testKeys.AddItem("A"); testKeys.AddItem("aa"); testKeys.AddItem("b"); testKeys.AddItem("B"); testKeys.AddItem("ba"); testKeys.AddItem("bb"); testKeys.AddItem(list1); testKeys.AddItem(list2); testKeys.AddItem(list3); testKeys.AddItem(list4); testKeys.AddItem(list5); testKeys.AddItem(list6); int i = 0; foreach (object key in testKeys) { IDictionary<string, object> docProperties = new Dictionary<string, object>(); docProperties.Put("_id", Sharpen.Extensions.ToString(i++)); docProperties.Put("name", key); PutDoc(database, docProperties); } View view = database.GetView("default/names"); view.SetMapReduce(new _Mapper_970(), null, "1.0"); QueryOptions options = new QueryOptions(); IList<QueryRow> rows = view.QueryWithOptions(options); i = 0; foreach (QueryRow row in rows) { NUnit.Framework.Assert.AreEqual(testKeys[i++], row.GetKey()); } } private sealed class _Mapper_970 : Mapper { public _Mapper_970() { } public void Map(IDictionary<string, object> document, Emitter emitter) { emitter.Emit(document.Get("name"), null); } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestViewCollationRaw() { IList<object> list1 = new AList<object>(); list1.AddItem("a"); IList<object> list2 = new AList<object>(); list2.AddItem("b"); IList<object> list3 = new AList<object>(); list3.AddItem("b"); list3.AddItem("c"); IList<object> list4 = new AList<object>(); list4.AddItem("b"); list4.AddItem("c"); list4.AddItem("a"); IList<object> list5 = new AList<object>(); list5.AddItem("b"); list5.AddItem("d"); IList<object> list6 = new AList<object>(); list6.AddItem("b"); list6.AddItem("d"); list6.AddItem("e"); // Based on CouchDB's "view_collation.js" test IList<object> testKeys = new AList<object>(); testKeys.AddItem(0); testKeys.AddItem(2.5); testKeys.AddItem(10); testKeys.AddItem(false); testKeys.AddItem(null); testKeys.AddItem(true); testKeys.AddItem(list1); testKeys.AddItem(list2); testKeys.AddItem(list3); testKeys.AddItem(list4); testKeys.AddItem(list5); testKeys.AddItem(list6); testKeys.AddItem(" "); testKeys.AddItem("A"); testKeys.AddItem("B"); testKeys.AddItem("_"); testKeys.AddItem("a"); testKeys.AddItem("aa"); testKeys.AddItem("b"); testKeys.AddItem("ba"); testKeys.AddItem("bb"); testKeys.AddItem("~"); int i = 0; foreach (object key in testKeys) { IDictionary<string, object> docProperties = new Dictionary<string, object>(); docProperties.Put("_id", Sharpen.Extensions.ToString(i++)); docProperties.Put("name", key); PutDoc(database, docProperties); } View view = database.GetView("default/names"); view.SetMapReduce(new _Mapper_1048(), null, "1.0"); view.SetCollation(View.TDViewCollation.TDViewCollationRaw); QueryOptions options = new QueryOptions(); IList<QueryRow> rows = view.QueryWithOptions(options); i = 0; foreach (QueryRow row in rows) { NUnit.Framework.Assert.AreEqual(testKeys[i++], row.GetKey()); } database.Close(); } private sealed class _Mapper_1048 : Mapper { public _Mapper_1048() { } public void Map(IDictionary<string, object> document, Emitter emitter) { emitter.Emit(document.Get("name"), null); } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestLargerViewQuery() { PutNDocs(database, 4); View view = CreateView(database); view.UpdateIndex(); // Query all rows: QueryOptions options = new QueryOptions(); Status status = new Status(); IList<QueryRow> rows = view.QueryWithOptions(options); } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestViewLinkedDocs() { PutLinkedDocs(database); View view = database.GetView("linked"); view.SetMapReduce(new _Mapper_1086(), null, "1"); view.UpdateIndex(); QueryOptions options = new QueryOptions(); options.SetIncludeDocs(true); // required for linked documents IList<QueryRow> rows = view.QueryWithOptions(options); NUnit.Framework.Assert.IsNotNull(rows); NUnit.Framework.Assert.AreEqual(5, rows.Count); object[][] expected = new object[][] { new object[] { "22222", "hello", 0, null, "22222" }, new object[] { "22222", "hello", 1, "11111", "11111" }, new object[] { "33333", "world", 0, null, "33333" }, new object[] { "33333", "world", 1, "22222" , "22222" }, new object[] { "33333", "world", 2, "11111", "11111" } }; for (int i = 0; i < rows.Count; i++) { QueryRow row = rows[i]; IDictionary<string, object> rowAsJson = row.AsJSONDictionary(); Log.D(Tag, string.Empty + rowAsJson); IList<object> key = (IList<object>)rowAsJson.Get("key"); IDictionary<string, object> doc = (IDictionary<string, object>)rowAsJson.Get("doc" ); string id = (string)rowAsJson.Get("id"); NUnit.Framework.Assert.AreEqual(expected[i][0], id); NUnit.Framework.Assert.AreEqual(2, key.Count); NUnit.Framework.Assert.AreEqual(expected[i][1], key[0]); NUnit.Framework.Assert.AreEqual(expected[i][2], key[1]); if (expected[i][3] == null) { NUnit.Framework.Assert.IsNull(row.GetValue()); } else { NUnit.Framework.Assert.AreEqual(expected[i][3], ((IDictionary<string, object>)row .GetValue()).Get("_id")); } NUnit.Framework.Assert.AreEqual(expected[i][4], doc.Get("_id")); } } private sealed class _Mapper_1086 : Mapper { public _Mapper_1086() { } public void Map(IDictionary<string, object> document, Emitter emitter) { if (document.ContainsKey("value")) { emitter.Emit(new object[] { document.Get("value"), 0 }, null); } if (document.ContainsKey("ancestors")) { IList<object> ancestors = (IList<object>)document.Get("ancestors"); for (int i = 0; i < ancestors.Count; i++) { IDictionary<string, object> value = new Dictionary<string, object>(); value.Put("_id", ancestors[i]); emitter.Emit(new object[] { document.Get("value"), i + 1 }, value); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Threading; using Xunit; public partial class ThreadPoolBoundHandleTests { [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_NullAsCallback_ThrowsArgumentNullException() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { AssertExtensions.Throws<ArgumentNullException>("callback", () => { handle.AllocateNativeOverlapped(null, new object(), new byte[256]); }); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_PreAllocated_ThrowsArgumentNullException() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { AssertExtensions.Throws<ArgumentNullException>("preAllocated", () => { handle.AllocateNativeOverlapped((PreAllocatedOverlapped)null); }); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_NullAsContext_DoesNotThrow() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, (object)null, new byte[256]); Assert.True(result != null); handle.FreeNativeOverlapped(result); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_NullAsPinData_DoesNotThrow() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), (byte[])null); Assert.True(result != null); handle.FreeNativeOverlapped(result); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_EmptyArrayAsPinData_DoesNotThrow() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[0]); Assert.True(result != null); handle.FreeNativeOverlapped(result); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_NonBlittableTypeAsPinData_Throws() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { AssertExtensions.Throws<ArgumentException>(null, () => handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new NonBlittableType() { s = "foo" })); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_BlittableTypeAsPinData_DoesNotThrow() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new BlittableType() { i = 42 }); Assert.True(result != null); handle.FreeNativeOverlapped(result); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_ObjectArrayAsPinData_DoesNotThrow() { object[] array = new object[] { new BlittableType() { i = 1 }, new byte[5], }; using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), array); Assert.True(result != null); handle.FreeNativeOverlapped(result); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_ObjectArrayWithNonBlittableTypeAsPinData_Throws() { object[] array = new object[] { new NonBlittableType() { s = "foo" }, new byte[5], }; using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { AssertExtensions.Throws<ArgumentException>(null, () => handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), array)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_ReturnedNativeOverlapped_AllFieldsZero() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* overlapped = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[256]); Assert.Equal(IntPtr.Zero, overlapped->InternalLow); Assert.Equal(IntPtr.Zero, overlapped->InternalHigh); Assert.Equal(0, overlapped->OffsetLow); Assert.Equal(0, overlapped->OffsetHigh); Assert.Equal(IntPtr.Zero, overlapped->EventHandle); handle.FreeNativeOverlapped(overlapped); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_PreAllocated_ReturnedNativeOverlapped_AllFieldsZero() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { using(PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped((_, __, ___) => { }, new object(), new byte[256])) { NativeOverlapped* overlapped = handle.AllocateNativeOverlapped(preAlloc); Assert.Equal(IntPtr.Zero, overlapped->InternalLow); Assert.Equal(IntPtr.Zero, overlapped->InternalHigh); Assert.Equal(0, overlapped->OffsetLow); Assert.Equal(0, overlapped->OffsetHigh); Assert.Equal(IntPtr.Zero, overlapped->EventHandle); handle.FreeNativeOverlapped(overlapped); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_PossibleReusedReturnedNativeOverlapped_OffsetLowAndOffsetHighSetToZero() { // The CLR reuses NativeOverlapped underneath, check to make sure that they reset fields back to zero using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { NativeOverlapped* overlapped = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[256]); overlapped->OffsetHigh = 1; overlapped->OffsetLow = 1; handle.FreeNativeOverlapped(overlapped); overlapped = handle.AllocateNativeOverlapped((errorCode, numBytes, overlap) => { }, new object(), new byte[256]); Assert.Equal(IntPtr.Zero, overlapped->InternalLow); Assert.Equal(IntPtr.Zero, overlapped->InternalHigh); Assert.Equal(0, overlapped->OffsetLow); Assert.Equal(0, overlapped->OffsetHigh); Assert.Equal(IntPtr.Zero, overlapped->EventHandle); handle.FreeNativeOverlapped(overlapped); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_PreAllocated_ReusedReturnedNativeOverlapped_OffsetLowAndOffsetHighSetToZero() { // The CLR reuses NativeOverlapped underneath, check to make sure that they reset fields back to zero using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped((_, __, ___) => { }, new object(), new byte[256]); NativeOverlapped* overlapped = handle.AllocateNativeOverlapped(preAlloc); overlapped->OffsetHigh = 1; overlapped->OffsetLow = 1; handle.FreeNativeOverlapped(overlapped); overlapped = handle.AllocateNativeOverlapped(preAlloc); Assert.Equal(IntPtr.Zero, overlapped->InternalLow); Assert.Equal(IntPtr.Zero, overlapped->InternalHigh); Assert.Equal(0, overlapped->OffsetLow); Assert.Equal(0, overlapped->OffsetHigh); Assert.Equal(IntPtr.Zero, overlapped->EventHandle); handle.FreeNativeOverlapped(overlapped); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_WhenDisposed_ThrowsObjectDisposedException() { ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle(); handle.Dispose(); Assert.Throws<ObjectDisposedException>(() => { handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[256]); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_PreAllocated_WhenDisposed_ThrowsObjectDisposedException() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped(delegate { }, null, null); preAlloc.Dispose(); Assert.Throws<ObjectDisposedException>(() => { handle.AllocateNativeOverlapped(preAlloc); }); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_PreAllocated_WhenHandleDisposed_ThrowsObjectDisposedException() { ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle(); handle.Dispose(); PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped(delegate { }, null, null); Assert.Throws<ObjectDisposedException>(() => { handle.AllocateNativeOverlapped(preAlloc); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix public unsafe void AllocateNativeOverlapped_PreAllocated_WhenAlreadyAllocated_ThrowsArgumentException() { using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle()) { using(PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped(delegate { }, null, null)) { NativeOverlapped* overlapped = handle.AllocateNativeOverlapped(preAlloc); AssertExtensions.Throws<ArgumentException>("preAllocated", () => { handle.AllocateNativeOverlapped(preAlloc); }); handle.FreeNativeOverlapped(overlapped); } } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Storages.Algo File: SecurityList.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Storages { using System; using System.Collections.Generic; using System.Data; using System.Linq; using Ecng.Collections; using Ecng.Common; using Ecng.Data; using Ecng.Data.Sql; using Ecng.Serialization; using MoreLinq; using StockSharp.BusinessEntities; /// <summary> /// The class for representation in the form of list of instruments, stored in external storage. /// </summary> public class SecurityList : BaseStorageEntityList<Security>, IStorageSecurityList { private readonly IEntityRegistry _registry; private readonly DatabaseCommand _readAllByCodeAndType; private readonly DatabaseCommand _readAllByCodeAndTypeAndExpiryDate; private readonly DatabaseCommand _readAllByType; private readonly DatabaseCommand _readAllByBoardAndType; private readonly DatabaseCommand _readAllByTypeAndExpiryDate; private readonly DatabaseCommand _readSecurityIds; private const string _code = nameof(Security.Code); private const string _type = nameof(Security.Type); private const string _expiryDate = nameof(Security.ExpiryDate); private const string _board = nameof(Security.Board); private const string _id = nameof(Security.Id); /// <summary> /// Initializes a new instance of the <see cref="SecurityList"/>. /// </summary> /// <param name="registry">The storage of trade objects.</param> public SecurityList(IEntityRegistry registry) : base(registry.Storage) { _registry = registry; var database = Storage as Database; if (database == null) return; var readAllByCodeAndType = database.CommandType == CommandType.StoredProcedure ? Query.Execute(Schema, SqlCommandTypes.ReadAll, string.Empty, "CodeAndType") : Query .Select(Schema) .From(Schema) .Where() .Like(Schema.Fields[_code]) .And() .OpenBracket() .IsParamNull(Schema.Fields[_type]) .Or() .Equals(Schema.Fields[_type]) .CloseBracket(); _readAllByCodeAndType = database.GetCommand(readAllByCodeAndType, Schema, new FieldList(Schema.Fields[_code], Schema.Fields[_type]), new FieldList()); var readAllByCodeAndTypeAndExpiryDate = database.CommandType == CommandType.StoredProcedure ? Query.Execute(Schema, SqlCommandTypes.ReadAll, string.Empty, "CodeAndTypeAndExpiryDate") : Query .Select(Schema) .From(Schema) .Where() .Like(Schema.Fields[_code]) .And() .OpenBracket() .IsParamNull(Schema.Fields[_type]) .Or() .Equals(Schema.Fields[_type]) .CloseBracket() .And() .OpenBracket() .IsNull(Schema.Fields[_expiryDate]) .Or() .Equals(Schema.Fields[_expiryDate]) .CloseBracket(); _readAllByCodeAndTypeAndExpiryDate = database.GetCommand(readAllByCodeAndTypeAndExpiryDate, Schema, new FieldList(Schema.Fields[_code], Schema.Fields[_type], Schema.Fields[_expiryDate]), new FieldList()); if (database.CommandType == CommandType.Text) { var readSecurityIds = Query .Execute("SELECT group_concat(Id, ',') FROM Security"); _readSecurityIds = database.GetCommand(readSecurityIds, null, new FieldList(), new FieldList()); var readAllByBoardAndType = Query .Select(Schema) .From(Schema) .Where() .Equals(Schema.Fields[_board]) .And() .OpenBracket() .IsParamNull(Schema.Fields[_type]) .Or() .Equals(Schema.Fields[_type]) .CloseBracket(); _readAllByBoardAndType = database.GetCommand(readAllByBoardAndType, Schema, new FieldList(Schema.Fields[_board], Schema.Fields[_type]), new FieldList()); var readAllByTypeAndExpiryDate = Query .Select(Schema) .From(Schema) .Where() .Equals(Schema.Fields[_type]) .And() .OpenBracket() .IsNull(Schema.Fields[_expiryDate]) .Or() .Equals(Schema.Fields[_expiryDate]) .CloseBracket(); _readAllByTypeAndExpiryDate = database.GetCommand(readAllByTypeAndExpiryDate, Schema, new FieldList(Schema.Fields[_type], Schema.Fields[_expiryDate]), new FieldList()); var readAllByType = Query .Select(Schema) .From(Schema) .Where() .Equals(Schema.Fields[_type]); _readAllByType = database.GetCommand(readAllByType, Schema, new FieldList(Schema.Fields[_type]), new FieldList()); RemoveQuery = Query .Delete() .From(Schema) .Where() .Equals(Schema.Fields[_id]); } ((ICollectionEx<Security>)this).AddedRange += s => _added?.Invoke(s); ((ICollectionEx<Security>)this).RemovedRange += s => _removed?.Invoke(s); } private Action<IEnumerable<Security>> _added; event Action<IEnumerable<Security>> ISecurityProvider.Added { add { _added += value; } remove { _added -= value; } } private Action<IEnumerable<Security>> _removed; event Action<IEnumerable<Security>> ISecurityProvider.Removed { add { _removed += value; } remove { _removed -= value; } } /// <summary> /// Lookup securities by criteria <paramref name="criteria" />. /// </summary> /// <param name="criteria">The instrument whose fields will be used as a filter.</param> /// <returns>Found instruments.</returns> public IEnumerable<Security> Lookup(Security criteria) { if (criteria.IsLookupAll()) return this.ToArray(); if (!criteria.Id.IsEmpty()) { var security = ReadById(criteria.Id); return security == null ? Enumerable.Empty<Security>() : new[] { security }; } if (!criteria.Code.IsEmpty() && _readAllByCodeAndType != null) { return criteria.ExpiryDate == null ? ReadAllByCodeAndType(criteria) : ReadAllByCodeAndTypeAndExpiryDate(criteria); } if (criteria.Board != null && _readAllByBoardAndType != null) { return ReadAllByBoardAndType(criteria); } if (criteria.Type != null && _readAllByTypeAndExpiryDate != null) { return criteria.ExpiryDate == null ? ReadAllByType(criteria) : ReadAllByTypeAndExpiryDate(criteria); } return this.Filter(criteria); } private IEnumerable<Security> ReadAllByCodeAndType(Security criteria) { var fields = new[] { new SerializationItem(Schema.Fields[_code], "%" + criteria.Code + "%"), new SerializationItem(Schema.Fields[_type], criteria.Type) }; return Database.ReadAll<Security>(_readAllByCodeAndType, new SerializationItemCollection(fields)); } private IEnumerable<Security> ReadAllByCodeAndTypeAndExpiryDate(Security criteria) { if (criteria.ExpiryDate == null) throw new ArgumentNullException(nameof(criteria), "ExpiryDate == null"); var fields = new[] { new SerializationItem(Schema.Fields[_code], "%" + criteria.Code + "%"), new SerializationItem(Schema.Fields[_type], criteria.Type), new SerializationItem(Schema.Fields[_expiryDate], criteria.ExpiryDate.Value) }; return Database.ReadAll<Security>(_readAllByCodeAndTypeAndExpiryDate, new SerializationItemCollection(fields)); } private IEnumerable<Security> ReadAllByBoardAndType(Security criteria) { var fields = new[] { new SerializationItem(Schema.Fields[_board], criteria.Board.Code), new SerializationItem(Schema.Fields[_type], criteria.Type) }; return Database.ReadAll<Security>(_readAllByCodeAndType, new SerializationItemCollection(fields)); } private IEnumerable<Security> ReadAllByTypeAndExpiryDate(Security criteria) { if (criteria.ExpiryDate == null) throw new ArgumentNullException(nameof(criteria), "ExpiryDate == null"); var fields = new[] { new SerializationItem(Schema.Fields[_type], criteria.Type), new SerializationItem(Schema.Fields[_expiryDate], criteria.ExpiryDate.Value) }; return Database.ReadAll<Security>(_readAllByTypeAndExpiryDate, new SerializationItemCollection(fields)); } private IEnumerable<Security> ReadAllByType(Security criteria) { var fields = new[] { new SerializationItem(Schema.Fields[_type], criteria.Type) }; return Database.ReadAll<Security>(_readAllByType, new SerializationItemCollection(fields)); } /// <summary> /// To save the trading object. /// </summary> /// <param name="entity">The trading object.</param> public override void Save(Security entity) { _registry.Exchanges.Save(entity.Board.Exchange); _registry.ExchangeBoards.Save(entity.Board); base.Save(entity); } /// <summary> /// To get identifiers of saved instruments. /// </summary> /// <returns>IDs securities.</returns> public IEnumerable<string> GetSecurityIds() { if (_readSecurityIds == null) return this.Select(s => s.Id); var str = _readSecurityIds.ExecuteScalar<string>(new SerializationItemCollection()); return str.SplitByComma(",", true); } /// <summary> /// It is called when adding element to the storage. /// </summary> /// <param name="entity">The trading object.</param> protected override void OnAdd(Security entity) { _registry.Exchanges.Save(entity.Board.Exchange); _registry.ExchangeBoards.Save(entity.Board); base.OnAdd(entity); } /// <summary> /// Delete security. /// </summary> /// <param name="security">Security.</param> public void Delete(Security security) { Remove(security); } /// <summary> /// To delete instruments by the criterion. /// </summary> /// <param name="criteria">The criterion.</param> public void DeleteBy(Security criteria) { this.Filter(criteria).ForEach(s => Remove(s)); } void IDisposable.Dispose() { } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.CompilerServices; using System.Security; using System.Text; using System.Text.RegularExpressions; namespace Godot { public static class StringExtensions { private static int GetSliceCount(this string instance, string splitter) { if (string.IsNullOrEmpty(instance) || string.IsNullOrEmpty(splitter)) return 0; int pos = 0; int slices = 1; while ((pos = instance.Find(splitter, pos, caseSensitive: true)) >= 0) { slices++; pos += splitter.Length; } return slices; } private static string GetSliceCharacter(this string instance, char splitter, int slice) { if (!string.IsNullOrEmpty(instance) && slice >= 0) { int i = 0; int prev = 0; int count = 0; while (true) { bool end = instance.Length <= i; if (end || instance[i] == splitter) { if (slice == count) { return instance.Substring(prev, i - prev); } else if (end) { return string.Empty; } count++; prev = i + 1; } i++; } } return string.Empty; } // <summary> // If the string is a path to a file, return the path to the file without the extension. // </summary> public static string BaseName(this string instance) { int index = instance.LastIndexOf('.'); if (index > 0) return instance.Substring(0, index); return instance; } // <summary> // Return true if the strings begins with the given string. // </summary> public static bool BeginsWith(this string instance, string text) { return instance.StartsWith(text); } // <summary> // Return the bigrams (pairs of consecutive letters) of this string. // </summary> public static string[] Bigrams(this string instance) { var b = new string[instance.Length - 1]; for (int i = 0; i < b.Length; i++) { b[i] = instance.Substring(i, 2); } return b; } // <summary> // Return the amount of substrings in string. // </summary> public static int Count(this string instance, string what, bool caseSensitive = true, int from = 0, int to = 0) { if (what.Length == 0) { return 0; } int len = instance.Length; int slen = what.Length; if (len < slen) { return 0; } string str; if (from >= 0 && to >= 0) { if (to == 0) { to = len; } else if (from >= to) { return 0; } if (from == 0 && to == len) { str = instance; } else { str = instance.Substring(from, to - from); } } else { return 0; } int c = 0; int idx; do { idx = str.IndexOf(what, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); if (idx != -1) { str = str.Substring(idx + slen); ++c; } } while (idx != -1); return c; } // <summary> // Return a copy of the string with special characters escaped using the C language standard. // </summary> public static string CEscape(this string instance) { var sb = new StringBuilder(string.Copy(instance)); sb.Replace("\\", "\\\\"); sb.Replace("\a", "\\a"); sb.Replace("\b", "\\b"); sb.Replace("\f", "\\f"); sb.Replace("\n", "\\n"); sb.Replace("\r", "\\r"); sb.Replace("\t", "\\t"); sb.Replace("\v", "\\v"); sb.Replace("\'", "\\'"); sb.Replace("\"", "\\\""); sb.Replace("?", "\\?"); return sb.ToString(); } // <summary> // Return a copy of the string with escaped characters replaced by their meanings according to the C language standard. // </summary> public static string CUnescape(this string instance) { var sb = new StringBuilder(string.Copy(instance)); sb.Replace("\\a", "\a"); sb.Replace("\\b", "\b"); sb.Replace("\\f", "\f"); sb.Replace("\\n", "\n"); sb.Replace("\\r", "\r"); sb.Replace("\\t", "\t"); sb.Replace("\\v", "\v"); sb.Replace("\\'", "\'"); sb.Replace("\\\"", "\""); sb.Replace("\\?", "?"); sb.Replace("\\\\", "\\"); return sb.ToString(); } // <summary> // Change the case of some letters. Replace underscores with spaces, convert all letters to lowercase then capitalize first and every letter following the space character. For [code]capitalize camelCase mixed_with_underscores[/code] it will return [code]Capitalize Camelcase Mixed With Underscores[/code]. // </summary> public static string Capitalize(this string instance) { string aux = instance.Replace("_", " ").ToLower(); var cap = string.Empty; for (int i = 0; i < aux.GetSliceCount(" "); i++) { string slice = aux.GetSliceCharacter(' ', i); if (slice.Length > 0) { slice = char.ToUpper(slice[0]) + slice.Substring(1); if (i > 0) cap += " "; cap += slice; } } return cap; } // <summary> // Perform a case-sensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater. // </summary> public static int CasecmpTo(this string instance, string to) { return instance.CompareTo(to, caseSensitive: true); } // <summary> // Perform a comparison to another string, return -1 if less, 0 if equal and +1 if greater. // </summary> public static int CompareTo(this string instance, string to, bool caseSensitive = true) { if (string.IsNullOrEmpty(instance)) return string.IsNullOrEmpty(to) ? 0 : -1; if (string.IsNullOrEmpty(to)) return 1; int instanceIndex = 0; int toIndex = 0; if (caseSensitive) // Outside while loop to avoid checking multiple times, despite some code duplication. { while (true) { if (to[toIndex] == 0 && instance[instanceIndex] == 0) return 0; // We're equal if (instance[instanceIndex] == 0) return -1; // If this is empty, and the other one is not, then we're less... I think? if (to[toIndex] == 0) return 1; // Otherwise the other one is smaller... if (instance[instanceIndex] < to[toIndex]) // More than return -1; if (instance[instanceIndex] > to[toIndex]) // Less than return 1; instanceIndex++; toIndex++; } } else { while (true) { if (to[toIndex] == 0 && instance[instanceIndex] == 0) return 0; // We're equal if (instance[instanceIndex] == 0) return -1; // If this is empty, and the other one is not, then we're less... I think? if (to[toIndex] == 0) return 1; // Otherwise the other one is smaller.. if (char.ToUpper(instance[instanceIndex]) < char.ToUpper(to[toIndex])) // More than return -1; if (char.ToUpper(instance[instanceIndex]) > char.ToUpper(to[toIndex])) // Less than return 1; instanceIndex++; toIndex++; } } } // <summary> // Return true if the strings ends with the given string. // </summary> public static bool EndsWith(this string instance, string text) { return instance.EndsWith(text); } // <summary> // Erase [code]chars[/code] characters from the string starting from [code]pos[/code]. // </summary> public static void Erase(this StringBuilder instance, int pos, int chars) { instance.Remove(pos, chars); } // <summary> // If the string is a path to a file, return the extension. // </summary> public static string Extension(this string instance) { int pos = instance.FindLast("."); if (pos < 0) return instance; return instance.Substring(pos + 1); } /// <summary>Find the first occurrence of a substring. Optionally, the search starting position can be passed.</summary> /// <returns>The starting position of the substring, or -1 if not found.</returns> public static int Find(this string instance, string what, int from = 0, bool caseSensitive = true) { return instance.IndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); } /// <summary>Find the last occurrence of a substring.</summary> /// <returns>The starting position of the substring, or -1 if not found.</returns> public static int FindLast(this string instance, string what, bool caseSensitive = true) { return instance.FindLast(what, instance.Length - 1, caseSensitive); } /// <summary>Find the last occurrence of a substring specifying the search starting position.</summary> /// <returns>The starting position of the substring, or -1 if not found.</returns> public static int FindLast(this string instance, string what, int from, bool caseSensitive = true) { return instance.LastIndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); } /// <summary>Find the first occurrence of a substring but search as case-insensitive. Optionally, the search starting position can be passed.</summary> /// <returns>The starting position of the substring, or -1 if not found.</returns> public static int FindN(this string instance, string what, int from = 0) { return instance.IndexOf(what, from, StringComparison.OrdinalIgnoreCase); } // <summary> // If the string is a path to a file, return the base directory. // </summary> public static string GetBaseDir(this string instance) { int basepos = instance.Find("://"); string rs; var @base = string.Empty; if (basepos != -1) { var end = basepos + 3; rs = instance.Substring(end); @base = instance.Substring(0, end); } else { if (instance.BeginsWith("/")) { rs = instance.Substring(1); @base = "/"; } else { rs = instance; } } int sep = Mathf.Max(rs.FindLast("/"), rs.FindLast("\\")); if (sep == -1) return @base; return @base + rs.Substr(0, sep); } // <summary> // If the string is a path to a file, return the file and ignore the base directory. // </summary> public static string GetFile(this string instance) { int sep = Mathf.Max(instance.FindLast("/"), instance.FindLast("\\")); if (sep == -1) return instance; return instance.Substring(sep + 1); } // <summary> // Hash the string and return a 32 bits integer. // </summary> public static int Hash(this string instance) { int index = 0; int hashv = 5381; int c; while ((c = instance[index++]) != 0) hashv = (hashv << 5) + hashv + c; // hash * 33 + c return hashv; } // <summary> // Convert a string containing an hexadecimal number into an int. // </summary> public static int HexToInt(this string instance) { int sign = 1; if (instance[0] == '-') { sign = -1; instance = instance.Substring(1); } if (!instance.StartsWith("0x")) return 0; return sign * int.Parse(instance.Substring(2), NumberStyles.HexNumber); } // <summary> // Insert a substring at a given position. // </summary> public static string Insert(this string instance, int pos, string what) { return instance.Insert(pos, what); } // <summary> // If the string is a path to a file or directory, return true if the path is absolute. // </summary> public static bool IsAbsPath(this string instance) { return System.IO.Path.IsPathRooted(instance); } // <summary> // If the string is a path to a file or directory, return true if the path is relative. // </summary> public static bool IsRelPath(this string instance) { return !System.IO.Path.IsPathRooted(instance); } // <summary> // Check whether this string is a subsequence of the given string. // </summary> public static bool IsSubsequenceOf(this string instance, string text, bool caseSensitive = true) { int len = instance.Length; if (len == 0) return true; // Technically an empty string is subsequence of any string if (len > text.Length) return false; int source = 0; int target = 0; while (source < len && target < text.Length) { bool match; if (!caseSensitive) { char sourcec = char.ToLower(instance[source]); char targetc = char.ToLower(text[target]); match = sourcec == targetc; } else { match = instance[source] == text[target]; } if (match) { source++; if (source >= len) return true; } target++; } return false; } // <summary> // Check whether this string is a subsequence of the given string, ignoring case differences. // </summary> public static bool IsSubsequenceOfI(this string instance, string text) { return instance.IsSubsequenceOf(text, caseSensitive: false); } // <summary> // Check whether the string contains a valid float. // </summary> public static bool IsValidFloat(this string instance) { float f; return float.TryParse(instance, out f); } // <summary> // Check whether the string contains a valid color in HTML notation. // </summary> public static bool IsValidHtmlColor(this string instance) { return Color.HtmlIsValid(instance); } // <summary> // Check whether the string is a valid identifier. As is common in programming languages, a valid identifier may contain only letters, digits and underscores (_) and the first character may not be a digit. // </summary> public static bool IsValidIdentifier(this string instance) { int len = instance.Length; if (len == 0) return false; for (int i = 0; i < len; i++) { if (i == 0) { if (instance[0] >= '0' && instance[0] <= '9') return false; // Don't start with number plz } bool validChar = instance[i] >= '0' && instance[i] <= '9' || instance[i] >= 'a' && instance[i] <= 'z' || instance[i] >= 'A' && instance[i] <= 'Z' || instance[i] == '_'; if (!validChar) return false; } return true; } // <summary> // Check whether the string contains a valid integer. // </summary> public static bool IsValidInteger(this string instance) { int f; return int.TryParse(instance, out f); } // <summary> // Check whether the string contains a valid IP address. // </summary> public static bool IsValidIPAddress(this string instance) { // TODO: Support IPv6 addresses string[] ip = instance.Split("."); if (ip.Length != 4) return false; for (int i = 0; i < ip.Length; i++) { string n = ip[i]; if (!n.IsValidInteger()) return false; int val = n.ToInt(); if (val < 0 || val > 255) return false; } return true; } // <summary> // Return a copy of the string with special characters escaped using the JSON standard. // </summary> public static string JSONEscape(this string instance) { var sb = new StringBuilder(string.Copy(instance)); sb.Replace("\\", "\\\\"); sb.Replace("\b", "\\b"); sb.Replace("\f", "\\f"); sb.Replace("\n", "\\n"); sb.Replace("\r", "\\r"); sb.Replace("\t", "\\t"); sb.Replace("\v", "\\v"); sb.Replace("\"", "\\\""); return sb.ToString(); } // <summary> // Return an amount of characters from the left of the string. // </summary> public static string Left(this string instance, int pos) { if (pos <= 0) return string.Empty; if (pos >= instance.Length) return instance; return instance.Substring(0, pos); } /// <summary> /// Return the length of the string in characters. /// </summary> public static int Length(this string instance) { return instance.Length; } // <summary> // Do a simple expression match, where '*' matches zero or more arbitrary characters and '?' matches any single character except '.'. // </summary> public static bool ExprMatch(this string instance, string expr, bool caseSensitive) { if (expr.Length == 0 || instance.Length == 0) return false; switch (expr[0]) { case '\0': return instance[0] == 0; case '*': return ExprMatch(expr + 1, instance, caseSensitive) || instance[0] != 0 && ExprMatch(expr, instance + 1, caseSensitive); case '?': return instance[0] != 0 && instance[0] != '.' && ExprMatch(expr + 1, instance + 1, caseSensitive); default: return (caseSensitive ? instance[0] == expr[0] : char.ToUpper(instance[0]) == char.ToUpper(expr[0])) && ExprMatch(expr + 1, instance + 1, caseSensitive); } } // <summary> // Do a simple case sensitive expression match, using ? and * wildcards (see [method expr_match]). // </summary> public static bool Match(this string instance, string expr, bool caseSensitive = true) { return instance.ExprMatch(expr, caseSensitive); } // <summary> // Do a simple case insensitive expression match, using ? and * wildcards (see [method expr_match]). // </summary> public static bool MatchN(this string instance, string expr) { return instance.ExprMatch(expr, caseSensitive: false); } // <summary> // Return the MD5 hash of the string as an array of bytes. // </summary> public static byte[] MD5Buffer(this string instance) { return godot_icall_String_md5_buffer(instance); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern static byte[] godot_icall_String_md5_buffer(string str); // <summary> // Return the MD5 hash of the string as a string. // </summary> public static string MD5Text(this string instance) { return godot_icall_String_md5_text(instance); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_String_md5_text(string str); // <summary> // Perform a case-insensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater. // </summary> public static int NocasecmpTo(this string instance, string to) { return instance.CompareTo(to, caseSensitive: false); } // <summary> // Return the character code at position [code]at[/code]. // </summary> public static int OrdAt(this string instance, int at) { return instance[at]; } // <summary> // Format a number to have an exact number of [code]digits[/code] after the decimal point. // </summary> public static string PadDecimals(this string instance, int digits) { int c = instance.Find("."); if (c == -1) { if (digits <= 0) return instance; instance += "."; c = instance.Length - 1; } else { if (digits <= 0) return instance.Substring(0, c); } if (instance.Length - (c + 1) > digits) { instance = instance.Substring(0, c + digits + 1); } else { while (instance.Length - (c + 1) < digits) { instance += "0"; } } return instance; } // <summary> // Format a number to have an exact number of [code]digits[/code] before the decimal point. // </summary> public static string PadZeros(this string instance, int digits) { string s = instance; int end = s.Find("."); if (end == -1) end = s.Length; if (end == 0) return s; int begin = 0; while (begin < end && (s[begin] < '0' || s[begin] > '9')) { begin++; } if (begin >= end) return s; while (end - begin < digits) { s = s.Insert(begin, "0"); end++; } return s; } // <summary> // Decode a percent-encoded string. See [method percent_encode]. // </summary> public static string PercentDecode(this string instance) { return Uri.UnescapeDataString(instance); } // <summary> // Percent-encode a string. This is meant to encode parameters in a URL when sending a HTTP GET request and bodies of form-urlencoded POST request. // </summary> public static string PercentEncode(this string instance) { return Uri.EscapeDataString(instance); } // <summary> // If the string is a path, this concatenates [code]file[/code] at the end of the string as a subpath. E.g. [code]"this/is".plus_file("path") == "this/is/path"[/code]. // </summary> public static string PlusFile(this string instance, string file) { if (instance.Length > 0 && instance[instance.Length - 1] == '/') return instance + file; return instance + "/" + file; } // <summary> // Replace occurrences of a substring for different ones inside the string. // </summary> public static string Replace(this string instance, string what, string forwhat) { return instance.Replace(what, forwhat); } // <summary> // Replace occurrences of a substring for different ones inside the string, but search case-insensitive. // </summary> public static string ReplaceN(this string instance, string what, string forwhat) { return Regex.Replace(instance, what, forwhat, RegexOptions.IgnoreCase); } // <summary> // Perform a search for a substring, but start from the end of the string instead of the beginning. // </summary> public static int RFind(this string instance, string what, int from = -1) { return godot_icall_String_rfind(instance, what, from); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_String_rfind(string str, string what, int from); // <summary> // Perform a search for a substring, but start from the end of the string instead of the beginning. Also search case-insensitive. // </summary> public static int RFindN(this string instance, string what, int from = -1) { return godot_icall_String_rfindn(instance, what, from); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_String_rfindn(string str, string what, int from); // <summary> // Return the right side of the string from a given position. // </summary> public static string Right(this string instance, int pos) { if (pos >= instance.Length) return instance; if (pos < 0) return string.Empty; return instance.Substring(pos, instance.Length - pos); } public static byte[] SHA256Buffer(this string instance) { return godot_icall_String_sha256_buffer(instance); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern static byte[] godot_icall_String_sha256_buffer(string str); // <summary> // Return the SHA-256 hash of the string as a string. // </summary> public static string SHA256Text(this string instance) { return godot_icall_String_sha256_text(instance); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_String_sha256_text(string str); // <summary> // Return the similarity index of the text compared to this string. 1 means totally similar and 0 means totally dissimilar. // </summary> public static float Similarity(this string instance, string text) { if (instance == text) { // Equal strings are totally similar return 1.0f; } if (instance.Length < 2 || text.Length < 2) { // No way to calculate similarity without a single bigram return 0.0f; } string[] sourceBigrams = instance.Bigrams(); string[] targetBigrams = text.Bigrams(); int sourceSize = sourceBigrams.Length; int targetSize = targetBigrams.Length; float sum = sourceSize + targetSize; float inter = 0; for (int i = 0; i < sourceSize; i++) { for (int j = 0; j < targetSize; j++) { if (sourceBigrams[i] == targetBigrams[j]) { inter++; break; } } } return 2.0f * inter / sum; } // <summary> // Split the string by a divisor string, return an array of the substrings. Example "One,Two,Three" will return ["One","Two","Three"] if split by ",". // </summary> public static string[] Split(this string instance, string divisor, bool allowEmpty = true) { return instance.Split(new[] { divisor }, StringSplitOptions.RemoveEmptyEntries); } // <summary> // Split the string in floats by using a divisor string, return an array of the substrings. Example "1,2.5,3" will return [1,2.5,3] if split by ",". // </summary> public static float[] SplitFloats(this string instance, string divisor, bool allowEmpty = true) { var ret = new List<float>(); int from = 0; int len = instance.Length; while (true) { int end = instance.Find(divisor, from, caseSensitive: true); if (end < 0) end = len; if (allowEmpty || end > from) ret.Add(float.Parse(instance.Substring(from))); if (end == len) break; from = end + divisor.Length; } return ret.ToArray(); } private static readonly char[] _nonPrintable = { (char)00, (char)01, (char)02, (char)03, (char)04, (char)05, (char)06, (char)07, (char)08, (char)09, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, (char)32 }; // <summary> // Return a copy of the string stripped of any non-printable character at the beginning and the end. The optional arguments are used to toggle stripping on the left and right edges respectively. // </summary> public static string StripEdges(this string instance, bool left = true, bool right = true) { if (left) { if (right) return instance.Trim(_nonPrintable); return instance.TrimStart(_nonPrintable); } return instance.TrimEnd(_nonPrintable); } // <summary> // Return part of the string from the position [code]from[/code], with length [code]len[/code]. // </summary> public static string Substr(this string instance, int from, int len) { int max = instance.Length - from; return instance.Substring(from, len > max ? max : len); } // <summary> // Convert the String (which is a character array) to PackedByteArray (which is an array of bytes). The conversion is speeded up in comparison to to_utf8() with the assumption that all the characters the String contains are only ASCII characters. // </summary> public static byte[] ToAscii(this string instance) { return Encoding.ASCII.GetBytes(instance); } // <summary> // Convert a string, containing a decimal number, into a [code]float[/code]. // </summary> public static float ToFloat(this string instance) { return float.Parse(instance); } // <summary> // Convert a string, containing an integer number, into an [code]int[/code]. // </summary> public static int ToInt(this string instance) { return int.Parse(instance); } // <summary> // Return the string converted to lowercase. // </summary> public static string ToLower(this string instance) { return instance.ToLower(); } // <summary> // Return the string converted to uppercase. // </summary> public static string ToUpper(this string instance) { return instance.ToUpper(); } // <summary> // Convert the String (which is an array of characters) to PackedByteArray (which is an array of bytes). The conversion is a bit slower than to_ascii(), but supports all UTF-8 characters. Therefore, you should prefer this function over to_ascii(). // </summary> public static byte[] ToUTF8(this string instance) { return Encoding.UTF8.GetBytes(instance); } // <summary> // Return a copy of the string with special characters escaped using the XML standard. // </summary> public static string XMLEscape(this string instance) { return SecurityElement.Escape(instance); } // <summary> // Return a copy of the string with escaped characters replaced by their meanings according to the XML standard. // </summary> public static string XMLUnescape(this string instance) { return SecurityElement.FromString(instance).Text; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Net.WebSockets; namespace Microsoft.AspNetCore.Owin { // http://owin.org/extensions/owin-WebSocket-Extension-v0.4.0.htm using WebSocketCloseAsync = Func<int /* closeStatus */, string /* closeDescription */, CancellationToken /* cancel */, Task>; using WebSocketReceiveAsync = Func<ArraySegment<byte> /* data */, CancellationToken /* cancel */, Task<Tuple<int /* messageType */, bool /* endOfMessage */, int /* count */>>>; using WebSocketSendAsync = Func<ArraySegment<byte> /* data */, int /* messageType */, bool /* endOfMessage */, CancellationToken /* cancel */, Task>; using RawWebSocketReceiveResult = Tuple<int, // type bool, // end of message? int>; // count /// <summary> /// OWIN WebSocket adapter. /// </summary> public class OwinWebSocketAdapter : WebSocket { private const int _rentedBufferSize = 1024; private readonly IDictionary<string, object> _websocketContext; private readonly WebSocketSendAsync _sendAsync; private readonly WebSocketReceiveAsync _receiveAsync; private readonly WebSocketCloseAsync _closeAsync; private WebSocketState _state; private readonly string _subProtocol; /// <summary> /// Initializes a new instance of <see cref="OwinWebSocketAdapter"/>. /// </summary> /// <param name="websocketContext">WebSocket context options.</param> /// <param name="subProtocol">The WebSocket subprotocol.</param> public OwinWebSocketAdapter(IDictionary<string, object> websocketContext, string subProtocol) { _websocketContext = websocketContext; _sendAsync = (WebSocketSendAsync)websocketContext[OwinConstants.WebSocket.SendAsync]; _receiveAsync = (WebSocketReceiveAsync)websocketContext[OwinConstants.WebSocket.ReceiveAsync]; _closeAsync = (WebSocketCloseAsync)websocketContext[OwinConstants.WebSocket.CloseAsync]; _state = WebSocketState.Open; _subProtocol = subProtocol; } /// <inheritdocs /> public override WebSocketCloseStatus? CloseStatus { get { object obj; if (_websocketContext.TryGetValue(OwinConstants.WebSocket.ClientCloseStatus, out obj)) { return (WebSocketCloseStatus)obj; } return null; } } /// <inheritdocs /> public override string CloseStatusDescription { get { object obj; if (_websocketContext.TryGetValue(OwinConstants.WebSocket.ClientCloseDescription, out obj)) { return (string)obj; } return null; } } /// <inheritdocs /> public override string SubProtocol { get { return _subProtocol; } } /// <inheritdocs /> public override WebSocketState State { get { return _state; } } /// <inheritdocs /> public override async Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) { var rawResult = await _receiveAsync(buffer, cancellationToken); var messageType = OpCodeToEnum(rawResult.Item1); if (messageType == WebSocketMessageType.Close) { if (State == WebSocketState.Open) { _state = WebSocketState.CloseReceived; } else if (State == WebSocketState.CloseSent) { _state = WebSocketState.Closed; } return new WebSocketReceiveResult(rawResult.Item3, messageType, rawResult.Item2, CloseStatus, CloseStatusDescription); } else { return new WebSocketReceiveResult(rawResult.Item3, messageType, rawResult.Item2); } } /// <inheritdocs /> public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) { return _sendAsync(buffer, EnumToOpCode(messageType), endOfMessage, cancellationToken); } /// <inheritdocs /> public override async Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { if (State == WebSocketState.Open || State == WebSocketState.CloseReceived) { await CloseOutputAsync(closeStatus, statusDescription, cancellationToken); } var buffer = ArrayPool<byte>.Shared.Rent(_rentedBufferSize); try { while (State == WebSocketState.CloseSent) { // Drain until close received await ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken); } } finally { ArrayPool<byte>.Shared.Return(buffer); } } /// <inheritdocs /> public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { // TODO: Validate state if (State == WebSocketState.Open) { _state = WebSocketState.CloseSent; } else if (State == WebSocketState.CloseReceived) { _state = WebSocketState.Closed; } return _closeAsync((int)closeStatus, statusDescription, cancellationToken); } /// <inheritdocs /> public override void Abort() { _state = WebSocketState.Aborted; } /// <inheritdocs /> public override void Dispose() { _state = WebSocketState.Closed; } private static WebSocketMessageType OpCodeToEnum(int messageType) { switch (messageType) { case 0x1: return WebSocketMessageType.Text; case 0x2: return WebSocketMessageType.Binary; case 0x8: return WebSocketMessageType.Close; default: throw new ArgumentOutOfRangeException(nameof(messageType), messageType, string.Empty); } } private static int EnumToOpCode(WebSocketMessageType webSocketMessageType) { switch (webSocketMessageType) { case WebSocketMessageType.Text: return 0x1; case WebSocketMessageType.Binary: return 0x2; case WebSocketMessageType.Close: return 0x8; default: throw new ArgumentOutOfRangeException(nameof(webSocketMessageType), webSocketMessageType, string.Empty); } } } }
/* * Created by SharpDevelop. * User: lextm * Date: 2008/5/17 * Time: 17:38 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using Lextm.SharpSnmpLib.Mib.Elements; using Lextm.SharpSnmpLib.Mib.Elements.Entities; using Lextm.SharpSnmpLib.Mib.Elements.Types; namespace Lextm.SharpSnmpLib.Mib { /// <summary> /// MIB module class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mib")] public sealed class MibModule : IModule { private readonly string _name; private readonly Imports _imports; private readonly Exports _exports; private readonly List<IElement> _tokens = new List<IElement>(); /// <summary> /// Creates a <see cref="MibModule"/> with a specific <see cref="Lexer"/>. /// </summary> /// <param name="name">Module name</param> /// <param name="symbols">Lexer</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "lexer")] public MibModule(ISymbolEnumerator symbols) { if (symbols == null) { throw new ArgumentNullException("lexer"); } Symbol temp = symbols.NextNonEOLSymbol(); temp.AssertIsValidIdentifier(); _name = temp.ToString().ToUpperInvariant(); // all module names are uppercase temp = symbols.NextNonEOLSymbol(); temp.Expect(Symbol.Definitions); temp = symbols.NextNonEOLSymbol(); temp.Expect(Symbol.Assign); temp = symbols.NextSymbol(); temp.Expect(Symbol.Begin); temp = symbols.NextNonEOLSymbol(); if (temp == Symbol.Imports) { _imports = ParseDependents(symbols); } else if (temp == Symbol.Exports) { _exports = ParseExports(symbols); } else { symbols.PutBack(temp); } ParseEntities(symbols); } #region Accessors /// <summary> /// Module name. /// </summary> public string Name { get { return _name; } } public Exports Exports { get { return _exports; } } public Imports Imports { get { return _imports; } } public List<IElement> Tokens { get { return this._tokens; } } /// <summary> /// Entities + Types + all other elements implementing IDeclaration /// </summary> public IList<IDeclaration> Declarations { get { IList<IDeclaration> result = new List<IDeclaration>(); foreach (IElement e in _tokens) { IDeclaration decl = e as IDeclaration; if (decl != null) { result.Add(decl); } } return result; } } /// <summary> /// OID nodes. /// </summary> public IList<IEntity> Entities { get { IList<IEntity> result = new List<IEntity>(); foreach (IElement e in _tokens) { IEntity entity = e as IEntity; if (entity != null) { result.Add(entity); } } return result; } } public IList<ITypeAssignment> Types { get { IList<ITypeAssignment> result = new List<ITypeAssignment>(); foreach (IElement e in _tokens) { ITypeAssignment type = e as ITypeAssignment; if (type != null) { result.Add(type); } } return result; } } #endregion #region Parsing of Symbols private Exports ParseExports(ISymbolEnumerator symbols) { return new Exports(this, symbols); } private Imports ParseDependents(ISymbolEnumerator symbols) { return new Imports(this, symbols); } private void ParseEntities(ISymbolEnumerator symbols) { Symbol temp = symbols.NextNonEOLSymbol(); SymbolList buffer = new SymbolList(); while (temp != Symbol.End) { if (temp == Symbol.Assign) { ParseEntity(buffer, symbols); buffer.Clear(); // skip linebreaks behind an entity temp = symbols.NextNonEOLSymbol(); } else { buffer.Add(temp); temp = symbols.NextSymbol(); } } } private void ParseEntity(SymbolList preAssignSymbols, ISymbolEnumerator symbols) { if ((preAssignSymbols == null) || (preAssignSymbols.Count == 0)) { Symbol s = symbols.NextSymbol(); if (s != null) { s.Assert(false, "Invalid Entitiy declaration"); } else { throw new MibException("Invalid Entitiy declaration"); } } // check for a valid identifier preAssignSymbols[0].AssertIsValidIdentifier(); if (preAssignSymbols.Count == 1) { // its a typedef _tokens.Add(Lexer.ParseBasicTypeDef(this, preAssignSymbols[0].ToString(), symbols, isMacroSyntax: false)); return; } ISymbolEnumerator preAssignSymbolsEnumerator = preAssignSymbols.GetSymbolEnumerator(); preAssignSymbolsEnumerator.NextNonEOLSymbol(); // returns identifier Symbol type = preAssignSymbolsEnumerator.NextNonEOLSymbol(); // parse declarations if (type == Symbol.Object) { Symbol next = preAssignSymbolsEnumerator.NextNonEOLSymbol(); if (next == Symbol.Identifier) { _tokens.Add(new OidValueAssignment(this, preAssignSymbols, symbols)); return; } else if (next != null) { preAssignSymbolsEnumerator.PutBack(next); } } if (type == Symbol.ModuleIdentity) { _tokens.Add(new ModuleIdentity(this, preAssignSymbols, symbols)); return; } if (type == Symbol.ObjectType) { _tokens.Add(new ObjectType(this, preAssignSymbols, symbols)); return; } if (type == Symbol.ObjectGroup) { _tokens.Add(new ObjectGroup(this, preAssignSymbols, symbols)); return; } if (type == Symbol.NotificationGroup) { _tokens.Add(new NotificationGroup(this, preAssignSymbols, symbols)); return; } if (type == Symbol.ModuleCompliance) { _tokens.Add(new ModuleCompliance(this, preAssignSymbols, symbols)); return; } if (type == Symbol.NotificationType) { _tokens.Add(new NotificationType(this, preAssignSymbols, symbols)); return; } if (type == Symbol.ObjectIdentity) { _tokens.Add(new ObjectIdentity(this, preAssignSymbols, symbols)); return; } if (type == Symbol.Macro) { _tokens.Add(new Macro(this, preAssignSymbols, symbols)); return; } if (type == Symbol.TrapType) { _tokens.Add(new TrapType(this, preAssignSymbols, symbols)); return; } if (type == Symbol.AgentCapabilities) { _tokens.Add(new AgentCapabilities(this, preAssignSymbols, symbols)); return; } preAssignSymbols[1].Assert(false, "Unknown/Invalid declaration"); } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Login.cs" company="The Watcher"> // Copyright (c) The Watcher Partial Rights Reserved. // This software is licensed under the MIT license. See license.txt for details. // </copyright> // <summary> // Code Named: PG-Ripper // Function : Extracts Images posted on VB forums and attempts to fetch them to disk. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Ripper { using System; using System.Drawing; using System.Linq; using System.Reflection; using System.Resources; using System.Windows.Forms; using Ripper.Core.Components; using Ripper.Core.Objects; /// <summary> /// The Login Dialog /// </summary> public partial class Login : Form { /// <summary> /// The Resource Manger Instance /// </summary> private ResourceManager rm; /// <summary> /// Initializes a new instance of the <see cref="Login"/> class. /// </summary> public Login() { this.InitializeComponent(); } /// <summary> /// Set Language Strings /// </summary> private void AdjustCulture() { this.groupBox1.Text = this.rm.GetString("gbLoginHead"); this.label1.Text = this.rm.GetString("lblUser"); this.label2.Text = this.rm.GetString("lblPass"); this.LoginButton.Text = this.rm.GetString("logintext"); this.label5.Text = this.rm.GetString("gbLanguage"); this.label6.Text = this.rm.GetString("lblForums"); this.GuestLogin.Text = this.rm.GetString("GuestLogin"); } /// <summary> /// Loads the Form /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void LoginLoad(object sender, EventArgs e) { // Set Default Forum this.ForumList.SelectedIndex = 0; // Load Language Setting try { var language = CacheController.Instance().UserSettings.Language; switch (language) { case "de-DE": this.LanuageSelector.SelectedIndex = 0; break; case "fr-FR": this.LanuageSelector.SelectedIndex = 1; break; case "en-EN": this.LanuageSelector.SelectedIndex = 2; break; default: this.LanuageSelector.SelectedIndex = 2; break; } } catch (Exception) { this.LanuageSelector.SelectedIndex = 2; } } /// <summary> /// Tries to Login to the Forums /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void LoginBtnClick(object sender, EventArgs e) { if (this.ForumUrl.Text.StartsWith("http://")) { if (!this.ForumUrl.Text.EndsWith("/")) { this.ForumUrl.Text += "/"; } CacheController.Instance().UserSettings.CurrentForumUrl = this.ForumUrl.Text; } string welcomeString = this.rm.GetString("lblWelcome"), lblFailed = this.rm.GetString("lblFailed"); if (this.GuestLogin.Checked) { this.UserNameField.Text = "Guest"; this.PasswordField.Text = "Guest"; this.label3.Text = string.Format("{0}{1}", welcomeString, this.UserNameField.Text); this.label3.ForeColor = Color.Green; this.LoginButton.Enabled = false; if ( CacheController.Instance().UserSettings.ForumsAccount.Any( item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl)) { CacheController.Instance().UserSettings.ForumsAccount.RemoveAll( item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl); } var forumsAccount = new ForumAccount { ForumURL = CacheController.Instance().UserSettings.CurrentForumUrl, UserName = this.UserNameField.Text, UserPassWord = this.PasswordField.Text, GuestAccount = false }; CacheController.Instance().UserSettings.ForumsAccount.Add(forumsAccount); CacheController.Instance().UserSettings.CurrentUserName = this.UserNameField.Text; this.timer1.Enabled = true; } else { // Encrypt Password this.PasswordField.Text = Utility.EncodePassword(this.PasswordField.Text).Replace("-", string.Empty).ToLower(); var loginManager = new LoginManager(this.UserNameField.Text, this.PasswordField.Text); if (loginManager.DoLogin(CacheController.Instance().UserSettings.CurrentForumUrl)) { this.label3.Text = string.Format("{0}{1}", welcomeString, this.UserNameField.Text); this.label3.ForeColor = Color.Green; this.LoginButton.Enabled = false; if ( CacheController.Instance().UserSettings.ForumsAccount.Any( item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl)) { CacheController.Instance().UserSettings.ForumsAccount.RemoveAll( item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl); } var forumsAccount = new ForumAccount { ForumURL = CacheController.Instance().UserSettings.CurrentForumUrl, UserName = this.UserNameField.Text, UserPassWord = this.PasswordField.Text, GuestAccount = false }; CacheController.Instance().UserSettings.ForumsAccount.Add(forumsAccount); CacheController.Instance().UserSettings.CurrentUserName = this.UserNameField.Text; this.timer1.Enabled = true; } else { this.label3.Text = lblFailed; this.label3.ForeColor = Color.Red; } } } /// <summary> /// If Login successfully send user data to MainForm /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.Timers.ElapsedEventArgs"/> instance containing the event data.</param> private void Timer1Elapsed(object sender, System.Timers.ElapsedEventArgs e) { this.timer1.Enabled = false; ((MainForm)Owner).cameThroughCorrectLogin = true; if (CacheController.Instance().UserSettings.ForumsAccount.Any(item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl)) { CacheController.Instance().UserSettings.ForumsAccount.RemoveAll( item => item.ForumURL == CacheController.Instance().UserSettings.CurrentForumUrl); } var forumsAccount = new ForumAccount { ForumURL = CacheController.Instance().UserSettings.CurrentForumUrl, UserName = this.UserNameField.Text, UserPassWord = this.PasswordField.Text, GuestAccount = this.GuestLogin.Checked }; CacheController.Instance().UserSettings.ForumsAccount.Add(forumsAccount); CacheController.Instance().UserSettings.CurrentUserName = this.UserNameField.Text; this.Close(); } /// <summary> /// Changes the UI Language based on the selected Language /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void LanuageSelectorIndexChanged(object sender, EventArgs e) { switch (this.LanuageSelector.SelectedIndex) { case 0: this.rm = new ResourceManager("Ripper.Languages.german", Assembly.GetExecutingAssembly()); CacheController.Instance().UserSettings.Language = "de-DE"; break; case 1: this.rm = new ResourceManager("Ripper.Languages.french", Assembly.GetExecutingAssembly()); CacheController.Instance().UserSettings.Language = "fr-FR"; break; case 2: this.rm = new ResourceManager("Ripper.Languages.english", Assembly.GetExecutingAssembly()); CacheController.Instance().UserSettings.Language = "en-EN"; break; default: this.rm = new ResourceManager("Ripper.Languages.english", Assembly.GetExecutingAssembly()); CacheController.Instance().UserSettings.Language = "en-EN"; break; } this.AdjustCulture(); } /// <summary> /// Forum Chooser /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void ForumSelectedIndexChanged(object sender, EventArgs e) { switch (this.ForumList.SelectedIndex) { case 2: this.ForumUrl.Text = "http://vipergirls.to/"; break; case 3: this.ForumUrl.Text = "http://forums.sexyandfunny.com/"; break; case 4: this.ForumUrl.Text = "http://forum.scanlover.com/"; break; case 5: this.ForumUrl.Text = "http://bignaturalsonly.com/"; break; case 6: this.ForumUrl.Text = "http://forum.phun.org/"; break; case 7: this.ForumUrl.Text = "http://..."; break; default: this.ForumUrl.Text = "http://..."; break; } } /// <summary> /// Handles the CheckedChanged event of the GuestLogin control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void GuestLogin_CheckedChanged(object sender, EventArgs e) { this.UserNameField.Enabled = !this.GuestLogin.Checked; this.PasswordField.Enabled = !this.GuestLogin.Checked; } } }
//------------------------------------------------------------------------------ // <copyright file="DataGridViewBand.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Text; using System; using System.Globalization; using System.Security; using System.Security.Permissions; /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand"]/*' /> /// <devdoc> /// <para>Identifies a band or column in the dataGridView.</para> /// </devdoc> public class DataGridViewBand : DataGridViewElement, ICloneable, IDisposable { private static readonly int PropContextMenuStrip = PropertyStore.CreateKey(); private static readonly int PropDefaultCellStyle = PropertyStore.CreateKey(); private static readonly int PropDefaultHeaderCellType = PropertyStore.CreateKey(); private static readonly int PropDividerThickness = PropertyStore.CreateKey(); private static readonly int PropHeaderCell = PropertyStore.CreateKey(); private static readonly int PropUserData = PropertyStore.CreateKey(); internal const int minBandThickness = 2; internal const int maxBandThickness = 65536; private PropertyStore propertyStore; // Contains all properties that are not always set. private int thickness, cachedThickness; private int minimumThickness; private int bandIndex; internal bool bandIsRow; /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.DataGridViewBand"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Windows.Forms.DataGridViewBand'/> class. /// </para> /// </devdoc> internal DataGridViewBand() { this.propertyStore = new PropertyStore(); this.bandIndex = -1; } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.Finalize"]/*' /> ~DataGridViewBand() { Dispose(false); } internal int CachedThickness { get { return this.cachedThickness; } set { this.cachedThickness = value; } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.ContextMenu"]/*' /> [ DefaultValue(null) ] public virtual ContextMenuStrip ContextMenuStrip { get { if (this.bandIsRow) { return ((DataGridViewRow) this).GetContextMenuStrip(this.Index); } return this.ContextMenuStripInternal; } set { this.ContextMenuStripInternal = value; } } internal ContextMenuStrip ContextMenuStripInternal { get { return (ContextMenuStrip)this.Properties.GetObject(PropContextMenuStrip); } set { ContextMenuStrip oldValue = (ContextMenuStrip)this.Properties.GetObject(PropContextMenuStrip); if (oldValue != value) { EventHandler disposedHandler = new EventHandler(DetachContextMenuStrip); if (oldValue != null) { oldValue.Disposed -= disposedHandler; } this.Properties.SetObject(PropContextMenuStrip, value); if (value != null) { value.Disposed += disposedHandler; } if (this.DataGridView != null) { this.DataGridView.OnBandContextMenuStripChanged(this); } } } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.DefaultCellStyle"]/*' /> [ Browsable(false) ] public virtual DataGridViewCellStyle DefaultCellStyle { get { DataGridViewCellStyle dgvcs = (DataGridViewCellStyle)this.Properties.GetObject(PropDefaultCellStyle); if (dgvcs == null) { dgvcs = new DataGridViewCellStyle(); dgvcs.AddScope(this.DataGridView, this.bandIsRow ? DataGridViewCellStyleScopes.Row : DataGridViewCellStyleScopes.Column); this.Properties.SetObject(PropDefaultCellStyle, dgvcs); } return dgvcs; } set { DataGridViewCellStyle dgvcs = null; if (this.HasDefaultCellStyle) { dgvcs = this.DefaultCellStyle; dgvcs.RemoveScope(this.bandIsRow ? DataGridViewCellStyleScopes.Row : DataGridViewCellStyleScopes.Column); } if (value != null || this.Properties.ContainsObject(PropDefaultCellStyle)) { if (value != null) { value.AddScope(this.DataGridView, this.bandIsRow ? DataGridViewCellStyleScopes.Row : DataGridViewCellStyleScopes.Column); } this.Properties.SetObject(PropDefaultCellStyle, value); } if (((dgvcs != null && value == null) || (dgvcs == null && value != null) || (dgvcs != null && value != null && !dgvcs.Equals(this.DefaultCellStyle))) && this.DataGridView != null) { this.DataGridView.OnBandDefaultCellStyleChanged(this); } } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.DefaultHeaderCellType"]/*' /> [ Browsable(false) ] public Type DefaultHeaderCellType { get { Type dhct = (Type)this.Properties.GetObject(PropDefaultHeaderCellType); if (dhct == null) { if (this.bandIsRow) { dhct = typeof(System.Windows.Forms.DataGridViewRowHeaderCell); } else { dhct = typeof(System.Windows.Forms.DataGridViewColumnHeaderCell); } } return dhct; } set { if (value != null || this.Properties.ContainsObject(PropDefaultHeaderCellType)) { if (Type.GetType("System.Windows.Forms.DataGridViewHeaderCell").IsAssignableFrom(value)) { this.Properties.SetObject(PropDefaultHeaderCellType, value); } else { throw new ArgumentException(SR.GetString(SR.DataGridView_WrongType, "DefaultHeaderCellType", "System.Windows.Forms.DataGridViewHeaderCell")); } } } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.Displayed"]/*' /> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public virtual bool Displayed { get { Debug.Assert(!this.bandIsRow); bool displayed = (this.State & DataGridViewElementStates.Displayed) != 0; // Only attached and visible columns can be displayed. // Debug.Assert(!displayed || (this.DataGridView != null && this.DataGridView.Visible && this.Visible)); return displayed; } } internal bool DisplayedInternal { set { Debug.Assert(value != this.Displayed); if (value) { this.StateInternal = this.State | DataGridViewElementStates.Displayed; } else { this.StateInternal = this.State & ~DataGridViewElementStates.Displayed; } if (this.DataGridView != null) { OnStateChanged(DataGridViewElementStates.Displayed); } } } internal int DividerThickness { get { bool found; int dividerThickness = this.Properties.GetInteger(PropDividerThickness, out found); return found ? dividerThickness : 0; } set { if (value < 0) { if (this.bandIsRow) { throw new ArgumentOutOfRangeException("DividerHeight", SR.GetString(SR.InvalidLowBoundArgumentEx, "DividerHeight", (value).ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture))); } else { throw new ArgumentOutOfRangeException("DividerWidth", SR.GetString(SR.InvalidLowBoundArgumentEx, "DividerWidth", (value).ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture))); } } if (value > maxBandThickness) { if (this.bandIsRow) { throw new ArgumentOutOfRangeException("DividerHeight", SR.GetString(SR.InvalidHighBoundArgumentEx, "DividerHeight", (value).ToString(CultureInfo.CurrentCulture), (maxBandThickness).ToString(CultureInfo.CurrentCulture))); } else { throw new ArgumentOutOfRangeException("DividerWidth", SR.GetString(SR.InvalidHighBoundArgumentEx, "DividerWidth", (value).ToString(CultureInfo.CurrentCulture), (maxBandThickness).ToString(CultureInfo.CurrentCulture))); } } if (value != this.DividerThickness) { this.Properties.SetInteger(PropDividerThickness, (int)value); if (this.DataGridView != null) { this.DataGridView.OnBandDividerThicknessChanged(this); } } } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.Frozen"]/*' /> [ DefaultValue(false), ] public virtual bool Frozen { get { Debug.Assert(!this.bandIsRow); return (this.State & DataGridViewElementStates.Frozen) != 0; } set { if (((this.State & DataGridViewElementStates.Frozen) != 0) != value) { OnStateChanging(DataGridViewElementStates.Frozen); if (value) { this.StateInternal = this.State | DataGridViewElementStates.Frozen; } else { this.StateInternal = this.State & ~DataGridViewElementStates.Frozen; } OnStateChanged(DataGridViewElementStates.Frozen); } } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.HasDefaultCellStyle"]/*' /> [ Browsable(false) ] public bool HasDefaultCellStyle { get { return this.Properties.ContainsObject(PropDefaultCellStyle) && this.Properties.GetObject(PropDefaultCellStyle) != null; } } internal bool HasDefaultHeaderCellType { get { return this.Properties.ContainsObject(PropDefaultHeaderCellType) && this.Properties.GetObject(PropDefaultHeaderCellType) != null; } } internal bool HasHeaderCell { get { return this.Properties.ContainsObject(PropHeaderCell) && this.Properties.GetObject(PropHeaderCell) != null; } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.HeaderCellCore"]/*' /> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] protected DataGridViewHeaderCell HeaderCellCore { get { DataGridViewHeaderCell headerCell = (DataGridViewHeaderCell)this.Properties.GetObject(PropHeaderCell); if (headerCell == null) { Type cellType = this.DefaultHeaderCellType; headerCell = (DataGridViewHeaderCell) SecurityUtils.SecureCreateInstance(cellType); headerCell.DataGridViewInternal = this.DataGridView; if (this.bandIsRow) { headerCell.OwningRowInternal = (DataGridViewRow)this; // may be a shared row this.Properties.SetObject(PropHeaderCell, headerCell); } else { DataGridViewColumn dataGridViewColumn = this as DataGridViewColumn; headerCell.OwningColumnInternal = dataGridViewColumn; // Set the headerCell in the property store before setting the SortOrder. // vsWhidbey 411787. this.Properties.SetObject(PropHeaderCell, headerCell); if (this.DataGridView != null && this.DataGridView.SortedColumn == dataGridViewColumn) { DataGridViewColumnHeaderCell dataGridViewColumnHeaderCell = headerCell as DataGridViewColumnHeaderCell; Debug.Assert(dataGridViewColumnHeaderCell != null); dataGridViewColumnHeaderCell.SortGlyphDirection = this.DataGridView.SortOrder; } } } return headerCell; } set { DataGridViewHeaderCell headerCell = (DataGridViewHeaderCell)this.Properties.GetObject(PropHeaderCell); if (value != null || this.Properties.ContainsObject(PropHeaderCell)) { if (headerCell != null) { headerCell.DataGridViewInternal = null; if (this.bandIsRow) { headerCell.OwningRowInternal = null; } else { headerCell.OwningColumnInternal = null; ((DataGridViewColumnHeaderCell)headerCell).SortGlyphDirectionInternal = SortOrder.None; } } if (value != null) { if (this.bandIsRow) { if (!(value is DataGridViewRowHeaderCell)) { throw new ArgumentException(SR.GetString(SR.DataGridView_WrongType, "HeaderCell", "System.Windows.Forms.DataGridViewRowHeaderCell")); } // A HeaderCell can only be used by one band. if (value.OwningRow != null) { value.OwningRow.HeaderCell = null; } Debug.Assert(value.OwningRow == null); value.OwningRowInternal = (DataGridViewRow)this; // may be a shared row } else { DataGridViewColumnHeaderCell dataGridViewColumnHeaderCell = value as DataGridViewColumnHeaderCell; if (dataGridViewColumnHeaderCell == null) { throw new ArgumentException(SR.GetString(SR.DataGridView_WrongType, "HeaderCell", "System.Windows.Forms.DataGridViewColumnHeaderCell")); } // A HeaderCell can only be used by one band. if (value.OwningColumn != null) { value.OwningColumn.HeaderCell = null; } Debug.Assert(dataGridViewColumnHeaderCell.SortGlyphDirection == SortOrder.None); Debug.Assert(value.OwningColumn == null); value.OwningColumnInternal = (DataGridViewColumn)this; } Debug.Assert(value.DataGridView == null); value.DataGridViewInternal = this.DataGridView; } this.Properties.SetObject(PropHeaderCell, value); } if (((value == null && headerCell != null) || (value != null && headerCell == null) || (value != null && headerCell != null && !headerCell.Equals(value))) && this.DataGridView != null) { this.DataGridView.OnBandHeaderCellChanged(this); } } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.Index"]/*' /> /// <devdoc> /// <para></para> /// </devdoc> [ Browsable(false) ] public int Index { get { return this.bandIndex; } } internal int IndexInternal { set { this.bandIndex = value; } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.InheritedStyle"]/*' /> [ Browsable(false) ] public virtual DataGridViewCellStyle InheritedStyle { get { return null; } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.IsRow"]/*' /> protected bool IsRow { get { return this.bandIsRow; } } internal int MinimumThickness { get { if (this.bandIsRow && this.bandIndex > -1) { int height, minimumHeight; GetHeightInfo(this.bandIndex, out height, out minimumHeight); return minimumHeight; } return this.minimumThickness; } set { if (this.minimumThickness != value) { if (value < minBandThickness) { if (this.bandIsRow) { throw new ArgumentOutOfRangeException("MinimumHeight", value, SR.GetString(SR.DataGridViewBand_MinimumHeightSmallerThanOne, (DataGridViewBand.minBandThickness).ToString(CultureInfo.CurrentCulture))); } else { throw new ArgumentOutOfRangeException("MinimumWidth", value, SR.GetString(SR.DataGridViewBand_MinimumWidthSmallerThanOne, (DataGridViewBand.minBandThickness).ToString(CultureInfo.CurrentCulture))); } } if (this.Thickness < value) { // Force the new minimum width on potential auto fill column. if (this.DataGridView != null && !this.bandIsRow) { this.DataGridView.OnColumnMinimumWidthChanging((DataGridViewColumn)this, value); } this.Thickness = value; } this.minimumThickness = value; if (this.DataGridView != null) { this.DataGridView.OnBandMinimumThicknessChanged(this); } } } } internal PropertyStore Properties { get { return this.propertyStore; } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.ReadOnly"]/*' /> [ DefaultValue(false) ] public virtual bool ReadOnly { get { Debug.Assert(!this.bandIsRow); return ((this.State & DataGridViewElementStates.ReadOnly) != 0 || (this.DataGridView != null && this.DataGridView.ReadOnly)); } set { if (this.DataGridView != null) { if (this.DataGridView.ReadOnly) { // if (!value): Trying to make a band read-write when the whole grid is read-only. // if (value): Trying to make a band read-only when the whole grid is read-only. // Ignoring the request and returning. return; } // this may trigger a call to set_ReadOnlyInternal if (this.bandIsRow) { if (this.bandIndex == -1) { throw new InvalidOperationException(SR.GetString(SR.DataGridView_InvalidPropertySetOnSharedRow, "ReadOnly")); } OnStateChanging(DataGridViewElementStates.ReadOnly); this.DataGridView.SetReadOnlyRowCore(this.bandIndex, value); } else { Debug.Assert(this.bandIndex >= 0); OnStateChanging(DataGridViewElementStates.ReadOnly); this.DataGridView.SetReadOnlyColumnCore(this.bandIndex, value); } } else { if (((this.State & DataGridViewElementStates.ReadOnly) != 0) != value) { if (value) { if (this.bandIsRow) { foreach (DataGridViewCell dataGridViewCell in ((DataGridViewRow) this).Cells) { if (dataGridViewCell.ReadOnly) { dataGridViewCell.ReadOnlyInternal = false; } } } this.StateInternal = this.State | DataGridViewElementStates.ReadOnly; } else { this.StateInternal = this.State & ~DataGridViewElementStates.ReadOnly; } } } } } internal bool ReadOnlyInternal { set { Debug.Assert(value != this.ReadOnly); if (value) { this.StateInternal = this.State | DataGridViewElementStates.ReadOnly; } else { this.StateInternal = this.State & ~DataGridViewElementStates.ReadOnly; } Debug.Assert(this.DataGridView != null); OnStateChanged(DataGridViewElementStates.ReadOnly); } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.Resizable"]/*' /> [ Browsable(true) ] public virtual DataGridViewTriState Resizable { get { Debug.Assert(!this.bandIsRow); if ((this.State & DataGridViewElementStates.ResizableSet) != 0) { return ((this.State & DataGridViewElementStates.Resizable) != 0) ? DataGridViewTriState.True : DataGridViewTriState.False; } if (this.DataGridView != null) { return this.DataGridView.AllowUserToResizeColumns ? DataGridViewTriState.True : DataGridViewTriState.False; } else { return DataGridViewTriState.NotSet; } } set { DataGridViewTriState oldResizable = this.Resizable; if (value == DataGridViewTriState.NotSet) { this.StateInternal = this.State & ~DataGridViewElementStates.ResizableSet; } else { this.StateInternal = this.State | DataGridViewElementStates.ResizableSet; if (((this.State & DataGridViewElementStates.Resizable) != 0) != (value == DataGridViewTriState.True)) { if (value == DataGridViewTriState.True) { this.StateInternal = this.State | DataGridViewElementStates.Resizable; } else { Debug.Assert(value == DataGridViewTriState.False, "TriState only supports NotSet, True, False"); this.StateInternal = this.State & ~DataGridViewElementStates.Resizable; } } } if (oldResizable != this.Resizable) { OnStateChanged(DataGridViewElementStates.Resizable); } } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.Selected"]/*' /> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public virtual bool Selected { get { Debug.Assert(!this.bandIsRow); return (this.State & DataGridViewElementStates.Selected) != 0; } set { if (this.DataGridView != null) { // this may trigger a call to set_SelectedInternal if (this.bandIsRow) { if (this.bandIndex == -1) { throw new InvalidOperationException(SR.GetString(SR.DataGridView_InvalidPropertySetOnSharedRow, "Selected")); } if (this.DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect || this.DataGridView.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { this.DataGridView.SetSelectedRowCoreInternal(this.bandIndex, value); } } else { Debug.Assert(this.bandIndex >= 0); if (this.DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || this.DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { this.DataGridView.SetSelectedColumnCoreInternal(this.bandIndex, value); } } } else if (value) { // We do not allow the selection of a band before it gets added to the dataGridView. throw new InvalidOperationException(SR.GetString(SR.DataGridViewBand_CannotSelect)); } } } internal bool SelectedInternal { set { Debug.Assert(value != this.Selected); if (value) { this.StateInternal = this.State | DataGridViewElementStates.Selected; } else { this.StateInternal = this.State & ~DataGridViewElementStates.Selected; } if (this.DataGridView != null) { OnStateChanged(DataGridViewElementStates.Selected); } } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.Tag"]/*' /> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public object Tag { get { return Properties.GetObject(PropUserData); } set { if (value != null || this.Properties.ContainsObject(PropUserData)) { Properties.SetObject(PropUserData, value); } } } internal int Thickness { get { if (this.bandIsRow && this.bandIndex > -1) { int height, minimumHeight; GetHeightInfo(this.bandIndex, out height, out minimumHeight); return height; } return this.thickness; } set { int minimumThickness = this.MinimumThickness; if (value < minimumThickness) { value = minimumThickness; } if (value > maxBandThickness) { if (this.bandIsRow) { throw new ArgumentOutOfRangeException("Height", SR.GetString(SR.InvalidHighBoundArgumentEx, "Height", (value).ToString(CultureInfo.CurrentCulture), (maxBandThickness).ToString(CultureInfo.CurrentCulture))); } else { throw new ArgumentOutOfRangeException("Width", SR.GetString(SR.InvalidHighBoundArgumentEx, "Width", (value).ToString(CultureInfo.CurrentCulture), (maxBandThickness).ToString(CultureInfo.CurrentCulture))); } } bool setThickness = true; if (this.bandIsRow) { if (this.DataGridView != null && this.DataGridView.AutoSizeRowsMode != DataGridViewAutoSizeRowsMode.None) { this.cachedThickness = value; setThickness = false; } } else { DataGridViewColumn dataGridViewColumn = (DataGridViewColumn) this; DataGridViewAutoSizeColumnMode inheritedAutoSizeMode = dataGridViewColumn.InheritedAutoSizeMode; if (inheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.Fill && inheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.None && inheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.NotSet) { this.cachedThickness = value; setThickness = false; } else if (inheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill && this.DataGridView != null) { if (dataGridViewColumn.Visible) { IntPtr handle = this.DataGridView.Handle; this.DataGridView.AdjustFillingColumn(dataGridViewColumn, value); setThickness = false; } } } if (setThickness && this.thickness != value) { if (this.DataGridView != null) { this.DataGridView.OnBandThicknessChanging(); } this.ThicknessInternal = value; } } } internal int ThicknessInternal { get { return this.thickness; } set { Debug.Assert(this.thickness != value); Debug.Assert(value >= this.minimumThickness); Debug.Assert(value <= maxBandThickness); this.thickness = value; if (this.DataGridView != null) { this.DataGridView.OnBandThicknessChanged(this); } } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.Visible"]/*' /> [ DefaultValue(true), ] public virtual bool Visible { get { Debug.Assert(!this.bandIsRow); return (this.State & DataGridViewElementStates.Visible) != 0; } set { if (((this.State & DataGridViewElementStates.Visible) != 0) != value) { if (this.DataGridView != null && this.bandIsRow && this.DataGridView.NewRowIndex != -1 && this.DataGridView.NewRowIndex == this.bandIndex && !value) { // the 'new' row cannot be made invisble. throw new InvalidOperationException(SR.GetString(SR.DataGridViewBand_NewRowCannotBeInvisible)); } OnStateChanging(DataGridViewElementStates.Visible); if (value) { this.StateInternal = this.State | DataGridViewElementStates.Visible; } else { this.StateInternal = this.State & ~DataGridViewElementStates.Visible; } OnStateChanged(DataGridViewElementStates.Visible); } } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.Clone"]/*' /> public virtual object Clone() { // SECREVIEW : Late-binding does not represent a security thread, see bug#411899 for more info.. // DataGridViewBand dataGridViewBand = (DataGridViewBand) System.Activator.CreateInstance(this.GetType()); if (dataGridViewBand != null) { CloneInternal(dataGridViewBand); } return dataGridViewBand; } internal void CloneInternal(DataGridViewBand dataGridViewBand) { dataGridViewBand.propertyStore = new PropertyStore(); dataGridViewBand.bandIndex = -1; dataGridViewBand.bandIsRow = this.bandIsRow; if (!this.bandIsRow || this.bandIndex >= 0 || this.DataGridView == null) { dataGridViewBand.StateInternal = this.State & ~(DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed); } dataGridViewBand.thickness = this.Thickness; dataGridViewBand.MinimumThickness = this.MinimumThickness; dataGridViewBand.cachedThickness = this.CachedThickness; dataGridViewBand.DividerThickness = this.DividerThickness; dataGridViewBand.Tag = this.Tag; if (this.HasDefaultCellStyle) { dataGridViewBand.DefaultCellStyle = new DataGridViewCellStyle(this.DefaultCellStyle); } if (this.HasDefaultHeaderCellType) { dataGridViewBand.DefaultHeaderCellType = this.DefaultHeaderCellType; } if (this.ContextMenuStripInternal != null) { dataGridViewBand.ContextMenuStrip = this.ContextMenuStripInternal.Clone(); } } private void DetachContextMenuStrip(object sender, EventArgs e) { this.ContextMenuStripInternal = null; } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.Dispose"]/*' /> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.Dispose2"]/*' /> protected virtual void Dispose(bool disposing) { if (disposing) { ContextMenuStrip contextMenuStrip = (ContextMenuStrip)this.ContextMenuStripInternal; if (contextMenuStrip != null) { contextMenuStrip.Disposed -= new EventHandler(DetachContextMenuStrip); } } } internal void GetHeightInfo(int rowIndex, out int height, out int minimumHeight) { Debug.Assert(this.bandIsRow); if (this.DataGridView != null && (this.DataGridView.VirtualMode || this.DataGridView.DataSource != null) && this.DataGridView.AutoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) { Debug.Assert(rowIndex > -1); DataGridViewRowHeightInfoNeededEventArgs dgvrhine = this.DataGridView.OnRowHeightInfoNeeded(rowIndex, this.thickness, this.minimumThickness); height = dgvrhine.Height; minimumHeight = dgvrhine.MinimumHeight; return; } height = this.thickness; minimumHeight = this.minimumThickness; } internal void OnStateChanged(DataGridViewElementStates elementState) { if (this.DataGridView != null) { // maybe move this code into OnDataGridViewElementStateChanged if (this.bandIsRow) { // we could be smarter about what needs to be invalidated. this.DataGridView.Rows.InvalidateCachedRowCount(elementState); this.DataGridView.Rows.InvalidateCachedRowsHeight(elementState); if (this.bandIndex != -1) { this.DataGridView.OnDataGridViewElementStateChanged(this, -1, elementState); } } else { // we could be smarter about what needs to be invalidated. this.DataGridView.Columns.InvalidateCachedColumnCount(elementState); this.DataGridView.Columns.InvalidateCachedColumnsWidth(elementState); this.DataGridView.OnDataGridViewElementStateChanged(this, -1, elementState); } } } private void OnStateChanging(DataGridViewElementStates elementState) { if (this.DataGridView != null) { if (this.bandIsRow) { if (this.bandIndex != -1) { this.DataGridView.OnDataGridViewElementStateChanging(this, -1, elementState); } } else { this.DataGridView.OnDataGridViewElementStateChanging(this, -1, elementState); } } } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.OnDataGridViewChanged"]/*' /> protected override void OnDataGridViewChanged() { if (this.HasDefaultCellStyle) { if (this.DataGridView == null) { this.DefaultCellStyle.RemoveScope(this.bandIsRow ? DataGridViewCellStyleScopes.Row : DataGridViewCellStyleScopes.Column); } else { this.DefaultCellStyle.AddScope(this.DataGridView, this.bandIsRow ? DataGridViewCellStyleScopes.Row : DataGridViewCellStyleScopes.Column); } } base.OnDataGridViewChanged(); } private bool ShouldSerializeDefaultHeaderCellType() { Type dhct = (Type)this.Properties.GetObject(PropDefaultHeaderCellType); return dhct != null; } // internal because DataGridViewColumn needs to access it internal bool ShouldSerializeResizable() { return (this.State & DataGridViewElementStates.ResizableSet) != 0; } /// <include file='doc\DataGridViewBand.uex' path='docs/doc[@for="DataGridViewBand.ToString"]/*' /> /// <devdoc> /// <para></para> /// </devdoc> public override string ToString() { StringBuilder sb = new StringBuilder(36); sb.Append("DataGridViewBand { Index="); sb.Append(this.Index.ToString(CultureInfo.CurrentCulture)); sb.Append(" }"); return sb.ToString(); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using ManagedBass; namespace osu.Framework.Audio.Track { /// <summary> /// Procsses audio sample data such that it can then be consumed to generate waveform plots of the audio. /// </summary> public class Waveform : IDisposable { /// <summary> /// <see cref="WaveformPoint"/>s are initially generated to a 1ms resolution to cover most use cases. /// </summary> private const float resolution = 0.001f; /// <summary> /// The data stream is iteratively decoded to provide this many points per iteration so as to not exceed BASS's internal buffer size. /// </summary> private const int points_per_iteration = 100000; private const int bytes_per_sample = 4; private int channels; private List<WaveformPoint> points = new List<WaveformPoint>(); private readonly CancellationTokenSource cancelSource = new CancellationTokenSource(); private readonly Task readTask; /// <summary> /// Constructs a new <see cref="Waveform"/> from provided audio data. /// </summary> /// <param name="data">The sample data stream. If null, an empty waveform is constructed.</param> public Waveform(Stream data = null) { if (data == null) return; readTask = Task.Run(() => { var procs = new DataStreamFileProcedures(data); int decodeStream = Bass.CreateStream(StreamSystem.NoBuffer, BassFlags.Decode | BassFlags.Float, procs.BassProcedures, IntPtr.Zero); Bass.ChannelGetInfo(decodeStream, out ChannelInfo info); long length = Bass.ChannelGetLength(decodeStream); // Each "point" is generated from a number of samples, each sample contains a number of channels int sampleDataPerPoint = (int)(info.Frequency * resolution * info.Channels); points.Capacity = (int)(length / sampleDataPerPoint); int bytesPerIteration = sampleDataPerPoint * points_per_iteration; var dataBuffer = new float[bytesPerIteration / bytes_per_sample]; while (length > 0) { length = Bass.ChannelGetData(decodeStream, dataBuffer, bytesPerIteration); int samplesRead = (int)(length / bytes_per_sample); // Process a sequence of samples for each point for (int i = 0; i < samplesRead; i += sampleDataPerPoint) { // Process each sample in the sequence var point = new WaveformPoint(info.Channels); for (int j = i; j < i + sampleDataPerPoint; j += info.Channels) { // Process each channel in the sample for (int c = 0; c < info.Channels; c++) point.Amplitude[c] = Math.Max(point.Amplitude[c], Math.Abs(dataBuffer[j + c])); } for (int c = 0; c < info.Channels; c++) point.Amplitude[c] = Math.Min(1, point.Amplitude[c]); points.Add(point); } } channels = info.Channels; }, cancelSource.Token); } /// <summary> /// Creates a new <see cref="Waveform"/> containing a specific number of data points by selecting the average value of each sampled group. /// </summary> /// <param name="pointCount">The number of points the resulting <see cref="Waveform"/> should contain.</param> /// <param name="cancellationToken">The token to cancel the task.</param> /// <returns>An async task for the generation of the <see cref="Waveform"/>.</returns> public async Task<Waveform> GenerateResampledAsync(int pointCount, CancellationToken cancellationToken = default(CancellationToken)) { if (pointCount < 0) throw new ArgumentOutOfRangeException(nameof(pointCount)); if (readTask == null) return new Waveform(); await readTask; return await Task.Run(() => { var generatedPoints = new List<WaveformPoint>(); float pointsPerGeneratedPoint = (float)points.Count / pointCount; for (float i = 0; i < points.Count; i += pointsPerGeneratedPoint) { int startIndex = (int)i; int endIndex = (int)Math.Min(points.Count, Math.Ceiling(i + pointsPerGeneratedPoint)); var point = new WaveformPoint(channels); for (int j = startIndex; j < endIndex; j++) { for (int c = 0; c < channels; c++) point.Amplitude[c] += points[j].Amplitude[c]; } // Mean for (int c = 0; c < channels; c++) point.Amplitude[c] /= endIndex - startIndex; generatedPoints.Add(point); } return new Waveform { points = generatedPoints, channels = channels }; }, cancellationToken); } /// <summary> /// Gets all the points represented by this <see cref="Waveform"/>. /// </summary> public List<WaveformPoint> GetPoints() => GetPointsAsync().Result; /// <summary> /// Gets all the points represented by this <see cref="Waveform"/>. /// </summary> public async Task<List<WaveformPoint>> GetPointsAsync() { if (readTask == null) return points; await readTask; return points; } /// <summary> /// Gets the number of channels represented by each <see cref="WaveformPoint"/>. /// </summary> public int GetChannels() => GetChannelsAsync().Result; /// <summary> /// Gets the number of channels represented by each <see cref="WaveformPoint"/>. /// </summary> public async Task<int> GetChannelsAsync() { if (readTask == null) return channels; await readTask; return channels; } #region Disposal ~Waveform() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private bool isDisposed; protected virtual void Dispose(bool disposing) { if (isDisposed) return; isDisposed = true; cancelSource?.Cancel(); cancelSource?.Dispose(); points = null; } #endregion } /// <summary> /// Represents a singular point of data in a <see cref="Waveform"/>. /// </summary> public struct WaveformPoint { /// <summary> /// An array of amplitudes, one for each channel. /// </summary> public readonly float[] Amplitude; /// <summary> /// Cconstructs a <see cref="WaveformPoint"/>. /// </summary> /// <param name="channels">The number of channels that contain data.</param> public WaveformPoint(int channels) { Amplitude = new float[channels]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class ConstantNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableBoolConstantTest(bool useInterpreter) { foreach (bool? value in new bool?[] { null, true, false }) { VerifyNullableBoolConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableByteConstantTest(bool useInterpreter) { foreach (byte? value in new byte?[] { null, 0, 1, byte.MaxValue }) { VerifyNullableByteConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableCharConstantTest(bool useInterpreter) { foreach (char? value in new char?[] { null, '\0', '\b', 'A', '\uffff' }) { VerifyNullableCharConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDecimalConstantTest(bool useInterpreter) { foreach (decimal? value in new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }) { VerifyNullableDecimalConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDoubleConstantTest(bool useInterpreter) { foreach (double? value in new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }) { VerifyNullableDoubleConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableEnumConstantTest(bool useInterpreter) { foreach (E? value in new E?[] { null, (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }) { VerifyNullableEnumConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableEnumLongConstantTest(bool useInterpreter) { foreach (El? value in new El?[] { null, (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }) { VerifyNullableEnumLongConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableFloatConstantTest(bool useInterpreter) { foreach (float? value in new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }) { VerifyNullableFloatConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableIntConstantTest(bool useInterpreter) { foreach (int? value in new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }) { VerifyNullableIntConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableLongConstantTest(bool useInterpreter) { foreach (long? value in new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }) { VerifyNullableLongConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableStructConstantTest(bool useInterpreter) { foreach (S? value in new S?[] { null, default(S), new S() }) { VerifyNullableStructConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableSByteConstantTest(bool useInterpreter) { foreach (sbyte? value in new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }) { VerifyNullableSByteConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableStructWithStringConstantTest(bool useInterpreter) { foreach (Sc? value in new Sc?[] { null, default(Sc), new Sc(), new Sc(null) }) { VerifyNullableStructWithStringConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableStructWithStringAndFieldConstantTest(bool useInterpreter) { foreach (Scs? value in new Scs?[] { null, default(Scs), new Scs(), new Scs(null, new S()) }) { VerifyNullableStructWithStringAndFieldConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableShortConstantTest(bool useInterpreter) { foreach (short? value in new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }) { VerifyNullableShortConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableStructWithTwoValuesConstantTest(bool useInterpreter) { foreach (Sp? value in new Sp?[] { null, default(Sp), new Sp(), new Sp(5, 5.0) }) { VerifyNullableStructWithTwoValuesConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableStructWithValueConstantTest(bool useInterpreter) { foreach (Ss? value in new Ss?[] { null, default(Ss), new Ss(), new Ss(new S()) }) { VerifyNullableStructWithValueConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUIntConstantTest(bool useInterpreter) { foreach (uint? value in new uint?[] { null, 0, 1, uint.MaxValue }) { VerifyNullableUIntConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableULongConstantTest(bool useInterpreter) { foreach (ulong? value in new ulong?[] { null, 0, 1, ulong.MaxValue }) { VerifyNullableULongConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUShortConstantTest(bool useInterpreter) { foreach (ushort? value in new ushort?[] { null, 0, 1, ushort.MaxValue }) { VerifyNullableUShortConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableGenericWithStructRestrictionWithEnumConstantTest(bool useInterpreter) { CheckNullableGenericWithStructRestrictionConstantHelper<E>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableGenericWithStructRestrictionWithStructConstantTest(bool useInterpreter) { CheckNullableGenericWithStructRestrictionConstantHelper<S>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableGenericWithStructRestrictionWithStructWithStringAndValueConstantTest(bool useInterpreter) { CheckNullableGenericWithStructRestrictionConstantHelper<Scs>(useInterpreter); } #endregion #region Generic helpers private static void CheckNullableGenericWithStructRestrictionConstantHelper<Ts>(bool useInterpreter) where Ts : struct { foreach (Ts? value in new Ts?[] { null, default(Ts), new Ts() }) { VerifyNullableGenericWithStructRestriction<Ts>(value, useInterpreter); } } #endregion #region Test verifiers private static void VerifyNullableBoolConstant(bool? value, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.Constant(value, typeof(bool?)), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableByteConstant(byte? value, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.Constant(value, typeof(byte?)), Enumerable.Empty<ParameterExpression>()); Func<byte?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableCharConstant(char? value, bool useInterpreter) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.Constant(value, typeof(char?)), Enumerable.Empty<ParameterExpression>()); Func<char?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableDecimalConstant(decimal? value, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Constant(value, typeof(decimal?)), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableDoubleConstant(double? value, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Constant(value, typeof(double?)), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableEnumConstant(E? value, bool useInterpreter) { Expression<Func<E?>> e = Expression.Lambda<Func<E?>>( Expression.Constant(value, typeof(E?)), Enumerable.Empty<ParameterExpression>()); Func<E?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableEnumLongConstant(El? value, bool useInterpreter) { Expression<Func<El?>> e = Expression.Lambda<Func<El?>>( Expression.Constant(value, typeof(El?)), Enumerable.Empty<ParameterExpression>()); Func<El?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableFloatConstant(float? value, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Constant(value, typeof(float?)), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableIntConstant(int? value, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Constant(value, typeof(int?)), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableLongConstant(long? value, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Constant(value, typeof(long?)), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableStructConstant(S? value, bool useInterpreter) { Expression<Func<S?>> e = Expression.Lambda<Func<S?>>( Expression.Constant(value, typeof(S?)), Enumerable.Empty<ParameterExpression>()); Func<S?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableSByteConstant(sbyte? value, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.Constant(value, typeof(sbyte?)), Enumerable.Empty<ParameterExpression>()); Func<sbyte?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableStructWithStringConstant(Sc? value, bool useInterpreter) { Expression<Func<Sc?>> e = Expression.Lambda<Func<Sc?>>( Expression.Constant(value, typeof(Sc?)), Enumerable.Empty<ParameterExpression>()); Func<Sc?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableStructWithStringAndFieldConstant(Scs? value, bool useInterpreter) { Expression<Func<Scs?>> e = Expression.Lambda<Func<Scs?>>( Expression.Constant(value, typeof(Scs?)), Enumerable.Empty<ParameterExpression>()); Func<Scs?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableShortConstant(short? value, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Constant(value, typeof(short?)), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableStructWithTwoValuesConstant(Sp? value, bool useInterpreter) { Expression<Func<Sp?>> e = Expression.Lambda<Func<Sp?>>( Expression.Constant(value, typeof(Sp?)), Enumerable.Empty<ParameterExpression>()); Func<Sp?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableStructWithValueConstant(Ss? value, bool useInterpreter) { Expression<Func<Ss?>> e = Expression.Lambda<Func<Ss?>>( Expression.Constant(value, typeof(Ss?)), Enumerable.Empty<ParameterExpression>()); Func<Ss?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableUIntConstant(uint? value, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Constant(value, typeof(uint?)), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableULongConstant(ulong? value, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Constant(value, typeof(ulong?)), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableUShortConstant(ushort? value, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Constant(value, typeof(ushort?)), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyNullableGenericWithStructRestriction<Ts>(Ts? value, bool useInterpreter) where Ts : struct { Expression<Func<Ts?>> e = Expression.Lambda<Func<Ts?>>( Expression.Constant(value, typeof(Ts?)), Enumerable.Empty<ParameterExpression>()); Func<Ts?> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Simple1C.Impl.Helpers; using Simple1C.Impl.Sql.SqlAccess.Syntax; namespace Simple1C.Impl.Sql.Translation { internal class SqlFormatter : SqlVisitor { private ISqlElement parentOperatorExpression; private readonly StringBuilder builder = new StringBuilder(); public static string Format(ISqlElement element) { var formatter = new SqlFormatter(); formatter.Visit(element); return formatter.builder.ToString(); } public override ISqlElement VisitIsReference(IsReferenceExpression expression) { NotSupported(expression, expression.Argument, expression.ObjectName); return expression; } public override ISqlElement VisitValueLiteral(ValueLiteralExpression expression) { NotSupported(expression, expression.Value); return expression; } public override UnionClause VisitUnion(UnionClause clause) { var result = base.VisitUnion(clause); if (clause.Type.HasValue) { builder.Append("\r\n\r\nunion"); if (clause.Type == UnionType.All) builder.Append(" all"); builder.Append("\r\n\r\n"); } return result; } public override AggregateFunctionExpression VisitAggregateFunction(AggregateFunctionExpression expression) { builder.Append(expression.Function.ToString().ToLower()); builder.Append("("); if (expression.IsSelectAll) builder.Append("*"); else { if (expression.IsDistinct) builder.Append("distinct "); Visit(expression.Argument); } builder.Append(")"); return expression; } public override GroupByClause VisitGroupBy(GroupByClause clause) { builder.Append("\r\ngroup by "); VisitEnumerable(clause.Expressions, ","); return clause; } public override OrderByClause VisitOrderBy(OrderByClause element) { builder.Append("\r\norder by "); VisitEnumerable(element.Expressions, ","); return element; } public override ISqlElement VisitOrderingElement(OrderByClause.OrderingElement orderingElement) { Visit(orderingElement.Expression); builder.AppendFormat(" {0}", orderingElement.IsAsc ? "asc" : "desc"); return orderingElement; } public override SubqueryClause VisitSubquery(SubqueryClause clause) { var previous = parentOperatorExpression; parentOperatorExpression = null; builder.Append("("); Visit(clause.Query); builder.Append(")"); parentOperatorExpression = previous; return clause; } public override SubqueryTable VisitSubqueryTable(SubqueryTable subqueryTable) { Visit(subqueryTable.Query); if (string.IsNullOrWhiteSpace(subqueryTable.Alias)) { var message = string.Format("Subquery must have an alias but did not: [{0}]", subqueryTable); throw new InvalidOperationException(message); } builder.AppendFormat(" as {0}", subqueryTable.Alias); return subqueryTable; } public override SelectClause VisitSelect(SelectClause clause) { builder.Append("select"); if (clause.IsDistinct) builder.AppendFormat(" distinct"); builder.Append("\r\n\t"); if (clause.IsSelectAll) builder.Append("*"); else VisitEnumerable(clause.Fields, ",\r\n\t"); builder.Append("\r\nfrom "); Visit(clause.Source); if (clause.JoinClauses.Count > 0) { builder.Append("\r\n"); VisitEnumerable(clause.JoinClauses, "\r\n"); } if (clause.WhereExpression != null) { builder.Append("\r\nwhere "); Visit(clause.WhereExpression); } if (clause.GroupBy != null) Visit(clause.GroupBy); if (clause.Having != null) { builder.Append("\r\nhaving "); Visit(clause.Having); } if (clause.Top.HasValue) builder.AppendFormat("\r\nlimit {0}", clause.Top.Value); return clause; } public override SelectFieldExpression VisitSelectField(SelectFieldExpression clause) { Visit(clause.Expression); WriteAlias(clause.Alias); return clause; } public override CaseExpression VisitCase(CaseExpression expression) { builder.Append("case"); foreach (var e in expression.Elements) { builder.Append("\r\n\t"); builder.Append("when "); Visit(e.Condition); builder.Append(" then "); Visit(e.Value); } if (expression.DefaultValue != null) { builder.Append("\r\n\t"); builder.Append("else "); Visit(expression.DefaultValue); } builder.Append("\r\nend"); return expression; } public override ISqlElement VisitUnary(UnaryExpression unaryExpression) { var needParens = NeedParens(unaryExpression); var previous = parentOperatorExpression; parentOperatorExpression = unaryExpression; builder.Append(needParens ? "(" : " "); if (unaryExpression.Operator == UnaryOperator.Not) builder.Append("not "); else if (unaryExpression.Operator == UnaryOperator.Negation) builder.Append("-"); else { const string messageFormat = "unexpected unary operator type [{0}]"; throw new InvalidOperationException(string.Format(messageFormat, unaryExpression.Operator)); } Visit(unaryExpression.Argument); if (needParens) builder.Append(")"); parentOperatorExpression = previous; return unaryExpression; } public override ISqlElement VisitBinary(BinaryExpression expression) { var needParens = NeedParens(expression); var previous = parentOperatorExpression; parentOperatorExpression = expression; if (needParens) builder.Append("("); Visit(expression.Left); builder.AppendFormat(" {0} ", GetOperatorText(expression.Operator)); Visit(expression.Right); if (needParens) builder.Append(")"); parentOperatorExpression = previous; return expression; } public override ISqlElement VisitColumnReference(ColumnReferenceExpression expression) { var alias = expression.Table.Alias; if (!string.IsNullOrEmpty(alias)) { builder.Append(alias); builder.Append("."); } builder.Append(expression.Name); return expression; } public override ISqlElement VisitTableDeclaration(TableDeclarationClause clause) { builder.Append(clause.Name); WriteAlias(clause.Alias); return clause; } public override ISqlElement VisitIn(InExpression expression) { Visit(expression.Column); builder.Append(" in "); Visit(expression.Source); return expression; } public override JoinClause VisitJoin(JoinClause clause) { builder.Append(GetJoinKindString(clause)); builder.Append(" join "); Visit(clause.Source); builder.Append(" on "); Visit(clause.Condition); return clause; } public override ISqlElement VisitParameter(ParameterExpression expression) { builder.Append("@"); builder.Append(expression.Name); return expression; } public override ISqlElement VisitLiteral(LiteralExpression expression) { var value = expression.SqlType.HasValue ? ApplySqlType(expression.Value, expression.SqlType.Value) : expression.Value; builder.Append(FormatValueAsString(value)); return expression; } public override ISqlElement VisitQueryFunction(QueryFunctionExpression expression) { var functionName = expression.KnownFunction.HasValue ? FormatQueryFunctionName(expression.KnownFunction.Value) : expression.CustomFunction; builder.Append(functionName); builder.Append('('); VisitEnumerable(expression.Arguments, ", "); builder.Append(')'); return expression; } public override ISqlElement VisitList(ListExpression listExpression) { builder.Append('('); VisitEnumerable(listExpression.Elements, ", "); builder.Append(')'); return listExpression; } private static string FormatQueryFunctionName(KnownQueryFunction name) { switch (name) { case KnownQueryFunction.SqlDatePart: return "date_part"; case KnownQueryFunction.SqlDateTrunc: return "date_trunc"; case KnownQueryFunction.SqlNot: return "not"; case KnownQueryFunction.Substring: return "substring"; default: throw new InvalidOperationException(string.Format("unexpected function [{0}]", name)); } } public override ISqlElement VisitIsNullExpression(IsNullExpression expression) { Visit(expression.Argument); builder.Append(" is "); if (expression.IsNotNull) builder.Append("not "); builder.Append("null"); return expression; } public override ISqlElement VisitCast(CastExpression castExpression) { builder.Append("cast("); Visit(castExpression.Expression); builder.AppendFormat(" as {0})", castExpression.Type); return castExpression; } private static void NotSupported(ISqlElement element, params object[] args) { const string messageFormat = "element [{0}] can't be turned to sql, " + "must be rewritten to something else first"; var argsString = args.JoinStrings(","); throw new InvalidOperationException(string.Format(messageFormat, element.GetType().FormatName() + (argsString == "" ? "" : ":" + argsString))); } private static string GetOperatorText(SqlBinaryOperator op) { switch (op) { case SqlBinaryOperator.Eq: return "="; case SqlBinaryOperator.Neq: return "<>"; case SqlBinaryOperator.And: return "and"; case SqlBinaryOperator.Or: return "or"; case SqlBinaryOperator.LessThan: return "<"; case SqlBinaryOperator.LessThanOrEqual: return "<="; case SqlBinaryOperator.GreaterThan: return ">"; case SqlBinaryOperator.GreaterThanOrEqual: return ">="; case SqlBinaryOperator.Plus: return "+"; case SqlBinaryOperator.Minus: return "-"; case SqlBinaryOperator.Mult: return "*"; case SqlBinaryOperator.Div: return "/"; case SqlBinaryOperator.Remainder: return "%"; case SqlBinaryOperator.Like: return "like"; default: throw new ArgumentOutOfRangeException("op", op, null); } } private static string FormatValueAsString(object value) { var str = value as string; if (str != null) return "'" + str.Replace("\'", "\'\'") + "'"; var bytes = value as byte[]; if (bytes != null) return "E'\\\\x" + bytes.ToHex() + "'"; if (value is bool) return ((bool?) value).Value ? "true" : "false"; return value == null ? "null" : value.ToString(); } private static object ApplySqlType(object value, SqlType sqlType) { switch (sqlType) { case SqlType.ByteArray: var b = value as byte?; if (b.HasValue) return new[] {b.Value}; var i = value as int?; if (i.HasValue) return BitConverter.GetBytes(i.Value).Reverse().ToArray(); const string messageFormat = "can't convert value [{0}] of type [{1}] to [{2}]"; throw new InvalidOperationException(string.Format(messageFormat, value, value == null ? "<null>" : value.GetType().FormatName(), sqlType)); case SqlType.DatePart: return value.ToString(); default: const string message = "unexpected value [{0}] of SqlType"; throw new InvalidOperationException(string.Format(message, sqlType)); } } private static string GetJoinKindString(JoinClause joinClause) { switch (joinClause.JoinKind) { case JoinKind.Left: return "left"; case JoinKind.Right: return "right"; case JoinKind.Inner: return "inner"; case JoinKind.Full: return "full outer"; default: throw new InvalidOperationException(string.Format("unexpected join kind [{0}]", joinClause.JoinKind)); } } private void WriteAlias(string alias) { if (!string.IsNullOrEmpty(alias)) { builder.Append(" as "); builder.Append(alias); } } private void VisitEnumerable(IEnumerable<ISqlElement> elements, string delimiter) { var isFirst = true; foreach (var e in elements) { if (isFirst) isFirst = false; else builder.Append(delimiter); Visit(e); } } private bool NeedParens(ISqlElement current) { return GetOperatorPrecedence(parentOperatorExpression) > GetOperatorPrecedence(current); } private static int? GetOperatorPrecedence(ISqlElement element) { var binaryExpression = element as BinaryExpression; if (binaryExpression != null) return GetPrecedence(binaryExpression.Operator); var unaryExpression = element as UnaryExpression; if (unaryExpression != null) return GetPrecedence(unaryExpression.Operator); return null; } private static int GetPrecedence<TOp>(TOp op) where TOp : struct { var attribute = EnumAttributesCache<OperatorPrecedenceAttribute>.GetAttribute(op); return attribute.Precedence; } } }
// Copyright 2020 The Tilt Brush Authors // // 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 Newtonsoft.Json; using System.Collections.Generic; using System; using System.IO; using System.Linq; using UnityEngine; namespace TiltBrush { public static class ExportRaw { public static bool Export(string outputFile) { var tempName = outputFile + "_part"; try { using (var textWriter = new StreamWriter(tempName)) using (var json = new JsonTextWriter(textWriter)) { json.Formatting = Formatting.Indented; json.WriteStartObject(); Dictionary<Guid, int> brushMap; WriteStrokes(json, out brushMap); WriteBrushes(json, brushMap); json.WriteEndObject(); } DestroyFile(outputFile); Directory.Move(tempName, outputFile); return true; } catch (IOException e) { Debug.LogException(e); return false; } } static void DestroyFile(string path) { if (File.Exists(path)) { File.SetAttributes(path, FileAttributes.Normal); File.Delete(path); } } static void WriteBrushes(JsonWriter json, Dictionary<Guid, int> brushMap) { var brushList = new BrushDescriptor[brushMap.Count]; foreach (var pair in brushMap) { brushList[pair.Value] = BrushCatalog.m_Instance.GetBrush(pair.Key); } json.WritePropertyName("brushes"); json.WriteStartArray(); for (int i = 0; i < brushList.Length; ++i) { WriteBrush(json, brushList[i]); } json.WriteEnd(); } static void WriteBrush(JsonWriter json, BrushDescriptor brush) { json.WriteStartObject(); json.WritePropertyName("name"); json.WriteValue(brush.name); json.WritePropertyName("guid"); json.WriteValue(brush.m_Guid.ToString("D")); json.WriteEndObject(); } static void WriteStrokes(JsonWriter json, out Dictionary<Guid, int> brushMap) { brushMap = new Dictionary<Guid, int>(); json.WritePropertyName("strokes"); json.WriteStartArray(); var strokes = SketchMemoryScript.AllStrokes().ToList(); for (int i = 0; i < strokes.Count; ++i) { if (strokes[i].IsGeometryEnabled) { WriteStroke(json, strokes[i], brushMap); } } json.WriteEnd(); } static void WriteStroke(JsonWriter json, Stroke stroke, Dictionary<Guid, int> brushMap) { json.WriteStartObject(); var brushGuid = stroke.m_BrushGuid; BrushDescriptor desc = BrushCatalog.m_Instance.GetBrush(brushGuid); int brushIndex; if (!brushMap.TryGetValue(brushGuid, out brushIndex)) { brushIndex = brushMap.Count; brushMap[brushGuid] = brushIndex; } json.WritePropertyName("brush"); json.WriteValue(brushIndex); if (stroke.m_Type == Stroke.Type.BrushStroke) { // Some strokes (eg particles) don't have meshes. For now, assume that // if the stroke has a mesh, it should be written. var meshFilter = stroke.m_Object.GetComponent<MeshFilter>(); if (meshFilter != null) { var mesh = meshFilter.sharedMesh; if (mesh != null) { WriteMesh(json, mesh, desc.VertexLayout); } } } else if (stroke.m_Type == Stroke.Type.BatchedBrushStroke) { BatchSubset subset = stroke.m_BatchSubset; GeometryPool geom = subset.m_ParentBatch.Geometry; Mesh tempMesh = new Mesh(); geom.CopyToMesh(tempMesh, subset.m_StartVertIndex, subset.m_VertLength, subset.m_iTriIndex, subset.m_nTriIndex); WriteMesh(json, tempMesh, geom.Layout); tempMesh.Clear(); UnityEngine.Object.Destroy(tempMesh); } json.WriteEndObject(); } static void WriteMesh(JsonWriter json, Mesh mesh, GeometryPool.VertexLayout layout) { // Unity does not import .obj verbatim. It makes these changes: // - flip x axis // - reverse winding of triangles // We undo these changes when exporting to obj. // NOTE: It's currently unknown whether this also happens for fbx files. int nVert = mesh.vertexCount; WriteArray(json, "v", AsByte(mesh.vertices, nVert, flip: true)); if (layout.bUseNormals) { WriteArray(json, "n", AsByte(mesh.normals, nVert, flip: true)); } WriteUvChannel(json, 0, layout.texcoord0.size, mesh, nVert); WriteUvChannel(json, 1, layout.texcoord1.size, mesh, nVert); if (layout.bUseColors) { WriteArray(json, "c", AsByte(mesh.colors32, nVert)); } // NOTE(b/30710462): Bubble wand lies about its tangents, so check they are really there if (layout.bUseTangents && mesh.tangents.Length > 0) { WriteArray(json, "t", AsByte(mesh.tangents, nVert, flip: true)); } var tris = mesh.GetTriangles(0); // Reverse winding, per above for (int i = 0; i < tris.Length; i += 3) { var tmp = tris[i+1]; tris[i+1] = tris[i+2]; tris[i+2] = tmp; } WriteArray(json, "tri", AsByte(tris, tris.Length)); } static void WriteUvChannel(JsonWriter json, int channel, int numComponents, Mesh mesh, int n) { if (numComponents == 0 || n == 0) { return; } var name = string.Format("uv{0}", channel); switch (numComponents) { case 2: { var uv = new List<Vector2>(); mesh.GetUVs(channel, uv); WriteArray(json, name, AsByte(uv.GetBackingArray(), n)); break; } case 3: { var uv = new List<Vector3>(); mesh.GetUVs(channel, uv); WriteArray(json, name, AsByte(uv.GetBackingArray(), n)); break; } case 4: { var uv = new List<Vector4>(); mesh.GetUVs(channel, uv); WriteArray(json, name, AsByte(uv.GetBackingArray(), n)); break; } default: throw new ArgumentException("numComponents"); } } static void WriteArray(JsonWriter json, string name, byte[] buf) { if (buf == null || buf.Length == 0) { return; } json.WritePropertyName(name); json.WriteValue(buf); } // Unfortunately, C# generics won't work here -- the compiler and // the runtime conservatively assume that the generic type isn't POD. static unsafe byte[] AsByte(Color32[] a, int n) { if (n == 0) { return null; } fixed (Color32* p = a) { int eltSize = (int)((byte*)&p[1] - (byte*)&p[0]); byte[] buf = new byte[n * eltSize]; System.Runtime.InteropServices.Marshal.Copy( (IntPtr)p, buf, 0, buf.Length); return buf; } } static unsafe byte[] AsByte(int[] a, int n) { if (n == 0) { return null; } fixed (int* p = a) { int eltSize = (int)((byte*)&p[1] - (byte*)&p[0]); byte[] buf = new byte[n * eltSize]; System.Runtime.InteropServices.Marshal.Copy( (IntPtr)p, buf, 0, buf.Length); return buf; } } static unsafe byte[] AsByte(Vector2[] a, int n) { if (n == 0) { return null; } fixed (Vector2* p = a) { int eltSize = (int)((byte*)&p[1] - (byte*)&p[0]); byte[] buf = new byte[n * eltSize]; System.Runtime.InteropServices.Marshal.Copy( (IntPtr)p, buf, 0, buf.Length); return buf; } } // "flip" changes the VectorN from left-handed to right-handed coordinates. // Note that flipping "x" is _not_ arbitrary -- it mirrors (no pun intended) // the conversion Unity applies when importing right-handed file formats // like .obj. static unsafe byte[] AsByte(Vector3[] a, int n, bool flip=false) { if (n == 0) { return null; } fixed (Vector3* p = a) { int eltSize = (int)((byte*)&p[1] - (byte*)&p[0]); byte[] buf = new byte[n * eltSize]; System.Runtime.InteropServices.Marshal.Copy( (IntPtr)p, buf, 0, buf.Length); if (flip) { // Flip the sign bit of the first float (x) in each element. for (int i = 3; i < buf.Length; i += eltSize) { buf[i] ^= 0x80; } } return buf; } } static unsafe byte[] AsByte(Vector4[] a, int n, bool flip=false) { if (n == 0) { return null; } fixed (Vector4* p = a) { int eltSize = (int)((byte*)&p[1] - (byte*)&p[0]); byte[] buf = new byte[n * eltSize]; System.Runtime.InteropServices.Marshal.Copy( (IntPtr)p, buf, 0, buf.Length); if (flip) { // Flip the sign bit of the first float (x) in each element. for (int i = 3; i < buf.Length; i += eltSize) { buf[i] ^= 0x80; } } return buf; } } } } // namespace TiltBrush
// 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.CompilerServices; using System.Threading; using Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem { /// <summary> /// A hash table which is lock free for readers and up to 1 writer at a time. /// It must be possible to compute the key's hashcode from a value. /// All values must be reference types. /// It must be possible to perform an equality check between a key and a value. /// It must be possible to perform an equality check between a value and a value. /// A LockFreeReaderKeyValueComparer must be provided to perform these operations. /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> abstract public class LockFreeReaderHashtable<TKey, TValue> where TValue : class { private const int _fillPercentageBeforeResize = 60; /// <summary> /// _hashtable is the currently visible underlying array for the hashtable /// Any modifications to this array must be additive only, and there must /// never be a situation where the visible _hashtable has less data than /// it did at an earlier time. This value is initialized to an array of size /// 1. (That array is never mutated as any additions will trigger an Expand /// operation, but we don't use an empty array as the /// initial step, as this approach allows the TryGetValue logic to always /// succeed without needing any length or null checks.) /// </summary> private TValue[] _hashtable = s_hashtableInitialArray; private static TValue[] s_hashtableInitialArray = new TValue[1]; /// <summary> /// _count represents the current count of elements in the hashtable /// _count is used in combination with _resizeCount to control when the /// hashtable should expand /// </summary> private int _count = 0; /// <summary> /// _resizeCount represents the size at which the hashtable should resize. /// </summary> private int _resizeCount = 0; /// <summary> /// Get the underlying array for the hashtable at this time. Implemented with /// MethodImplOptions.NoInlining to prohibit compiler optimizations that allow /// multiple reads from the _hashtable field when there is only one specified /// read without requiring the use of the volatile specifier which requires /// a more significant read barrier. Used by readers so that a reader thread /// looks at a consistent hashtable underlying array throughout the lifetime /// of a single read operation. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private TValue[] GetCurrentHashtable() { return _hashtable; } /// <summary> /// Set the newly visible hashtable underlying array. Used by writers after /// the new array is fully constructed. The volatile write is used to ensure /// that all writes to the contents of hashtable are completed before _hashtable /// is visible to readers. /// </summary> private void SetCurrentHashtable(TValue[] hashtable) { Volatile.Write(ref _hashtable, hashtable); } /// <summary> /// Used to ensure that the hashtable can function with /// fairly poor initial hash codes. /// </summary> /// <param name="key"></param> /// <returns></returns> public static int HashInt1(int key) { unchecked { int a = (int)0x9e3779b9 + key; int b = (int)0x9e3779b9; int c = 16777619; a -= b; a -= c; a ^= (c >> 13); b -= c; b -= a; b ^= (a << 8); c -= a; c -= b; c ^= (b >> 13); a -= b; a -= c; a ^= (c >> 12); b -= c; b -= a; b ^= (a << 16); c -= a; c -= b; c ^= (b >> 5); a -= b; a -= c; a ^= (c >> 3); b -= c; b -= a; b ^= (a << 10); c -= a; c -= b; c ^= (b >> 15); return c; } } /// <summary> /// Generate a somewhat independent hash value from another integer. This is used /// as part of a double hashing scheme. By being relatively prime with powers of 2 /// this hash function can be reliably used as part of a double hashing scheme as it /// is garaunteed to eventually probe every slot in the table. (Table sizes are /// constrained to be a power of two) /// </summary> public static int HashInt2(int key) { unchecked { int hash = unchecked((int)0xB1635D64) + key; hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); hash |= 0x00000001; // To make sure that this is relatively prime with power of 2 return hash; } } /// <summary> /// Create the LockFreeReaderHashtable. This hash table is designed for GetOrCreateValue /// to be a generally lock free api (unless an add is necessary) /// </summary> public LockFreeReaderHashtable() { } /// <summary> /// The current count of elements in the hashtable /// </summary> public int Count { get { return _count; } } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key of the value to get.</param> /// <param name="value">When this method returns, contains the value associated with /// the specified key, if the key is found; otherwise, the default value for the type /// of the value parameter. This parameter is passed uninitialized. This function is threadsafe, /// and wait-free</param> /// <returns>true if a value was found</returns> public bool TryGetValue(TKey key, out TValue value) { TValue[] hashTableLocal = GetCurrentHashtable(); Debug.Assert(hashTableLocal.Length > 0); int mask = hashTableLocal.Length - 1; int hashCode = GetKeyHashCode(key); int tableIndex = HashInt1(hashCode) & mask; if (hashTableLocal[tableIndex] == null) { value = null; return false; } if (CompareKeyToValue(key, hashTableLocal[tableIndex])) { value = hashTableLocal[tableIndex]; return true; } int hash2 = HashInt2(hashCode); tableIndex = (tableIndex + hash2) & mask; while (hashTableLocal[tableIndex] != null) { if (CompareKeyToValue(key, hashTableLocal[tableIndex])) { value = hashTableLocal[tableIndex]; return true; } tableIndex = (tableIndex + hash2) & mask; } value = null; return false; } /// <summary> /// Make the underlying array of the hashtable bigger. This function /// does not change the contents of the hashtable. /// </summary> private void Expand() { int newSize = checked(_hashtable.Length * 2); // The hashtable only functions well when it has a certain minimum size if (newSize < 16) newSize = 16; TValue[] hashTableLocal = new TValue[newSize]; int mask = hashTableLocal.Length - 1; foreach (TValue value in _hashtable) { if (value == null) continue; int hashCode = GetValueHashCode(value); int tableIndex = HashInt1(hashCode) & mask; // Initial probe into hashtable found empty spot if (hashTableLocal[tableIndex] == null) { // Add to hash hashTableLocal[tableIndex] = value; continue; } int hash2 = HashInt2(hashCode); tableIndex = (tableIndex + hash2) & mask; while (hashTableLocal[tableIndex] != null) { tableIndex = (tableIndex + hash2) & mask; } // We've probed to find an empty spot // Add to hash hashTableLocal[tableIndex] = value; } _resizeCount = checked((newSize * _fillPercentageBeforeResize) / 100); SetCurrentHashtable(hashTableLocal); } /// <summary> /// Add a value to the hashtable, or find a value which is already present in the hashtable. /// Note that the key is not specified as it is implicit in the value. This function is thread-safe /// through the use of locking. /// </summary> /// <param name="value">Value to attempt to add to the hashtable, must not be null</param> /// <returns>newly added value, or a value which was already present in the hashtable which is equal to it.</returns> public TValue AddOrGetExisting(TValue value) { if (value == null) throw new ArgumentNullException(); #if !TYPE_SYSTEM_SINGLE_THREADED lock (this) #endif { // Check to see if adding this value may require a resize. If so, expand // the table now. if (_count >= _resizeCount) { Expand(); Debug.Assert(_count < _resizeCount); } TValue[] hashTableLocal = _hashtable; int mask = hashTableLocal.Length - 1; int hashCode = GetValueHashCode(value); int tableIndex = HashInt1(hashCode) & mask; // Initial probe into hashtable found empty spot if (hashTableLocal[tableIndex] == null) { // Add to hash, use a volatile write to ensure that // the contents of the value are fully published to all // threads before adding to the hashtable Volatile.Write(ref hashTableLocal[tableIndex], value); _count++; return value; } if (CompareValueToValue(value, hashTableLocal[tableIndex])) { // Value is already present in hash, do not add return hashTableLocal[tableIndex]; } int hash2 = HashInt2(hashCode); tableIndex = (tableIndex + hash2) & mask; while (hashTableLocal[tableIndex] != null) { if (CompareValueToValue(value, hashTableLocal[tableIndex])) { // Value is already present in hash, do not add return hashTableLocal[tableIndex]; } tableIndex = (tableIndex + hash2) & mask; } // We've probed to find an empty spot // Add to hash, use a volatile write to ensure that // the contents of the value are fully published to all // threads before adding to the hashtable Volatile.Write(ref hashTableLocal[tableIndex], value); _count++; return value; } } [MethodImpl(MethodImplOptions.NoInlining)] private TValue CreateValueAndEnsureValueIsInTable(TKey key) { TValue newValue = CreateValueFromKey(key); Debug.Assert(GetValueHashCode(newValue) == GetKeyHashCode(key)); return AddOrGetExisting(newValue); } /// <summary> /// Get the value associated with a key. If value is not present in dictionary, use the creator delegate passed in /// at object construction time to create the value, and attempt to add it to the table. (Create the value while not /// under the lock, but add it to the table while under the lock. This may result in a throw away object being constructed) /// This function is thread-safe, but will take a lock to perform its operations. /// </summary> /// <param name="key"></param> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public TValue GetOrCreateValue(TKey key) { TValue existingValue; if (TryGetValue(key, out existingValue)) return existingValue; return CreateValueAndEnsureValueIsInTable(key); } /// <summary> /// Determine if this collection contains a value associated with a key. This function is thread-safe, and wait-free. /// </summary> public bool Contains(TKey key) { TValue dummyExistingValue; return TryGetValue(key, out dummyExistingValue); } /// <summary> /// Determine if this collection contains a given value, and returns the value in the hashtable if found. This function is thread-safe, and wait-free. /// </summary> /// <param name="value">Value to search for in the hashtable, must not be null</param> /// <returns>Value from the hashtable if found, otherwise null.</returns> public TValue GetValueIfExists(TValue value) { if (value == null) throw new ArgumentNullException(); TValue[] hashTableLocal = GetCurrentHashtable(); Debug.Assert(hashTableLocal.Length > 0); int mask = hashTableLocal.Length - 1; int hashCode = GetValueHashCode(value); int tableIndex = HashInt1(hashCode) & mask; if (hashTableLocal[tableIndex] == null) return null; if (CompareValueToValue(value, hashTableLocal[tableIndex])) return hashTableLocal[tableIndex]; int hash2 = HashInt2(hashCode); tableIndex = (tableIndex + hash2) & mask; while (hashTableLocal[tableIndex] != null) { if (CompareValueToValue(value, hashTableLocal[tableIndex])) return hashTableLocal[tableIndex]; tableIndex = (tableIndex + hash2) & mask; } return null; } /// <summary> /// Enumerator type for the LockFreeReaderHashtable /// This is threadsafe, but is not garaunteed to avoid torn state. /// In particular, the enumerator may report some newly added values /// but not others. All values in the hashtable as of enumerator /// creation will always be enumerated. /// </summary> public struct Enumerator { private TValue[] _hashtableContentsToEnumerate; private int _index; private TValue _current; /// <summary> /// Use this to get an enumerable collection from a LockFreeReaderHashtable. /// Used instead of a GetEnumerator method on the LockFreeReaderHashtable to /// reduce excess type creation. (By moving the method here, the generic dictionary for /// LockFreeReaderHashtable does not need to contain a reference to the /// enumerator type. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Enumerator Get(LockFreeReaderHashtable<TKey, TValue> hashtable) { return new Enumerator(hashtable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Enumerator GetEnumerator() { return this; } internal Enumerator(LockFreeReaderHashtable<TKey, TValue> hashtable) { _hashtableContentsToEnumerate = hashtable._hashtable; _index = 0; _current = default(TValue); } public bool MoveNext() { if ((_hashtableContentsToEnumerate != null) && (_index < _hashtableContentsToEnumerate.Length)) { for (; _index < _hashtableContentsToEnumerate.Length; _index++) { if (_hashtableContentsToEnumerate[_index] != null) { _current = _hashtableContentsToEnumerate[_index]; _index++; return true; } } } _current = default(TValue); return false; } public TValue Current { get { return _current; } } } /// <summary> /// Given a key, compute a hash code. This function must be thread safe. /// </summary> protected abstract int GetKeyHashCode(TKey key); /// <summary> /// Given a value, compute a hash code which would be identical to the hash code /// for a key which should look up this value. This function must be thread safe. /// </summary> protected abstract int GetValueHashCode(TValue value); /// <summary> /// Compare a key and value. If the key refers to this value, return true. /// This function must be thread safe. /// </summary> protected abstract bool CompareKeyToValue(TKey key, TValue value); /// <summary> /// Compare a value with another value. Return true if values are equal. /// This function must be thread safe. /// </summary> protected abstract bool CompareValueToValue(TValue value1, TValue value2); /// <summary> /// Create a new value from a key. Must be threadsafe. Value may or may not be added /// to collection. Return value must not be null. /// </summary> protected abstract TValue CreateValueFromKey(TKey key); } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- // The "Object Inspector" is a useful little window for browsing and editing SimObject // hierarchies. Be aware that there is no undo in the inspector. //--------------------------------------------------------------------------------------------- /// Bring up a new inspector window on the given object. function inspectObject( %object ) { if( !isObject( %object ) ) { error( "inspectObject: no object '" @ %object @ "'" ); return; } // Create a new object inspector window. exec( "./guiObjectInspector.ed.gui" ); if( !isObject( %guiContent) ) { error( "InspectObject: failed to create GUI from 'guiObjectInspector.ed.gui'" ); return; } // Initialize the inspector. %guiContent.init( %object ); Canvas.getContent().add( %guiContent ); } //============================================================================================= // GuiObjectInspector //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiObjectInspector::init( %this, %object ) { if( !%object.isMemberOfClass( "SimSet" ) ) { // Complete deletely the splitter and the left-side part of the inspector // leaving only the field inspector. %this.add( %this-->panel2 ); %this-->splitter.delete(); %this-->inspector.inspect( %object ); %this-->methodList.init( %object ); } else { %treeView = %this-->treeView; %treeView.inspectorCtrl = %this-->inspector; %treeView.methodList = %this-->methodList; %treeView.open( %object ); } // Set window caption. %caption = "Object Inspector - " @ %object.getId() @ " : " @ %object.getClassName(); %name = %object.getName(); if( %name !$= "" ) %caption = %caption @ " - " @ %name; %this.text = %caption; } //--------------------------------------------------------------------------------------------- function GuiObjectInspector::onClose( %this ) { // Delete us. %this.schedule( 1, "delete" ); } //============================================================================================= // GuiObjectInspectorTree //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiObjectInspectorTree::onSelect( %this, %object ) { if( isObject( %object ) ) { %this.inspectorCtrl.inspect( %object ); %this.methodList.init( %object ); } } //--------------------------------------------------------------------------------------------- function GuiObjectInspectorTree::onRightMouseUp( %this, %itemId, %mousePos, %object ) { if( !isObject( GuiObjectInspectorTreePopup ) ) new PopupMenu( GuiObjectInspectorTreePopup ) { superClass = "MenuBuilder"; isPopup = true; item[ 0 ] = "Jump to Definition in Torsion" TAB "" TAB "EditorOpenDeclarationInTorsion( %this.object );"; object = ""; }; GuiObjectInspectorTreePopup.object = %object; GuiObjectInspectorTreePopup.showPopup( Canvas ); } //============================================================================================= // GuiObjectInspectorMethodList //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiObjectInspectorMethodList::init( %this, %object ) { %this.clear(); %methods = %object.dumpMethods(); %count = %methods.count(); %methodsGroup = %this.insertItem( 0, "Methods" ); %parentScripted = %this.insertItem( %methodsGroup, "Scripted" ); %parentNative = %this.insertItem( %methodsGroup, "Native" ); for( %i = 0; %i < %count; %i ++ ) { %name = %methods.getKey( %i ); %value = %methods.getValue( %i ); %prototype = getRecord( %value, 2 ); %fileName = getRecord( %value, 3 ); %lineNumber = getRecord( %value, 4 ); %usage = getRecords( %value, 5 ); %tooltip = %prototype; if( isFile( %fileName ) ) { %parent = %parentScripted; %tooltip = %tooltip NL "Declared in: " @ %fileName @ ":" @ %lineNumber; } else %parent = %parentNative; %tooltip = %tooltip @ "\n\n" @ %usage; %id = %this.insertItem( %parent, %prototype, %fileName NL %lineNumber ); %this.setItemTooltip( %id, %tooltip ); } %methods.delete(); if( %object.isMethod( "getDebugInfo" ) ) { %debugInfo = %object.getDebugInfo(); %count = %debugInfo.count(); %parent = %this.insertItem( 0, "Debug Info" ); for( %i = 0; %i < %count; %i ++ ) %id = %this.insertItem( %parent, %debugInfo.getKey( %i ) @ ": " @ %debugInfo.getValue( %i ) ); %debugInfo.delete(); } %this.sort( 0, true ); } //--------------------------------------------------------------------------------------------- function GuiObjectInspectorMethodList::onRightMouseUp( %this, %item, %mousePos ) { %value = %this.getItemValue( %item ); if( %value $= "" ) return; %fileName = getRecord( %value, 0 ); %lineNumber = getRecord( %value, 1 ); if( isFile( %fileName ) ) { if( !isObject( GuiInspectorMethodListPopup ) ) new PopupMenu( GuiInspectorMethodListPopup ) { superClass = "MenuBuilder"; isPopup = true; item[ 0 ] = "Jump to Definition in Torsion" TAB "" TAB "EditorOpenFileInTorsion( %this.jumpFileName, %this.jumpLineNumber );"; jumpFileName = ""; jumpLineNumber = ""; }; GuiInspectorMethodListPopup.jumpFileName = %fileName; GuiInspectorMethodListPopup.jumpLineNumber = %lineNumber; GuiInspectorMethodListPopup.showPopup( Canvas ); } } //============================================================================================= // GuiObjectInspectorTreeFilter //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiObjectInspectorTreeFilter::onWake( %this ) { %treeView = %this.getParent()-->TreeView; if( isObject( %treeView ) ) %this.treeView = %treeView; Parent::onWake( %this ); } //============================================================================================= // GuiObjectInspectorTreeFilter //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiObjectInspectorTreeFilterClearButton::onWake( %this ) { %filterText = %this.getParent()-->FilterText; if( isObject( %filterText ) ) %this.textCtrl = %filterText; }
// 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.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.ExceptionServices; using System.Threading; namespace System.Reflection { // Helper class to handle the IL EMIT for the generation of proxies. // Much of this code was taken directly from the Silverlight proxy generation. // Differences between this and the Silverlight version are: // 1. This version is based on DispatchProxy from NET Native and CoreCLR, not RealProxy in Silverlight ServiceModel. // There are several notable differences between them. // 2. Both DispatchProxy and RealProxy permit the caller to ask for a proxy specifying a pair of types: // the interface type to implement, and a base type. But they behave slightly differently: // - RealProxy generates a proxy type that derives from Object and *implements" all the base type's // interfaces plus all the interface type's interfaces. // - DispatchProxy generates a proxy type that *derives* from the base type and implements all // the interface type's interfaces. This is true for both the CLR version in NET Native and this // version for CoreCLR. // 3. DispatchProxy and RealProxy use different type hierarchies for the generated proxies: // - RealProxy type hierarchy is: // proxyType : proxyBaseType : object // Presumably the 'proxyBaseType' in the middle is to allow it to implement the base type's interfaces // explicitly, preventing collision for same name methods on the base and interface types. // - DispatchProxy hierarchy is: // proxyType : baseType (where baseType : DispatchProxy) // The generated DispatchProxy proxy type does not need to generate implementation methods // for the base type's interfaces, because the base type already must have implemented them. // 4. RealProxy required a proxy instance to hold a backpointer to the RealProxy instance to mirror // the .Net Remoting design that required the proxy and RealProxy to be separate instances. // But the DispatchProxy design encourages the proxy type to *be* an DispatchProxy. Therefore, // the proxy's 'this' becomes the equivalent of RealProxy's backpointer to RealProxy, so we were // able to remove an extraneous field and ctor arg from the DispatchProxy proxies. // internal static class DispatchProxyGenerator { // Generated proxies have a private Action field that all generated methods // invoke. It is the first field in the class and the first ctor parameter. private const int InvokeActionFieldAndCtorParameterIndex = 0; // Proxies are requested for a pair of types: base type and interface type. // The generated proxy will subclass the given base type and implement the interface type. // We maintain a cache keyed by 'base type' containing a dictionary keyed by interface type, // containing the generated proxy type for that pair. There are likely to be few (maybe only 1) // base type in use for many interface types. // Note: this differs from Silverlight's RealProxy implementation which keys strictly off the // interface type. But this does not allow the same interface type to be used with more than a // single base type. The implementation here permits multiple interface types to be used with // multiple base types, and the generated proxy types will be unique. // This cache of generated types grows unbounded, one element per unique T/ProxyT pair. // This approach is used to prevent regenerating identical proxy types for identical T/Proxy pairs, // which would ultimately be a more expensive leak. // Proxy instances are not cached. Their lifetime is entirely owned by the caller of DispatchProxy.Create. private static readonly Dictionary<Type, Dictionary<Type, Type>> s_baseTypeAndInterfaceToGeneratedProxyType = new Dictionary<Type, Dictionary<Type, Type>>(); private static readonly ProxyAssembly s_proxyAssembly = new ProxyAssembly(); private static readonly MethodInfo s_dispatchProxyInvokeMethod = typeof(DispatchProxy).GetTypeInfo().GetDeclaredMethod("Invoke"); // Returns a new instance of a proxy the derives from 'baseType' and implements 'interfaceType' internal static object CreateProxyInstance(Type baseType, Type interfaceType) { Debug.Assert(baseType != null); Debug.Assert(interfaceType != null); Type proxiedType = GetProxyType(baseType, interfaceType); return Activator.CreateInstance(proxiedType, (Action<object[]>)DispatchProxyGenerator.Invoke); } private static Type GetProxyType(Type baseType, Type interfaceType) { lock (s_baseTypeAndInterfaceToGeneratedProxyType) { Dictionary<Type, Type> interfaceToProxy = null; if (!s_baseTypeAndInterfaceToGeneratedProxyType.TryGetValue(baseType, out interfaceToProxy)) { interfaceToProxy = new Dictionary<Type, Type>(); s_baseTypeAndInterfaceToGeneratedProxyType[baseType] = interfaceToProxy; } Type generatedProxy = null; if (!interfaceToProxy.TryGetValue(interfaceType, out generatedProxy)) { generatedProxy = GenerateProxyType(baseType, interfaceType); interfaceToProxy[interfaceType] = generatedProxy; } return generatedProxy; } } // Unconditionally generates a new proxy type derived from 'baseType' and implements 'interfaceType' private static Type GenerateProxyType(Type baseType, Type interfaceType) { // Parameter validation is deferred until the point we need to create the proxy. // This prevents unnecessary overhead revalidating cached proxy types. TypeInfo baseTypeInfo = baseType.GetTypeInfo(); // The interface type must be an interface, not a class if (!interfaceType.GetTypeInfo().IsInterface) { // "T" is the generic parameter seen via the public contract throw new ArgumentException(SR.Format(SR.InterfaceType_Must_Be_Interface, interfaceType.FullName), "T"); } // The base type cannot be sealed because the proxy needs to subclass it. if (baseTypeInfo.IsSealed) { // "TProxy" is the generic parameter seen via the public contract throw new ArgumentException(SR.Format(SR.BaseType_Cannot_Be_Sealed, baseTypeInfo.FullName), "TProxy"); } // The base type cannot be abstract if (baseTypeInfo.IsAbstract) { throw new ArgumentException(SR.Format(SR.BaseType_Cannot_Be_Abstract, baseType.FullName), "TProxy"); } // The base type must have a public default ctor if (!baseTypeInfo.DeclaredConstructors.Any(c => c.IsPublic && c.GetParameters().Length == 0)) { throw new ArgumentException(SR.Format(SR.BaseType_Must_Have_Default_Ctor, baseType.FullName), "TProxy"); } // Create a type that derives from 'baseType' provided by caller ProxyBuilder pb = s_proxyAssembly.CreateProxy("generatedProxy", baseType); foreach (Type t in interfaceType.GetTypeInfo().ImplementedInterfaces) pb.AddInterfaceImpl(t); pb.AddInterfaceImpl(interfaceType); Type generatedProxyType = pb.CreateType(); return generatedProxyType; } // All generated proxy methods call this static helper method to dispatch. // Its job is to unpack the arguments and the 'this' instance and to dispatch directly // to the (abstract) DispatchProxy.Invoke() method. private static void Invoke(object[] args) { PackedArgs packed = new PackedArgs(args); MethodBase method = s_proxyAssembly.ResolveMethodToken(packed.DeclaringType, packed.MethodToken); if (method.IsGenericMethodDefinition) method = ((MethodInfo)method).MakeGenericMethod(packed.GenericTypes); // Call (protected method) DispatchProxy.Invoke() try { Debug.Assert(s_dispatchProxyInvokeMethod != null); object returnValue = s_dispatchProxyInvokeMethod.Invoke(packed.DispatchProxy, new object[] { method, packed.Args }); packed.ReturnValue = returnValue; } catch (TargetInvocationException tie) { ExceptionDispatchInfo.Capture(tie.InnerException).Throw(); } } private class PackedArgs { internal const int DispatchProxyPosition = 0; internal const int DeclaringTypePosition = 1; internal const int MethodTokenPosition = 2; internal const int ArgsPosition = 3; internal const int GenericTypesPosition = 4; internal const int ReturnValuePosition = 5; internal static readonly Type[] PackedTypes = new Type[] { typeof(object), typeof(Type), typeof(int), typeof(object[]), typeof(Type[]), typeof(object) }; private object[] _args; internal PackedArgs() : this(new object[PackedTypes.Length]) { } internal PackedArgs(object[] args) { _args = args; } internal DispatchProxy DispatchProxy { get { return (DispatchProxy)_args[DispatchProxyPosition]; } } internal Type DeclaringType { get { return (Type)_args[DeclaringTypePosition]; } } internal int MethodToken { get { return (int)_args[MethodTokenPosition]; } } internal object[] Args { get { return (object[])_args[ArgsPosition]; } } internal Type[] GenericTypes { get { return (Type[])_args[GenericTypesPosition]; } } internal object ReturnValue { /*get { return args[ReturnValuePosition]; }*/ set { _args[ReturnValuePosition] = value; } } } private class ProxyAssembly { private AssemblyBuilder _ab; private ModuleBuilder _mb; private int _typeId = 0; // Maintain a MethodBase-->int, int-->MethodBase mapping to permit generated code // to pass methods by token private Dictionary<MethodBase, int> _methodToToken = new Dictionary<MethodBase, int>(); private List<MethodBase> _methodsByToken = new List<MethodBase>(); private HashSet<string> _ignoresAccessAssemblyNames = new HashSet<string>(); private ConstructorInfo _ignoresAccessChecksToAttributeConstructor; public ProxyAssembly() { _ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ProxyBuilder"), AssemblyBuilderAccess.Run); _mb = _ab.DefineDynamicModule("testmod"); } // Gets or creates the ConstructorInfo for the IgnoresAccessChecksAttribute. // This attribute is both defined and referenced in the dynamic assembly to // allow access to internal types in other assemblies. internal ConstructorInfo IgnoresAccessChecksAttributeConstructor { get { if (_ignoresAccessChecksToAttributeConstructor == null) { _ignoresAccessChecksToAttributeConstructor = IgnoreAccessChecksToAttributeBuilder.AddToModule(_mb); } return _ignoresAccessChecksToAttributeConstructor; } } public ProxyBuilder CreateProxy(string name, Type proxyBaseType) { int nextId = Interlocked.Increment(ref _typeId); TypeBuilder tb = _mb.DefineType(name + "_" + nextId, TypeAttributes.Public, proxyBaseType); return new ProxyBuilder(this, tb, proxyBaseType); } // Generates an instance of the IgnoresAccessChecksToAttribute to // identify the given assembly as one which contains internal types // the dynamic assembly will need to reference. internal void GenerateInstanceOfIgnoresAccessChecksToAttribute(string assemblyName) { // Add this assembly level attribute: // [assembly: System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute(assemblyName)] ConstructorInfo attributeConstructor = IgnoresAccessChecksAttributeConstructor; CustomAttributeBuilder customAttributeBuilder = new CustomAttributeBuilder(attributeConstructor, new object[] { assemblyName }); _ab.SetCustomAttribute(customAttributeBuilder); } // Ensures the type we will reference from the dynamic assembly // is visible. Non-public types need to emit an attribute that // allows access from the dynamic assembly. internal void EnsureTypeIsVisible(Type type) { TypeInfo typeInfo = type.GetTypeInfo(); if (!typeInfo.IsVisible) { string assemblyName = typeInfo.Assembly.GetName().Name; if (!_ignoresAccessAssemblyNames.Contains(assemblyName)) { GenerateInstanceOfIgnoresAccessChecksToAttribute(assemblyName); _ignoresAccessAssemblyNames.Add(assemblyName); } } } internal void GetTokenForMethod(MethodBase method, out Type type, out int token) { type = method.DeclaringType; token = 0; if (!_methodToToken.TryGetValue(method, out token)) { _methodsByToken.Add(method); token = _methodsByToken.Count - 1; _methodToToken[method] = token; } } internal MethodBase ResolveMethodToken(Type type, int token) { Debug.Assert(token >= 0 && token < _methodsByToken.Count); return _methodsByToken[token]; } } private class ProxyBuilder { private static readonly MethodInfo s_delegateInvoke = typeof(Action<object[]>).GetTypeInfo().GetDeclaredMethod("Invoke"); private ProxyAssembly _assembly; private TypeBuilder _tb; private Type _proxyBaseType; private List<FieldBuilder> _fields; internal ProxyBuilder(ProxyAssembly assembly, TypeBuilder tb, Type proxyBaseType) { _assembly = assembly; _tb = tb; _proxyBaseType = proxyBaseType; _fields = new List<FieldBuilder>(); _fields.Add(tb.DefineField("invoke", typeof(Action<object[]>), FieldAttributes.Private)); } private void Complete() { Type[] args = new Type[_fields.Count]; for (int i = 0; i < args.Length; i++) { args[i] = _fields[i].FieldType; } ConstructorBuilder cb = _tb.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, args); ILGenerator il = cb.GetILGenerator(); // chained ctor call ConstructorInfo baseCtor = _proxyBaseType.GetTypeInfo().DeclaredConstructors.SingleOrDefault(c => c.IsPublic && c.GetParameters().Length == 0); Debug.Assert(baseCtor != null); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, baseCtor); // store all the fields for (int i = 0; i < args.Length; i++) { il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg, i + 1); il.Emit(OpCodes.Stfld, _fields[i]); } il.Emit(OpCodes.Ret); } internal Type CreateType() { this.Complete(); return _tb.CreateTypeInfo().AsType(); } internal void AddInterfaceImpl(Type iface) { // If necessary, generate an attribute to permit visibility // to internal types. _assembly.EnsureTypeIsVisible(iface); _tb.AddInterfaceImplementation(iface); // AccessorMethods -> Metadata mappings. var propertyMap = new Dictionary<MethodInfo, PropertyAccessorInfo>(MethodInfoEqualityComparer.Instance); foreach (PropertyInfo pi in iface.GetRuntimeProperties()) { var ai = new PropertyAccessorInfo(pi.GetMethod, pi.SetMethod); if (pi.GetMethod != null) propertyMap[pi.GetMethod] = ai; if (pi.SetMethod != null) propertyMap[pi.SetMethod] = ai; } var eventMap = new Dictionary<MethodInfo, EventAccessorInfo>(MethodInfoEqualityComparer.Instance); foreach (EventInfo ei in iface.GetRuntimeEvents()) { var ai = new EventAccessorInfo(ei.AddMethod, ei.RemoveMethod, ei.RaiseMethod); if (ei.AddMethod != null) eventMap[ei.AddMethod] = ai; if (ei.RemoveMethod != null) eventMap[ei.RemoveMethod] = ai; if (ei.RaiseMethod != null) eventMap[ei.RaiseMethod] = ai; } foreach (MethodInfo mi in iface.GetRuntimeMethods()) { MethodBuilder mdb = AddMethodImpl(mi); PropertyAccessorInfo associatedProperty; if (propertyMap.TryGetValue(mi, out associatedProperty)) { if (MethodInfoEqualityComparer.Instance.Equals(associatedProperty.InterfaceGetMethod, mi)) associatedProperty.GetMethodBuilder = mdb; else associatedProperty.SetMethodBuilder = mdb; } EventAccessorInfo associatedEvent; if (eventMap.TryGetValue(mi, out associatedEvent)) { if (MethodInfoEqualityComparer.Instance.Equals(associatedEvent.InterfaceAddMethod, mi)) associatedEvent.AddMethodBuilder = mdb; else if (MethodInfoEqualityComparer.Instance.Equals(associatedEvent.InterfaceRemoveMethod, mi)) associatedEvent.RemoveMethodBuilder = mdb; else associatedEvent.RaiseMethodBuilder = mdb; } } foreach (PropertyInfo pi in iface.GetRuntimeProperties()) { PropertyAccessorInfo ai = propertyMap[pi.GetMethod ?? pi.SetMethod]; PropertyBuilder pb = _tb.DefineProperty(pi.Name, pi.Attributes, pi.PropertyType, pi.GetIndexParameters().Select(p => p.ParameterType).ToArray()); if (ai.GetMethodBuilder != null) pb.SetGetMethod(ai.GetMethodBuilder); if (ai.SetMethodBuilder != null) pb.SetSetMethod(ai.SetMethodBuilder); } foreach (EventInfo ei in iface.GetRuntimeEvents()) { EventAccessorInfo ai = eventMap[ei.AddMethod ?? ei.RemoveMethod]; EventBuilder eb = _tb.DefineEvent(ei.Name, ei.Attributes, ei.EventHandlerType); if (ai.AddMethodBuilder != null) eb.SetAddOnMethod(ai.AddMethodBuilder); if (ai.RemoveMethodBuilder != null) eb.SetRemoveOnMethod(ai.RemoveMethodBuilder); if (ai.RaiseMethodBuilder != null) eb.SetRaiseMethod(ai.RaiseMethodBuilder); } } private MethodBuilder AddMethodImpl(MethodInfo mi) { ParameterInfo[] parameters = mi.GetParameters(); Type[] paramTypes = ParamTypes(parameters, false); MethodBuilder mdb = _tb.DefineMethod(mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, paramTypes); if (mi.ContainsGenericParameters) { Type[] ts = mi.GetGenericArguments(); string[] ss = new string[ts.Length]; for (int i = 0; i < ts.Length; i++) { ss[i] = ts[i].Name; } GenericTypeParameterBuilder[] genericParameters = mdb.DefineGenericParameters(ss); for (int i = 0; i < genericParameters.Length; i++) { genericParameters[i].SetGenericParameterAttributes(ts[i].GetTypeInfo().GenericParameterAttributes); } } ILGenerator il = mdb.GetILGenerator(); ParametersArray args = new ParametersArray(il, paramTypes); // object[] args = new object[paramCount]; il.Emit(OpCodes.Nop); GenericArray<object> argsArr = new GenericArray<object>(il, ParamTypes(parameters, true).Length); for (int i = 0; i < parameters.Length; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } // object[] packed = new object[PackedArgs.PackedTypes.Length]; GenericArray<object> packedArr = new GenericArray<object>(il, PackedArgs.PackedTypes.Length); // packed[PackedArgs.DispatchProxyPosition] = this; packedArr.BeginSet(PackedArgs.DispatchProxyPosition); il.Emit(OpCodes.Ldarg_0); packedArr.EndSet(typeof(DispatchProxy)); // packed[PackedArgs.DeclaringTypePosition] = typeof(iface); MethodInfo Type_GetTypeFromHandle = typeof(Type).GetRuntimeMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }); int methodToken; Type declaringType; _assembly.GetTokenForMethod(mi, out declaringType, out methodToken); packedArr.BeginSet(PackedArgs.DeclaringTypePosition); il.Emit(OpCodes.Ldtoken, declaringType); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); packedArr.EndSet(typeof(object)); // packed[PackedArgs.MethodTokenPosition] = iface method token; packedArr.BeginSet(PackedArgs.MethodTokenPosition); il.Emit(OpCodes.Ldc_I4, methodToken); packedArr.EndSet(typeof(int)); // packed[PackedArgs.ArgsPosition] = args; packedArr.BeginSet(PackedArgs.ArgsPosition); argsArr.Load(); packedArr.EndSet(typeof(object[])); // packed[PackedArgs.GenericTypesPosition] = mi.GetGenericArguments(); if (mi.ContainsGenericParameters) { packedArr.BeginSet(PackedArgs.GenericTypesPosition); Type[] genericTypes = mi.GetGenericArguments(); GenericArray<Type> typeArr = new GenericArray<Type>(il, genericTypes.Length); for (int i = 0; i < genericTypes.Length; ++i) { typeArr.BeginSet(i); il.Emit(OpCodes.Ldtoken, genericTypes[i]); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); typeArr.EndSet(typeof(Type)); } typeArr.Load(); packedArr.EndSet(typeof(Type[])); } // Call static DispatchProxyHelper.Invoke(object[]) il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, _fields[InvokeActionFieldAndCtorParameterIndex]); // delegate packedArr.Load(); il.Emit(OpCodes.Call, s_delegateInvoke); for (int i = 0; i < parameters.Length; i++) { if (parameters[i].ParameterType.IsByRef) { args.BeginSet(i); argsArr.Get(i); args.EndSet(i, typeof(object)); } } if (mi.ReturnType != typeof(void)) { packedArr.Get(PackedArgs.ReturnValuePosition); Convert(il, typeof(object), mi.ReturnType, false); } il.Emit(OpCodes.Ret); _tb.DefineMethodOverride(mdb, mi); return mdb; } private static Type[] ParamTypes(ParameterInfo[] parms, bool noByRef) { Type[] types = new Type[parms.Length]; for (int i = 0; i < parms.Length; i++) { types[i] = parms[i].ParameterType; if (noByRef && types[i].IsByRef) types[i] = types[i].GetElementType(); } return types; } // TypeCode does not exist in ProjectK or ProjectN. // This lookup method was copied from PortableLibraryThunks\Internal\PortableLibraryThunks\System\TypeThunks.cs // but returns the integer value equivalent to its TypeCode enum. private static int GetTypeCode(Type type) { if (type == null) return 0; // TypeCode.Empty; if (type == typeof(bool)) return 3; // TypeCode.Boolean; if (type == typeof(char)) return 4; // TypeCode.Char; if (type == typeof(sbyte)) return 5; // TypeCode.SByte; if (type == typeof(byte)) return 6; // TypeCode.Byte; if (type == typeof(short)) return 7; // TypeCode.Int16; if (type == typeof(ushort)) return 8; // TypeCode.UInt16; if (type == typeof(int)) return 9; // TypeCode.Int32; if (type == typeof(uint)) return 10; // TypeCode.UInt32; if (type == typeof(long)) return 11; // TypeCode.Int64; if (type == typeof(ulong)) return 12; // TypeCode.UInt64; if (type == typeof(float)) return 13; // TypeCode.Single; if (type == typeof(double)) return 14; // TypeCode.Double; if (type == typeof(decimal)) return 15; // TypeCode.Decimal; if (type == typeof(DateTime)) return 16; // TypeCode.DateTime; if (type == typeof(string)) return 18; // TypeCode.String; if (type.GetTypeInfo().IsEnum) return GetTypeCode(Enum.GetUnderlyingType(type)); return 1; // TypeCode.Object; } private static OpCode[] s_convOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Conv_I1,//Boolean = 3, OpCodes.Conv_I2,//Char = 4, OpCodes.Conv_I1,//SByte = 5, OpCodes.Conv_U1,//Byte = 6, OpCodes.Conv_I2,//Int16 = 7, OpCodes.Conv_U2,//UInt16 = 8, OpCodes.Conv_I4,//Int32 = 9, OpCodes.Conv_U4,//UInt32 = 10, OpCodes.Conv_I8,//Int64 = 11, OpCodes.Conv_U8,//UInt64 = 12, OpCodes.Conv_R4,//Single = 13, OpCodes.Conv_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Nop,//String = 18, }; private static OpCode[] s_ldindOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Ldind_I1,//Boolean = 3, OpCodes.Ldind_I2,//Char = 4, OpCodes.Ldind_I1,//SByte = 5, OpCodes.Ldind_U1,//Byte = 6, OpCodes.Ldind_I2,//Int16 = 7, OpCodes.Ldind_U2,//UInt16 = 8, OpCodes.Ldind_I4,//Int32 = 9, OpCodes.Ldind_U4,//UInt32 = 10, OpCodes.Ldind_I8,//Int64 = 11, OpCodes.Ldind_I8,//UInt64 = 12, OpCodes.Ldind_R4,//Single = 13, OpCodes.Ldind_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Ldind_Ref,//String = 18, }; private static OpCode[] s_stindOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Stind_I1,//Boolean = 3, OpCodes.Stind_I2,//Char = 4, OpCodes.Stind_I1,//SByte = 5, OpCodes.Stind_I1,//Byte = 6, OpCodes.Stind_I2,//Int16 = 7, OpCodes.Stind_I2,//UInt16 = 8, OpCodes.Stind_I4,//Int32 = 9, OpCodes.Stind_I4,//UInt32 = 10, OpCodes.Stind_I8,//Int64 = 11, OpCodes.Stind_I8,//UInt64 = 12, OpCodes.Stind_R4,//Single = 13, OpCodes.Stind_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Stind_Ref,//String = 18, }; private static void Convert(ILGenerator il, Type source, Type target, bool isAddress) { Debug.Assert(!target.IsByRef); if (target == source) return; TypeInfo sourceTypeInfo = source.GetTypeInfo(); TypeInfo targetTypeInfo = target.GetTypeInfo(); if (source.IsByRef) { Debug.Assert(!isAddress); Type argType = source.GetElementType(); Ldind(il, argType); Convert(il, argType, target, isAddress); return; } if (targetTypeInfo.IsValueType) { if (sourceTypeInfo.IsValueType) { OpCode opCode = s_convOpCodes[GetTypeCode(target)]; Debug.Assert(!opCode.Equals(OpCodes.Nop)); il.Emit(opCode); } else { Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo)); il.Emit(OpCodes.Unbox, target); if (!isAddress) Ldind(il, target); } } else if (targetTypeInfo.IsAssignableFrom(sourceTypeInfo)) { if (sourceTypeInfo.IsValueType || source.IsGenericParameter) { if (isAddress) Ldind(il, source); il.Emit(OpCodes.Box, source); } } else { Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo) || targetTypeInfo.IsInterface || sourceTypeInfo.IsInterface); if (target.IsGenericParameter) { il.Emit(OpCodes.Unbox_Any, target); } else { il.Emit(OpCodes.Castclass, target); } } } private static void Ldind(ILGenerator il, Type type) { OpCode opCode = s_ldindOpCodes[GetTypeCode(type)]; if (!opCode.Equals(OpCodes.Nop)) { il.Emit(opCode); } else { il.Emit(OpCodes.Ldobj, type); } } private static void Stind(ILGenerator il, Type type) { OpCode opCode = s_stindOpCodes[GetTypeCode(type)]; if (!opCode.Equals(OpCodes.Nop)) { il.Emit(opCode); } else { il.Emit(OpCodes.Stobj, type); } } private class ParametersArray { private ILGenerator _il; private Type[] _paramTypes; internal ParametersArray(ILGenerator il, Type[] paramTypes) { _il = il; _paramTypes = paramTypes; } internal void Get(int i) { _il.Emit(OpCodes.Ldarg, i + 1); } internal void BeginSet(int i) { _il.Emit(OpCodes.Ldarg, i + 1); } internal void EndSet(int i, Type stackType) { Debug.Assert(_paramTypes[i].IsByRef); Type argType = _paramTypes[i].GetElementType(); Convert(_il, stackType, argType, false); Stind(_il, argType); } } private class GenericArray<T> { private ILGenerator _il; private LocalBuilder _lb; internal GenericArray(ILGenerator il, int len) { _il = il; _lb = il.DeclareLocal(typeof(T[])); il.Emit(OpCodes.Ldc_I4, len); il.Emit(OpCodes.Newarr, typeof(T)); il.Emit(OpCodes.Stloc, _lb); } internal void Load() { _il.Emit(OpCodes.Ldloc, _lb); } internal void Get(int i) { _il.Emit(OpCodes.Ldloc, _lb); _il.Emit(OpCodes.Ldc_I4, i); _il.Emit(OpCodes.Ldelem_Ref); } internal void BeginSet(int i) { _il.Emit(OpCodes.Ldloc, _lb); _il.Emit(OpCodes.Ldc_I4, i); } internal void EndSet(Type stackType) { Convert(_il, stackType, typeof(T), false); _il.Emit(OpCodes.Stelem_Ref); } } private sealed class PropertyAccessorInfo { public MethodInfo InterfaceGetMethod { get; } public MethodInfo InterfaceSetMethod { get; } public MethodBuilder GetMethodBuilder { get; set; } public MethodBuilder SetMethodBuilder { get; set; } public PropertyAccessorInfo(MethodInfo interfaceGetMethod, MethodInfo interfaceSetMethod) { InterfaceGetMethod = interfaceGetMethod; InterfaceSetMethod = interfaceSetMethod; } } private sealed class EventAccessorInfo { public MethodInfo InterfaceAddMethod { get; } public MethodInfo InterfaceRemoveMethod { get; } public MethodInfo InterfaceRaiseMethod { get; } public MethodBuilder AddMethodBuilder { get; set; } public MethodBuilder RemoveMethodBuilder { get; set; } public MethodBuilder RaiseMethodBuilder { get; set; } public EventAccessorInfo(MethodInfo interfaceAddMethod, MethodInfo interfaceRemoveMethod, MethodInfo interfaceRaiseMethod) { InterfaceAddMethod = interfaceAddMethod; InterfaceRemoveMethod = interfaceRemoveMethod; InterfaceRaiseMethod = interfaceRaiseMethod; } } private sealed class MethodInfoEqualityComparer : EqualityComparer<MethodInfo> { public static readonly MethodInfoEqualityComparer Instance = new MethodInfoEqualityComparer(); private MethodInfoEqualityComparer() { } public sealed override bool Equals(MethodInfo left, MethodInfo right) { if (ReferenceEquals(left, right)) return true; if (left == null) return right == null; else if (right == null) return false; // This assembly should work in netstandard1.3, // so we cannot use MemberInfo.MetadataToken here. // Therefore, it compares honestly referring ECMA-335 I.8.6.1.6 Signature Matching. if (!Equals(left.DeclaringType, right.DeclaringType)) return false; if (!Equals(left.ReturnType, right.ReturnType)) return false; if (left.CallingConvention != right.CallingConvention) return false; if (left.IsStatic != right.IsStatic) return false; if ( left.Name != right.Name) return false; Type[] leftGenericParameters = left.GetGenericArguments(); Type[] rightGenericParameters = right.GetGenericArguments(); if (leftGenericParameters.Length != rightGenericParameters.Length) return false; for (int i = 0; i < leftGenericParameters.Length; i++) { if (!Equals(leftGenericParameters[i], rightGenericParameters[i])) return false; } ParameterInfo[] leftParameters = left.GetParameters(); ParameterInfo[] rightParameters = right.GetParameters(); if (leftParameters.Length != rightParameters.Length) return false; for (int i = 0; i < leftParameters.Length; i++) { if (!Equals(leftParameters[i].ParameterType, rightParameters[i].ParameterType)) return false; } return true; } public sealed override int GetHashCode(MethodInfo obj) { if (obj == null) return 0; int hashCode = obj.DeclaringType.GetHashCode(); hashCode ^= obj.Name.GetHashCode(); foreach (ParameterInfo parameter in obj.GetParameters()) { hashCode ^= parameter.ParameterType.GetHashCode(); } return hashCode; } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // 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. // File System.Net.WebClient.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Net { public partial class WebClient : System.ComponentModel.Component { #region Methods and constructors public void CancelAsync() { } public byte[] DownloadData(Uri address) { return default(byte[]); } public byte[] DownloadData(string address) { return default(byte[]); } public void DownloadDataAsync(Uri address) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void DownloadDataAsync(Uri address, Object userToken) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void DownloadFile(Uri address, string fileName) { } public void DownloadFile(string address, string fileName) { } public void DownloadFileAsync(Uri address, string fileName, Object userToken) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void DownloadFileAsync(Uri address, string fileName) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public string DownloadString(Uri address) { return default(string); } public string DownloadString(string address) { return default(string); } public void DownloadStringAsync(Uri address) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void DownloadStringAsync(Uri address, Object userToken) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } protected virtual new WebRequest GetWebRequest(Uri address) { return default(WebRequest); } protected virtual new WebResponse GetWebResponse(WebRequest request) { Contract.Requires(request != null); return default(WebResponse); } protected virtual new WebResponse GetWebResponse(WebRequest request, IAsyncResult result) { Contract.Requires(request != null); return default(WebResponse); } protected virtual new void OnDownloadDataCompleted(DownloadDataCompletedEventArgs e) { } protected virtual new void OnDownloadFileCompleted(System.ComponentModel.AsyncCompletedEventArgs e) { } protected virtual new void OnDownloadProgressChanged(DownloadProgressChangedEventArgs e) { } protected virtual new void OnDownloadStringCompleted(DownloadStringCompletedEventArgs e) { } protected virtual new void OnOpenReadCompleted(OpenReadCompletedEventArgs e) { } protected virtual new void OnOpenWriteCompleted(OpenWriteCompletedEventArgs e) { } protected virtual new void OnUploadDataCompleted(UploadDataCompletedEventArgs e) { } protected virtual new void OnUploadFileCompleted(UploadFileCompletedEventArgs e) { } protected virtual new void OnUploadProgressChanged(UploadProgressChangedEventArgs e) { } protected virtual new void OnUploadStringCompleted(UploadStringCompletedEventArgs e) { } protected virtual new void OnUploadValuesCompleted(UploadValuesCompletedEventArgs e) { } public Stream OpenRead(string address) { return default(Stream); } public Stream OpenRead(Uri address) { return default(Stream); } public void OpenReadAsync(Uri address) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void OpenReadAsync(Uri address, Object userToken) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public Stream OpenWrite(string address, string method) { Contract.Ensures(Contract.Result<System.IO.Stream>() != null); return default(Stream); } public Stream OpenWrite(Uri address, string method) { Contract.Ensures(Contract.Result<System.IO.Stream>() != null); return default(Stream); } public Stream OpenWrite(Uri address) { Contract.Ensures(Contract.Result<System.IO.Stream>() != null); return default(Stream); } public Stream OpenWrite(string address) { Contract.Ensures(Contract.Result<System.IO.Stream>() != null); return default(Stream); } public void OpenWriteAsync(Uri address, string method, Object userToken) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void OpenWriteAsync(Uri address, string method) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void OpenWriteAsync(Uri address) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public byte[] UploadData(string address, byte[] data) { return default(byte[]); } public byte[] UploadData(Uri address, string method, byte[] data) { return default(byte[]); } public byte[] UploadData(string address, string method, byte[] data) { return default(byte[]); } public byte[] UploadData(Uri address, byte[] data) { return default(byte[]); } public void UploadDataAsync(Uri address, byte[] data) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void UploadDataAsync(Uri address, string method, byte[] data) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void UploadDataAsync(Uri address, string method, byte[] data, Object userToken) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public byte[] UploadFile(Uri address, string method, string fileName) { return default(byte[]); } public byte[] UploadFile(string address, string fileName) { return default(byte[]); } public byte[] UploadFile(string address, string method, string fileName) { return default(byte[]); } public byte[] UploadFile(Uri address, string fileName) { return default(byte[]); } public void UploadFileAsync(Uri address, string method, string fileName, Object userToken) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void UploadFileAsync(Uri address, string method, string fileName) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void UploadFileAsync(Uri address, string fileName) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public string UploadString(Uri address, string method, string data) { return default(string); } public string UploadString(Uri address, string data) { return default(string); } public string UploadString(string address, string method, string data) { return default(string); } public string UploadString(string address, string data) { return default(string); } public void UploadStringAsync(Uri address, string data) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void UploadStringAsync(Uri address, string method, string data, Object userToken) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void UploadStringAsync(Uri address, string method, string data) { Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public byte[] UploadValues(string address, System.Collections.Specialized.NameValueCollection data) { Contract.Requires(data.AllKeys != null); Contract.Ensures(0 <= data.AllKeys.Length); return default(byte[]); } public byte[] UploadValues(Uri address, string method, System.Collections.Specialized.NameValueCollection data) { Contract.Requires(data.AllKeys != null); Contract.Ensures(0 <= data.AllKeys.Length); return default(byte[]); } public byte[] UploadValues(string address, string method, System.Collections.Specialized.NameValueCollection data) { Contract.Requires(data.AllKeys != null); Contract.Ensures(0 <= data.AllKeys.Length); return default(byte[]); } public byte[] UploadValues(Uri address, System.Collections.Specialized.NameValueCollection data) { Contract.Requires(data.AllKeys != null); Contract.Ensures(0 <= data.AllKeys.Length); return default(byte[]); } public void UploadValuesAsync(Uri address, string method, System.Collections.Specialized.NameValueCollection data) { Contract.Requires(data.AllKeys != null); Contract.Ensures(0 <= data.AllKeys.Length); Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void UploadValuesAsync(Uri address, System.Collections.Specialized.NameValueCollection data) { Contract.Requires(data.AllKeys != null); Contract.Ensures(0 <= data.AllKeys.Length); Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public void UploadValuesAsync(Uri address, string method, System.Collections.Specialized.NameValueCollection data, Object userToken) { Contract.Requires(data.AllKeys != null); Contract.Ensures(0 <= data.AllKeys.Length); Contract.Ensures(System.ComponentModel.AsyncOperationManager.SynchronizationContext == System.Threading.SynchronizationContext.Current); } public WebClient() { } #endregion #region Properties and indexers public string BaseAddress { get { return default(string); } set { } } public System.Net.Cache.RequestCachePolicy CachePolicy { get { return default(System.Net.Cache.RequestCachePolicy); } set { } } public ICredentials Credentials { get { return default(ICredentials); } set { } } public Encoding Encoding { get { return default(Encoding); } set { } } public WebHeaderCollection Headers { get { Contract.Ensures(Contract.Result<System.Net.WebHeaderCollection>() != null); return default(WebHeaderCollection); } set { } } public bool IsBusy { get { return default(bool); } } public IWebProxy Proxy { get { return default(IWebProxy); } set { } } public System.Collections.Specialized.NameValueCollection QueryString { get { Contract.Ensures(Contract.Result<System.Collections.Specialized.NameValueCollection>() != null); return default(System.Collections.Specialized.NameValueCollection); } set { } } public WebHeaderCollection ResponseHeaders { get { return default(WebHeaderCollection); } } public bool UseDefaultCredentials { get { return default(bool); } set { } } #endregion #region Events public event DownloadDataCompletedEventHandler DownloadDataCompleted { add { } remove { } } public event System.ComponentModel.AsyncCompletedEventHandler DownloadFileCompleted { add { } remove { } } public event DownloadProgressChangedEventHandler DownloadProgressChanged { add { } remove { } } public event DownloadStringCompletedEventHandler DownloadStringCompleted { add { } remove { } } public event OpenReadCompletedEventHandler OpenReadCompleted { add { } remove { } } public event OpenWriteCompletedEventHandler OpenWriteCompleted { add { } remove { } } public event UploadDataCompletedEventHandler UploadDataCompleted { add { } remove { } } public event UploadFileCompletedEventHandler UploadFileCompleted { add { } remove { } } public event UploadProgressChangedEventHandler UploadProgressChanged { add { } remove { } } public event UploadStringCompletedEventHandler UploadStringCompleted { add { } remove { } } public event UploadValuesCompletedEventHandler UploadValuesCompleted { add { } remove { } } #endregion } }
//----------------------------------------------------------------------- // <copyright file="AppContextTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>Test to see if contexts get cleared out properly</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using Csla; using System.Threading; #if !NUNIT using Microsoft.VisualStudio.TestTools.UnitTesting; #else using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; #endif namespace Csla.Test.AppContext { [TestClass()] public class AppContextTests { #region Simple Test [TestMethod()] public void SimpleTest() { ApplicationContext.Clear(); ApplicationContext.ClientContext["v1"] = "client"; ApplicationContext.GlobalContext["v2"] = "client"; SimpleRoot root = SimpleRoot.GetSimpleRoot("data"); Assert.AreEqual("client", ApplicationContext.ClientContext["v1"], "client context didn't roundtrip"); Assert.AreEqual("client", ApplicationContext.GlobalContext["v2"], "global context didn't roundtrip"); Assert.AreEqual("Fetched", ApplicationContext.GlobalContext["Root"], "global context missing server value"); } #endregion [TestMethod()] public void ApplicationContextProperties() { ApplicationContext.DataPortalProxy = null; Assert.AreEqual("Local", ApplicationContext.DataPortalProxy); Assert.AreEqual("Client", ApplicationContext.ExecutionLocation.ToString()); } #region NoContext /// <summary> /// Test to see if contexts get cleared out properly /// </summary> /// <remarks> /// This test fails if "CSLA" is all capitol letters. Using "Csla", /// as the namespace implies, is correct. /// </remarks> [TestMethod()] public void NoContext() { //clear the contexts Csla.ApplicationContext.GlobalContext.Clear(); ApplicationContext.ClientContext.Clear(); ApplicationContext.ClientContext.Add("Test", "Test"); ApplicationContext.GlobalContext.Add("Test", "Test"); Assert.IsNull(AppDomain.CurrentDomain.GetData("CSLA.ClientContext"), "ClientContext should be null"); System.LocalDataStoreSlot slot; slot = Thread.GetNamedDataSlot("CSLA.GlobalContext"); Assert.IsNull(Thread.GetData(slot), "GlobalContext should be null"); Assert.IsNotNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "Csla.ClientContext should not be null"); slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNotNull(Thread.GetData(slot), "GlobalContext should not be null"); } #endregion #region TestOnDemandContexts [TestMethod] public void TestOnDemandContexts() { //Make sure its all clear completely Csla.ApplicationContext.Clear(); System.LocalDataStoreSlot slot; Assert.IsNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "ClientContext should be null"); slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNull(Thread.GetData(slot), "GlobalContext should be null"); //Add to the GlobalContext but NOT the ClientContext ApplicationContext.GlobalContext.Add("Test", "Test"); Assert.IsNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "ClientContext should be null"); slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNotNull(Thread.GetData(slot), "GlobalContext should be null"); //Add to the ClientContext but NOT the GlobalContext Csla.ApplicationContext.Clear(); ApplicationContext.ClientContext.Add("Test", "Test"); Assert.IsNotNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "ClientContext should be null"); slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNull(Thread.GetData(slot), "GlobalContext should be null"); //Add to both contexts Csla.ApplicationContext.Clear(); ApplicationContext.ClientContext.Add("Test", "Test"); ApplicationContext.GlobalContext.Add("Test", "Test"); Assert.IsNotNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "ClientContext should be null"); slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNotNull(Thread.GetData(slot), "GlobalContext should be null"); //Now clear ONLY the GlobalContext Csla.ApplicationContext.GlobalContext.Clear(); Assert.IsNotNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "ClientContext should be null"); //The global context should still exist, it is just empty now slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNotNull(Thread.GetData(slot), "GlobalContext should be null"); //Now add an item to the GlobalContext and clear only the ClientContext ApplicationContext.GlobalContext.Add("Test", "Test"); ApplicationContext.ClientContext.Clear(); //the clientcontext should still exist, its just empty now. Assert.IsNotNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "ClientContext should be null"); slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNotNull(Thread.GetData(slot), "GlobalContext should be null"); //Now Clear all again and make sure they're gone ApplicationContext.Clear(); Assert.IsNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "ClientContext should be null"); slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNull(Thread.GetData(slot), "GlobalContext should be null"); } #endregion #region TestAppContext across different Threads [TestMethod] public void TestAppContextAcrossDifferentThreads() { List<AppContextThread> AppContextThreadList = new List<AppContextThread>(); List<Thread> ThreadList = new List<Thread>(); for (int x = 0; x < 10; x++) { AppContextThread act = new AppContextThread("Thread: " + x); AppContextThreadList.Add(act); Thread t = new Thread(new ThreadStart(act.Run)); t.Name = "Thread: " + x; t.Start(); ThreadList.Add(t); } ApplicationContext.Clear(); Exception ex = null; try { foreach (AppContextThread act in AppContextThreadList) { //We are accessing the Client/GlobalContext via this thread, therefore //it should be removed. Assert.AreEqual(true, act.Removed); } //We are now accessing the shared value. If any other thread //loses its Client/GlobalContext this will turn to true //Assert.AreEqual(false, AppContextThread.StaticRemoved); } catch (Exception e) { ex = e; } finally { foreach (AppContextThread act in AppContextThreadList) act.Stop(); foreach (Thread t in ThreadList) { t.Join(); } } if (ex != null) throw ex; } #endregion #region ClearContexts [TestMethod] public void ClearContexts() { ApplicationContext.GlobalContext.Clear(); ApplicationContext.ClientContext.Clear(); //put stuff into the application context ApplicationContext.ClientContext.Add("Test", "Test"); ApplicationContext.GlobalContext.Add("Test", "Test"); //it should NOT be null System.LocalDataStoreSlot slot; Assert.IsNotNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "Csla.ClientContext should not be null"); slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNotNull(Thread.GetData(slot), "GlobalContext should not be null"); //Do a generic clear ApplicationContext.Clear(); //cleared, this stuff should be null now Assert.IsNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "Csla.ClientContext should not be null"); slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNull(Thread.GetData(slot), "GlobalContext should not be null"); //put stuff into the Application context ApplicationContext.ClientContext.Add("Test", "Test"); ApplicationContext.GlobalContext.Add("Test", "Test"); //Should NOT be null Assert.IsNotNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "Csla.ClientContext should not be null"); slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNotNull(Thread.GetData(slot), "GlobalContext should not be null"); //clearing each individually instead of with ApplicationContext.Clear(); ApplicationContext.ClientContext.Clear(); ApplicationContext.GlobalContext.Clear(); //put stuff into ApplicationContext ApplicationContext.ClientContext.Add("Test", "Test"); ApplicationContext.GlobalContext.Add("Test", "Test"); //should NOT be null Assert.IsNotNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "Csla.ClientContext should not be null"); slot = Thread.GetNamedDataSlot("Csla.GlobalContext"); Assert.IsNotNull(Thread.GetData(slot), "GlobalContext should not be null"); } #endregion #region ClientContext /// <summary> /// Test the Client Context /// </summary> /// <remarks> /// Clearing the GlobalContext clears the ClientContext also? /// Should the ClientContext be cleared explicitly also? /// </remarks> [TestMethod()] public void ClientContext() { Csla.ApplicationContext.GlobalContext.Clear(); Csla.ApplicationContext.ClientContext.Add("clientcontext", "client context data"); Assert.AreEqual("client context data", Csla.ApplicationContext.ClientContext["clientcontext"], "Matching data not retrieved"); Csla.Test.Basic.Root root = Csla.Test.Basic.Root.NewRoot(); root.Data = "saved"; Assert.AreEqual("saved", root.Data, "Root data should be 'saved'"); Assert.AreEqual(true, root.IsDirty, "Object should be dirty"); Assert.AreEqual(true, root.IsValid, "Object should be valid"); Csla.ApplicationContext.GlobalContext.Clear(); root = root.Save(); Assert.IsNotNull(root, "Root object should not be null"); Assert.IsNotNull(AppDomain.CurrentDomain.GetData("Csla.ClientContext"), "Client context should not be null"); Assert.AreEqual("Inserted", Csla.ApplicationContext.GlobalContext["Root"], "Object not inserted"); Assert.AreEqual("saved", root.Data, "Root data should be 'saved'"); Assert.AreEqual(false, root.IsNew, "Object should not be new"); Assert.AreEqual(false, root.IsDeleted, "Object should not be deleted"); Assert.AreEqual(false, root.IsDirty, "Object should not be dirty"); Assert.AreEqual("client context data", Csla.ApplicationContext.ClientContext["clientcontext"], "Client context data lost"); Assert.AreEqual("client context data", Csla.ApplicationContext.GlobalContext["clientcontext"], "Global context data lost"); Assert.AreEqual("new global value", Csla.ApplicationContext.GlobalContext["globalcontext"], "New global value lost"); } #endregion #region GlobalContext /// <summary> /// Test the Global Context /// </summary> [TestMethod()] public void GlobalContext() { Csla.ApplicationContext.GlobalContext.Clear(); ApplicationContext.GlobalContext["globalcontext"] = "global context data"; Assert.AreEqual("global context data", ApplicationContext.GlobalContext["globalcontext"], "first"); Csla.Test.Basic.Root root = Csla.Test.Basic.Root.NewRoot(); root.Data = "saved"; Assert.AreEqual("saved", root.Data); Assert.AreEqual(true, root.IsDirty); Assert.AreEqual(true, root.IsValid); Csla.ApplicationContext.GlobalContext.Clear(); root = root.Save(); Assert.IsNotNull(root); Assert.IsNotNull(Thread.GetData(Thread.GetNamedDataSlot("Csla.GlobalContext"))); Assert.AreEqual("Inserted", Csla.ApplicationContext.GlobalContext["Root"]); Assert.AreEqual("saved", root.Data); Assert.AreEqual(false, root.IsNew); Assert.AreEqual(false, root.IsDeleted); Assert.AreEqual(false, root.IsDirty); Assert.AreEqual("new global value", ApplicationContext.GlobalContext["globalcontext"], "Second"); } #endregion #region Dataportal Events /// <summary> /// Test the dataportal events /// </summary> /// <remarks> /// How does the GlobalContext get the keys "dpinvoke" and "dpinvokecomplete"? /// /// In the vb version of this test it calls RemoveHandler in VB. Unfortunately removing handlers aren't quite /// that easy in C# I had to declare EventHandlers that could be added and removed. Also I found out that the /// VB library does not seem to contain the DataPortalInvokeEventHandler object so I put a conditional compile /// flag around this method and set a warning message. /// </remarks> [TestMethod()] public void DataPortalEvents() { ApplicationContext.GlobalContext.Clear(); ApplicationContext.Clear(); ApplicationContext.GlobalContext["global"] = "global"; Csla.DataPortal.DataPortalInvoke += new Action<DataPortalEventArgs>(OnDataPortaInvoke); Csla.DataPortal.DataPortalInvokeComplete += new Action<DataPortalEventArgs>(OnDataPortalInvokeComplete); Csla.Test.Basic.Root root = Csla.Test.Basic.Root.GetRoot("testing"); Csla.DataPortal.DataPortalInvoke -= new Action<DataPortalEventArgs>(OnDataPortaInvoke); Csla.DataPortal.DataPortalInvokeComplete -= new Action<DataPortalEventArgs>(OnDataPortalInvokeComplete); //Populated in the handlers below Assert.AreEqual("global", Csla.ApplicationContext.GlobalContext["ClientInvoke"], "Client invoke incorrect"); Assert.AreEqual("global", Csla.ApplicationContext.GlobalContext["ClientInvokeComplete"], "Client invoke complete"); //populated in the Root Dataportal handlers. Assert.AreEqual("global", Csla.ApplicationContext.GlobalContext["dpinvoke"], "Server invoke incorrect"); Assert.AreEqual("global", Csla.ApplicationContext.GlobalContext["dpinvokecomplete"], "Server invoke compelte incorrect"); } private void OnDataPortaInvoke(DataPortalEventArgs e) { Csla.ApplicationContext.GlobalContext["ClientInvoke"] = ApplicationContext.GlobalContext["global"]; } private void OnDataPortalInvokeComplete(DataPortalEventArgs e) { Csla.ApplicationContext.GlobalContext["ClientInvokeComplete"] = ApplicationContext.GlobalContext["global"]; } #endregion #region FailCreateContext /// <summary> /// Test the FaileCreate Context /// </summary> [TestMethod()] public void FailCreateContext() { ApplicationContext.GlobalContext.Clear(); ApplicationContext.Clear(); ExceptionRoot root; try { root = ExceptionRoot.NewExceptionRoot(); Assert.Fail("Exception didn't occur"); } catch (DataPortalException ex) { Assert.IsNull(ex.BusinessObject, "Business object shouldn't be returned"); Assert.AreEqual("Fail create", ex.GetBaseException().Message, "Base exception message incorrect"); Assert.IsTrue(ex.Message.StartsWith("DataPortal.Create failed"), "Exception message incorrect"); } Assert.AreEqual("create", ApplicationContext.GlobalContext["create"], "GlobalContext not preserved"); } #endregion #region FailFetchContext [TestMethod()] public void FailFetchContext() { ApplicationContext.GlobalContext.Clear(); ExceptionRoot root = null; try { root = ExceptionRoot.GetExceptionRoot("fail"); Assert.Fail("Exception didn't occur"); } catch (DataPortalException ex) { Assert.IsNull(ex.BusinessObject, "Business object shouldn't be returned"); Assert.AreEqual("Fail fetch", ex.GetBaseException().Message, "Base exception message incorrect"); Assert.IsTrue(ex.Message.StartsWith("DataPortal.Fetch failed"), "Exception message incorrect"); } catch (Exception ex) { Assert.Fail("Unexpected exception: " + ex.ToString()); } Assert.AreEqual("create", ApplicationContext.GlobalContext["create"], "GlobalContext not preserved"); } #endregion #region FailUpdateContext [TestMethod()] public void FailUpdateContext() { try { ApplicationContext.GlobalContext.Clear(); ApplicationContext.DataPortalReturnObjectOnException = true; ExceptionRoot root; try { root = ExceptionRoot.NewExceptionRoot(); Assert.Fail("Create exception didn't occur"); } catch (DataPortalException ex) { root = (ExceptionRoot)ex.BusinessObject; Assert.AreEqual("Fail create", ex.GetBaseException().Message, "Base exception message incorrect"); Assert.IsTrue(ex.Message.StartsWith("DataPortal.Create failed"), "Exception message incorrect"); } root.Data = "boom"; try { root = root.Save(); Assert.Fail("Insert exception didn't occur"); } catch (DataPortalException ex) { root = (ExceptionRoot)ex.BusinessObject; Assert.AreEqual("Fail insert", ex.GetBaseException().Message, "Base exception message incorrect"); Assert.IsTrue(ex.Message.StartsWith("DataPortal.Update failed"), "Exception message incorrect"); } Assert.AreEqual("boom", root.Data, "Business object not returned"); Assert.AreEqual("create", ApplicationContext.GlobalContext["create"], "GlobalContext not preserved"); } finally { ApplicationContext.DataPortalReturnObjectOnException = false; } } #endregion #region FailDeleteContext [TestMethod()] public void FailDeleteContext() { ApplicationContext.GlobalContext.Clear(); ApplicationContext.Clear(); ExceptionRoot root = null; try { ExceptionRoot.DeleteExceptionRoot("fail"); Assert.Fail("Exception didn't occur"); } catch (DataPortalException ex) { root = (ExceptionRoot)ex.BusinessObject; Assert.AreEqual("Fail delete", ex.GetBaseException().Message, "Base exception message incorrect"); Assert.IsTrue(ex.Message.StartsWith("DataPortal.Delete failed"), "Exception message incorrect"); } Assert.IsNull(root, "Business object returned"); Assert.AreEqual("create", ApplicationContext.GlobalContext["create"], "GlobalContext not preserved"); } #endregion [TestCleanup] public void ClearContextsAfterEachTest() { ApplicationContext.GlobalContext.Clear(); ApplicationContext.Clear(); } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2014-2016 FUJIWARA, Yusuke // // 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. // #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; #if UNITY using System.Collections; #endif // UNITY using System.Collections.Generic; #if UNITY using System.Reflection; #endif // UNITY #if FEATURE_TAP using System.Threading; using System.Threading.Tasks; #endif // FEATURE_TAP using MsgPack.Serialization.CollectionSerializers; namespace MsgPack.Serialization.DefaultSerializers { #if !UNITY /// <summary> /// Provides default implementation for <see cref="List{T}"/>. /// </summary> /// <typeparam name="T">The type of items of the <see cref="List{T}"/>.</typeparam> // ReSharper disable once InconsistentNaming [Preserve( AllMembers = true )] internal class System_Collections_Generic_List_1MessagePackSerializer<T> : MessagePackSerializer<List<T>>, ICollectionInstanceFactory { private readonly MessagePackSerializer<T> _itemSerializer; public System_Collections_Generic_List_1MessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema itemsSchema ) : base( ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { this._itemSerializer = ownerContext.GetSerializer<T>( itemsSchema ); } protected internal override void PackToCore( Packer packer, List<T> objectTree ) { PackerUnpackerExtensions.PackCollectionCore( packer, objectTree, this._itemSerializer ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override List<T> UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) { SerializationExceptions.ThrowIsNotArrayHeader( unpacker ); } var count = UnpackHelpers.GetItemsCount( unpacker ); var collection = new List<T>( count ); this.UnpackToCore( unpacker, collection, count ); return collection; } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void UnpackToCore( Unpacker unpacker, List<T> collection ) { if ( !unpacker.IsArrayHeader ) { SerializationExceptions.ThrowIsNotArrayHeader( unpacker ); } this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) ); } private void UnpackToCore( Unpacker unpacker, List<T> collection, int count ) { for ( int i = 0; i < count; i++ ) { if ( !unpacker.Read() ) { SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } if ( unpacker.IsCollectionHeader ) { using ( var subTreeUnpacker = unpacker.ReadSubtree() ) { collection.Add( this._itemSerializer.UnpackFrom( subTreeUnpacker ) ); } } else { collection.Add( this._itemSerializer.UnpackFrom( unpacker ) ); } } } public object CreateInstance( int initialCapacity ) { return new List<T>( initialCapacity ); } #if FEATURE_TAP protected internal override Task PackToAsyncCore( Packer packer, List<T> objectTree, CancellationToken cancellationToken ) { return PackerUnpackerExtensions.PackCollectionAsyncCore( packer, objectTree, this._itemSerializer, cancellationToken ); } protected internal override async Task<List<T>> UnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken ) { if ( !unpacker.IsArrayHeader ) { SerializationExceptions.ThrowIsNotArrayHeader( unpacker ); } var count = UnpackHelpers.GetItemsCount( unpacker ); var collection = new List<T>( count ); await this.UnpackToAsyncCore( unpacker, collection, count, cancellationToken ).ConfigureAwait( false ); return collection; } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal override Task UnpackToAsyncCore( Unpacker unpacker, List<T> collection, CancellationToken cancellationToken ) { if ( !unpacker.IsArrayHeader ) { SerializationExceptions.ThrowIsNotArrayHeader( unpacker ); } return this.UnpackToAsyncCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ), cancellationToken ); } private async Task UnpackToAsyncCore( Unpacker unpacker, List<T> collection, int count, CancellationToken cancellationToken ) { for ( int i = 0; i < count; i++ ) { if ( !await unpacker.ReadAsync( cancellationToken ).ConfigureAwait( false ) ) { SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } if ( unpacker.IsCollectionHeader ) { using ( var subTreeUnpacker = unpacker.ReadSubtree() ) { collection.Add( await this._itemSerializer.UnpackFromAsync( subTreeUnpacker, cancellationToken ).ConfigureAwait( false ) ); } } else { collection.Add( await this._itemSerializer.UnpackFromAsync( unpacker, cancellationToken ).ConfigureAwait( false ) ); } } } #endif // FEATURE_TAP } #else // ReSharper disable once InconsistentNaming internal class System_Collections_Generic_List_1MessagePackSerializer : NonGenericMessagePackSerializer, ICollectionInstanceFactory { private static readonly Type[] ConstructorWithCapacityParameterTypes = { typeof( int ) }; private readonly MessagePackSerializer _itemSerializer; private readonly ConstructorInfo _constructor; private readonly MethodInfo _add; public System_Collections_Generic_List_1MessagePackSerializer( SerializationContext ownerContext, Type targetType, CollectionTraits traits, PolymorphismSchema itemsSchema ) : base( ownerContext, targetType, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo ) { this._itemSerializer = ownerContext.GetSerializer( traits.ElementType, itemsSchema ); this._constructor = targetType.GetConstructor( ConstructorWithCapacityParameterTypes ); this._add = traits.AddMethod; } protected internal override void PackToCore( Packer packer, object objectTree ) { var asCollection = objectTree as ICollection; if ( asCollection == null ) { packer.PackNull(); return; } packer.PackArrayHeader( asCollection.Count ); foreach ( var item in asCollection ) { this._itemSerializer.PackTo( packer, item ); } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override object UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsArrayHeader ) { SerializationExceptions.ThrowIsNotArrayHeader( unpacker ); } var count = UnpackHelpers.GetItemsCount( unpacker ); var collection = this.CreateInstance( count ); this.UnpackToCore( unpacker, collection, count ); return collection; } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected internal override void UnpackToCore( Unpacker unpacker, object collection ) { if ( !unpacker.IsArrayHeader ) { SerializationExceptions.ThrowIsNotArrayHeader( unpacker ); } this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) ); } private void UnpackToCore( Unpacker unpacker, object collection, int count ) { for ( int i = 0; i < count; i++ ) { if ( !unpacker.Read() ) { SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker ); } if ( unpacker.IsCollectionHeader ) { using ( var subTreeUnpacker = unpacker.ReadSubtree() ) { this._add.InvokePreservingExceptionType( collection, this._itemSerializer.UnpackFrom( subTreeUnpacker ) ); } } else { this._add.InvokePreservingExceptionType( collection, this._itemSerializer.UnpackFrom( unpacker ) ); } } } public object CreateInstance( int initialCapacity ) { return this._constructor.InvokePreservingExceptionType( initialCapacity ); } } #endif // !UNITY }
#region BSD License /* Copyright (c) 2004 - 2008 Matthew Holmes ([email protected]), Dan Moorehead ([email protected]), Dave Hudson ([email protected]), C.J. Adams-Collier ([email protected]), 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. * The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion #region MIT X11 license /* Portions of this file authored by Lluis Sanchez Gual Copyright (C) 2006 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. */ #endregion using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Xsl; using System.Net; using System.Diagnostics; using Prebuild.Core.Attributes; using Prebuild.Core.Interfaces; using Prebuild.Core.Nodes; using Prebuild.Core.Utilities; namespace Prebuild.Core.Targets { public enum ClrVersion { Default, Net_1_1, Net_2_0 } public class SystemPackage { string name; string version; string description; string[] assemblies; bool isInternal; ClrVersion targetVersion; public void Initialize(string name, string version, string description, string[] assemblies, ClrVersion targetVersion, bool isInternal) { this.isInternal = isInternal; this.name = name; this.version = version; this.assemblies = assemblies; this.description = description; this.targetVersion = targetVersion; } public string Name { get { return name; } } public string Version { get { return version; } } public string Description { get { return description; } } public ClrVersion TargetVersion { get { return targetVersion; } } // The package is part of the mono SDK public bool IsCorePackage { get { return name == "mono"; } } // The package has been registered by an add-in, and is not installed // in the system. public bool IsInternalPackage { get { return isInternal; } } public string[] Assemblies { get { return assemblies; } } } /// <summary> /// /// </summary> [Target("autotools")] public class AutotoolsTarget : ITarget { #region Fields Kernel m_Kernel; XmlDocument autotoolsDoc; XmlUrlResolver xr; System.Security.Policy.Evidence e; readonly Dictionary<string, SystemPackage> assemblyPathToPackage = new Dictionary<string, SystemPackage>(); readonly Dictionary<string, string> assemblyFullNameToPath = new Dictionary<string, string>(); readonly Dictionary<string, SystemPackage> packagesHash = new Dictionary<string, SystemPackage>(); readonly List<SystemPackage> packages = new List<SystemPackage>(); #endregion #region Private Methods private static void mkdirDashP(string dirName) { DirectoryInfo di = new DirectoryInfo(dirName); if (di.Exists) return; string parentDirName = System.IO.Path.GetDirectoryName(dirName); DirectoryInfo parentDi = new DirectoryInfo(parentDirName); if (!parentDi.Exists) mkdirDashP(parentDirName); di.Create(); } private static void chkMkDir(string dirName) { System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(dirName); if (!di.Exists) di.Create(); } private void transformToFile(string filename, XsltArgumentList argList, string nodeName) { // Create an XslTransform for this file XslTransform templateTransformer = new XslTransform(); // Load up the template XmlNode templateNode = autotoolsDoc.SelectSingleNode(nodeName + "/*"); templateTransformer.Load(templateNode.CreateNavigator(), xr, e); // Create a writer for the transformed template XmlTextWriter templateWriter = new XmlTextWriter(filename, null); // Perform transformation, writing the file templateTransformer.Transform (m_Kernel.CurrentDoc, argList, templateWriter, xr); } static string NormalizeAsmName(string name) { int i = name.IndexOf(", PublicKeyToken=null"); if (i != -1) return name.Substring(0, i).Trim(); return name; } private void AddAssembly(string assemblyfile, SystemPackage package) { if (!File.Exists(assemblyfile)) return; try { System.Reflection.AssemblyName an = System.Reflection.AssemblyName.GetAssemblyName(assemblyfile); assemblyFullNameToPath[NormalizeAsmName(an.FullName)] = assemblyfile; assemblyPathToPackage[assemblyfile] = package; } catch { } } private static List<string> GetAssembliesWithLibInfo(string line, string file) { List<string> references = new List<string>(); List<string> libdirs = new List<string>(); List<string> retval = new List<string>(); foreach (string piece in line.Split(' ')) { if (piece.ToLower().Trim().StartsWith("/r:") || piece.ToLower().Trim().StartsWith("-r:")) { references.Add(ProcessPiece(piece.Substring(3).Trim(), file)); } else if (piece.ToLower().Trim().StartsWith("/lib:") || piece.ToLower().Trim().StartsWith("-lib:")) { libdirs.Add(ProcessPiece(piece.Substring(5).Trim(), file)); } } foreach (string refrnc in references) { foreach (string libdir in libdirs) { if (File.Exists(libdir + Path.DirectorySeparatorChar + refrnc)) { retval.Add(libdir + Path.DirectorySeparatorChar + refrnc); } } } return retval; } private static List<string> GetAssembliesWithoutLibInfo(string line, string file) { List<string> references = new List<string>(); foreach (string reference in line.Split(' ')) { if (reference.ToLower().Trim().StartsWith("/r:") || reference.ToLower().Trim().StartsWith("-r:")) { string final_ref = reference.Substring(3).Trim(); references.Add(ProcessPiece(final_ref, file)); } } return references; } private static string ProcessPiece(string piece, string pcfile) { int start = piece.IndexOf("${"); if (start == -1) return piece; int end = piece.IndexOf("}"); if (end == -1) return piece; string variable = piece.Substring(start + 2, end - start - 2); string interp = GetVariableFromPkgConfig(variable, Path.GetFileNameWithoutExtension(pcfile)); return ProcessPiece(piece.Replace("${" + variable + "}", interp), pcfile); } private static string GetVariableFromPkgConfig(string var, string pcfile) { ProcessStartInfo psi = new ProcessStartInfo("pkg-config"); psi.RedirectStandardOutput = true; psi.UseShellExecute = false; psi.Arguments = String.Format("--variable={0} {1}", var, pcfile); Process p = new Process(); p.StartInfo = psi; p.Start(); string ret = p.StandardOutput.ReadToEnd().Trim(); p.WaitForExit(); if (String.IsNullOrEmpty(ret)) return String.Empty; return ret; } private void ParsePCFile(string pcfile) { // Don't register the package twice string pname = Path.GetFileNameWithoutExtension(pcfile); if (packagesHash.ContainsKey(pname)) return; List<string> fullassemblies = null; string version = ""; string desc = ""; SystemPackage package = new SystemPackage(); using (StreamReader reader = new StreamReader(pcfile)) { string line; while ((line = reader.ReadLine()) != null) { string lowerLine = line.ToLower(); if (lowerLine.StartsWith("libs:") && lowerLine.IndexOf(".dll") != -1) { string choppedLine = line.Substring(5).Trim(); if (choppedLine.IndexOf("-lib:") != -1 || choppedLine.IndexOf("/lib:") != -1) { fullassemblies = GetAssembliesWithLibInfo(choppedLine, pcfile); } else { fullassemblies = GetAssembliesWithoutLibInfo(choppedLine, pcfile); } } else if (lowerLine.StartsWith("version:")) { // "version:".Length == 8 version = line.Substring(8).Trim(); } else if (lowerLine.StartsWith("description:")) { // "description:".Length == 12 desc = line.Substring(12).Trim(); } } } if (fullassemblies == null) return; foreach (string assembly in fullassemblies) { AddAssembly(assembly, package); } package.Initialize(pname, version, desc, fullassemblies.ToArray(), ClrVersion.Default, false); packages.Add(package); packagesHash[pname] = package; } void RegisterSystemAssemblies(string prefix, string version, ClrVersion ver) { SystemPackage package = new SystemPackage(); List<string> list = new List<string>(); string dir = Path.Combine(prefix, version); if (!Directory.Exists(dir)) { return; } foreach (string assembly in Directory.GetFiles(dir, "*.dll")) { AddAssembly(assembly, package); list.Add(assembly); } package.Initialize("mono", version, "The Mono runtime", list.ToArray(), ver, false); packages.Add(package); } void RunInitialization() { string versionDir; if (Environment.Version.Major == 1) { versionDir = "1.0"; } else { versionDir = "2.0"; } //Pull up assemblies from the installed mono system. string prefix = Path.GetDirectoryName(typeof(int).Assembly.Location); if (prefix.IndexOf(Path.Combine("mono", versionDir)) == -1) prefix = Path.Combine(prefix, "mono"); else prefix = Path.GetDirectoryName(prefix); RegisterSystemAssemblies(prefix, "1.0", ClrVersion.Net_1_1); RegisterSystemAssemblies(prefix, "2.0", ClrVersion.Net_2_0); string search_dirs = Environment.GetEnvironmentVariable("PKG_CONFIG_PATH"); string libpath = Environment.GetEnvironmentVariable("PKG_CONFIG_LIBPATH"); if (String.IsNullOrEmpty(libpath)) { string path_dirs = Environment.GetEnvironmentVariable("PATH"); foreach (string pathdir in path_dirs.Split(Path.PathSeparator)) { if (pathdir == null) continue; if (File.Exists(pathdir + Path.DirectorySeparatorChar + "pkg-config")) { libpath = Path.Combine(pathdir, ".."); libpath = Path.Combine(libpath, "lib"); libpath = Path.Combine(libpath, "pkgconfig"); break; } } } search_dirs += Path.PathSeparator + libpath; if (!string.IsNullOrEmpty(search_dirs)) { List<string> scanDirs = new List<string>(); foreach (string potentialDir in search_dirs.Split(Path.PathSeparator)) { if (!scanDirs.Contains(potentialDir)) scanDirs.Add(potentialDir); } foreach (string pcdir in scanDirs) { if (pcdir == null) continue; if (Directory.Exists(pcdir)) { foreach (string pcfile in Directory.GetFiles(pcdir, "*.pc")) { ParsePCFile(pcfile); } } } } } private void WriteCombine(SolutionNode solution) { #region "Create Solution directory if it doesn't exist" string solutionDir = Path.Combine(solution.FullPath, Path.Combine("autotools", solution.Name)); chkMkDir(solutionDir); #endregion #region "Write Solution-level files" XsltArgumentList argList = new XsltArgumentList(); argList.AddParam("solutionName", "", solution.Name); // $solutionDir is $rootDir/$solutionName/ transformToFile(Path.Combine(solutionDir, "configure.ac"), argList, "/Autotools/SolutionConfigureAc"); transformToFile(Path.Combine(solutionDir, "Makefile.am"), argList, "/Autotools/SolutionMakefileAm"); transformToFile(Path.Combine(solutionDir, "autogen.sh"), argList, "/Autotools/SolutionAutogenSh"); #endregion foreach (ProjectNode project in solution.ProjectsTableOrder) { m_Kernel.Log.Write(String.Format("Writing project: {0}", project.Name)); WriteProject(solution, project); } } private static string FindFileReference(string refName, ProjectNode project) { foreach (ReferencePathNode refPath in project.ReferencePaths) { string fullPath = Helper.MakeFilePath(refPath.Path, refName, "dll"); if (File.Exists(fullPath)) { return fullPath; } } return null; } /// <summary> /// Gets the XML doc file. /// </summary> /// <param name="project">The project.</param> /// <param name="conf">The conf.</param> /// <returns></returns> public static string GetXmlDocFile(ProjectNode project, ConfigurationNode conf) { if (conf == null) { throw new ArgumentNullException("conf"); } if (project == null) { throw new ArgumentNullException("project"); } string docFile = (string)conf.Options["XmlDocFile"]; // if(docFile != null && docFile.Length == 0)//default to assembly name if not specified // { // return Path.GetFileNameWithoutExtension(project.AssemblyName) + ".xml"; // } return docFile; } /// <summary> /// Normalizes the path. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> public static string NormalizePath(string path) { if (path == null) { return ""; } StringBuilder tmpPath; if (Core.Parse.Preprocessor.GetOS() == "Win32") { tmpPath = new StringBuilder(path.Replace('\\', '/')); tmpPath.Replace("/", @"\\"); } else { tmpPath = new StringBuilder(path.Replace('\\', '/')); tmpPath = tmpPath.Replace('/', Path.DirectorySeparatorChar); } return tmpPath.ToString(); } private void WriteProject(SolutionNode solution, ProjectNode project) { string solutionDir = Path.Combine(solution.FullPath, Path.Combine("autotools", solution.Name)); string projectDir = Path.Combine(solutionDir, project.Name); string projectVersion = project.Version; bool hasAssemblyConfig = false; chkMkDir(projectDir); List<string> compiledFiles = new List<string>(), contentFiles = new List<string>(), embeddedFiles = new List<string>(), binaryLibs = new List<string>(), pkgLibs = new List<string>(), systemLibs = new List<string>(), runtimeLibs = new List<string>(), extraDistFiles = new List<string>(), localCopyTargets = new List<string>(); // If there exists a .config file for this assembly, copy // it to the project folder // TODO: Support copying .config.osx files // TODO: support processing the .config file for native library deps string projectAssemblyName = project.Name; if (project.AssemblyName != null) projectAssemblyName = project.AssemblyName; if (File.Exists(Path.Combine(project.FullPath, projectAssemblyName) + ".dll.config")) { hasAssemblyConfig = true; System.IO.File.Copy(Path.Combine(project.FullPath, projectAssemblyName + ".dll.config"), Path.Combine(projectDir, projectAssemblyName + ".dll.config"), true); extraDistFiles.Add(project.AssemblyName + ".dll.config"); } foreach (ConfigurationNode conf in project.Configurations) { if (conf.Options.KeyFile != string.Empty) { // Copy snk file into the project's directory // Use the snk from the project directory directly string source = Path.Combine(project.FullPath, conf.Options.KeyFile); string keyFile = conf.Options.KeyFile; Regex re = new Regex(".*/"); keyFile = re.Replace(keyFile, ""); string dest = Path.Combine(projectDir, keyFile); // Tell the user if there's a problem copying the file try { mkdirDashP(System.IO.Path.GetDirectoryName(dest)); System.IO.File.Copy(source, dest, true); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } } // Copy compiled, embedded and content files into the project's directory foreach (string filename in project.Files) { string source = Path.Combine(project.FullPath, filename); string dest = Path.Combine(projectDir, filename); if (filename.Contains("AssemblyInfo.cs")) { // If we've got an AssemblyInfo.cs, pull the version number from it string[] sources = { source }; string[] args = { "" }; Microsoft.CSharp.CSharpCodeProvider cscp = new Microsoft.CSharp.CSharpCodeProvider(); string tempAssemblyFile = Path.Combine(Path.GetTempPath(), project.Name + "-temp.dll"); System.CodeDom.Compiler.CompilerParameters cparam = new System.CodeDom.Compiler.CompilerParameters(args, tempAssemblyFile); System.CodeDom.Compiler.CompilerResults cr = cscp.CompileAssemblyFromFile(cparam, sources); foreach (System.CodeDom.Compiler.CompilerError error in cr.Errors) Console.WriteLine("Error! '{0}'", error.ErrorText); try { string projectFullName = cr.CompiledAssembly.FullName; Regex verRegex = new Regex("Version=([\\d\\.]+)"); Match verMatch = verRegex.Match(projectFullName); if (verMatch.Success) projectVersion = verMatch.Groups[1].Value; }catch{ Console.WriteLine("Couldn't compile AssemblyInfo.cs"); } // Clean up the temp file try { if (File.Exists(tempAssemblyFile)) File.Delete(tempAssemblyFile); } catch { Console.WriteLine("Error! '{0}'", e); } } // Tell the user if there's a problem copying the file try { mkdirDashP(System.IO.Path.GetDirectoryName(dest)); System.IO.File.Copy(source, dest, true); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } switch (project.Files.GetBuildAction(filename)) { case BuildAction.Compile: compiledFiles.Add(filename); break; case BuildAction.Content: contentFiles.Add(filename); extraDistFiles.Add(filename); break; case BuildAction.EmbeddedResource: embeddedFiles.Add(filename); break; } } // Set up references for (int refNum = 0; refNum < project.References.Count; refNum++) { ReferenceNode refr = project.References[refNum]; Assembly refAssembly = Assembly.LoadWithPartialName(refr.Name); /* Determine which pkg-config (.pc) file refers to this assembly */ SystemPackage package = null; if (packagesHash.ContainsKey(refr.Name)) { package = packagesHash[refr.Name]; } else { string assemblyFullName = string.Empty; if (refAssembly != null) assemblyFullName = refAssembly.FullName; string assemblyFileName = string.Empty; if (assemblyFullName != string.Empty && assemblyFullNameToPath.ContainsKey(assemblyFullName) ) assemblyFileName = assemblyFullNameToPath[assemblyFullName]; if (assemblyFileName != string.Empty && assemblyPathToPackage.ContainsKey(assemblyFileName) ) package = assemblyPathToPackage[assemblyFileName]; } /* If we know the .pc file and it is not "mono" (already in the path), add a -pkg: argument */ if (package != null && package.Name != "mono" && !pkgLibs.Contains(package.Name) ) pkgLibs.Add(package.Name); string fileRef = FindFileReference(refr.Name, (ProjectNode)refr.Parent); if (refr.LocalCopy || solution.ProjectsTable.ContainsKey(refr.Name) || fileRef != null || refr.Path != null ) { /* Attempt to copy the referenced lib to the project's directory */ string filename = refr.Name + ".dll"; string source = filename; if (refr.Path != null) source = Path.Combine(refr.Path, source); source = Path.Combine(project.FullPath, source); string dest = Path.Combine(projectDir, filename); /* Since we depend on this binary dll to build, we * will add a compile- time dependency on the * copied dll, and add the dll to the list of * files distributed with this package */ binaryLibs.Add(refr.Name + ".dll"); extraDistFiles.Add(refr.Name + ".dll"); // TODO: Support copying .config.osx files // TODO: Support for determining native dependencies if (File.Exists(source + ".config")) { System.IO.File.Copy(source + ".config", Path.GetDirectoryName(dest), true); extraDistFiles.Add(refr.Name + ".dll.config"); } try { System.IO.File.Copy(source, dest, true); } catch (System.IO.IOException) { if (solution.ProjectsTable.ContainsKey(refr.Name)){ /* If an assembly is referenced, marked for * local copy, in the list of projects for * this solution, but does not exist, put a * target into the Makefile.am to build the * assembly and copy it to this project's * directory */ ProjectNode sourcePrj = ((solution.ProjectsTable[refr.Name])); string target = String.Format("{0}:\n" + "\t$(MAKE) -C ../{1}\n" + "\tln ../{2}/$@ $@\n", filename, sourcePrj.Name, sourcePrj.Name ); localCopyTargets.Add(target); } } } else if( !pkgLibs.Contains(refr.Name) ) { // Else, let's assume it's in the GAC or the lib path string assemName = string.Empty; int index = refr.Name.IndexOf(","); if (index > 0) assemName = refr.Name.Substring(0, index); else assemName = refr.Name; m_Kernel.Log.Write(String.Format( "Warning: Couldn't find an appropriate assembly " + "for reference:\n'{0}'", refr.Name )); systemLibs.Add(assemName); } } const string lineSep = " \\\n\t"; string compiledFilesString = string.Empty; if (compiledFiles.Count > 0) compiledFilesString = lineSep + string.Join(lineSep, compiledFiles.ToArray()); string embeddedFilesString = ""; if (embeddedFiles.Count > 0) embeddedFilesString = lineSep + string.Join(lineSep, embeddedFiles.ToArray()); string contentFilesString = ""; if (contentFiles.Count > 0) contentFilesString = lineSep + string.Join(lineSep, contentFiles.ToArray()); string extraDistFilesString = ""; if (extraDistFiles.Count > 0) extraDistFilesString = lineSep + string.Join(lineSep, extraDistFiles.ToArray()); string pkgLibsString = ""; if (pkgLibs.Count > 0) pkgLibsString = lineSep + string.Join(lineSep, pkgLibs.ToArray()); string binaryLibsString = ""; if (binaryLibs.Count > 0) binaryLibsString = lineSep + string.Join(lineSep, binaryLibs.ToArray()); string systemLibsString = ""; if (systemLibs.Count > 0) systemLibsString = lineSep + string.Join(lineSep, systemLibs.ToArray()); string localCopyTargetsString = ""; if (localCopyTargets.Count > 0) localCopyTargetsString = string.Join("\n", localCopyTargets.ToArray()); string monoPath = ""; foreach (string runtimeLib in runtimeLibs) { monoPath += ":`pkg-config --variable=libdir " + runtimeLib + "`"; } // Add the project name to the list of transformation // parameters XsltArgumentList argList = new XsltArgumentList(); argList.AddParam("projectName", "", project.Name); argList.AddParam("solutionName", "", solution.Name); argList.AddParam("assemblyName", "", projectAssemblyName); argList.AddParam("compiledFiles", "", compiledFilesString); argList.AddParam("embeddedFiles", "", embeddedFilesString); argList.AddParam("contentFiles", "", contentFilesString); argList.AddParam("extraDistFiles", "", extraDistFilesString); argList.AddParam("pkgLibs", "", pkgLibsString); argList.AddParam("binaryLibs", "", binaryLibsString); argList.AddParam("systemLibs", "", systemLibsString); argList.AddParam("monoPath", "", monoPath); argList.AddParam("localCopyTargets", "", localCopyTargetsString); argList.AddParam("projectVersion", "", projectVersion); argList.AddParam("hasAssemblyConfig", "", hasAssemblyConfig ? "true" : ""); // Transform the templates transformToFile(Path.Combine(projectDir, "configure.ac"), argList, "/Autotools/ProjectConfigureAc"); transformToFile(Path.Combine(projectDir, "Makefile.am"), argList, "/Autotools/ProjectMakefileAm"); transformToFile(Path.Combine(projectDir, "autogen.sh"), argList, "/Autotools/ProjectAutogenSh"); if (project.Type == Core.Nodes.ProjectType.Library) transformToFile(Path.Combine(projectDir, project.Name + ".pc.in"), argList, "/Autotools/ProjectPcIn"); if (project.Type == Core.Nodes.ProjectType.Exe || project.Type == Core.Nodes.ProjectType.WinExe) transformToFile(Path.Combine(projectDir, project.Name.ToLower() + ".in"), argList, "/Autotools/ProjectWrapperScriptIn"); } private void CleanProject(ProjectNode project) { m_Kernel.Log.Write("...Cleaning project: {0}", project.Name); string projectFile = Helper.MakeFilePath(project.FullPath, "Include", "am"); Helper.DeleteIfExists(projectFile); } private void CleanSolution(SolutionNode solution) { m_Kernel.Log.Write("Cleaning Autotools make files for", solution.Name); string slnFile = Helper.MakeFilePath(solution.FullPath, "Makefile", "am"); Helper.DeleteIfExists(slnFile); slnFile = Helper.MakeFilePath(solution.FullPath, "Makefile", "in"); Helper.DeleteIfExists(slnFile); slnFile = Helper.MakeFilePath(solution.FullPath, "configure", "ac"); Helper.DeleteIfExists(slnFile); slnFile = Helper.MakeFilePath(solution.FullPath, "configure"); Helper.DeleteIfExists(slnFile); slnFile = Helper.MakeFilePath(solution.FullPath, "Makefile"); Helper.DeleteIfExists(slnFile); foreach (ProjectNode project in solution.Projects) { CleanProject(project); } m_Kernel.Log.Write(""); } #endregion #region ITarget Members /// <summary> /// Writes the specified kern. /// </summary> /// <param name="kern">The kern.</param> public void Write(Kernel kern) { if (kern == null) { throw new ArgumentNullException("kern"); } m_Kernel = kern; m_Kernel.Log.Write("Parsing system pkg-config files"); RunInitialization(); const string streamName = "autotools.xml"; string fqStreamName = String.Format("Prebuild.data.{0}", streamName ); // Retrieve stream for the autotools template XML Stream autotoolsStream = Assembly.GetExecutingAssembly() .GetManifestResourceStream(fqStreamName); if(autotoolsStream == null) { /* * try without the default namespace prepended, in * case prebuild.exe assembly was compiled with * something other than Visual Studio .NET */ autotoolsStream = Assembly.GetExecutingAssembly() .GetManifestResourceStream(streamName); if(autotoolsStream == null){ string errStr = String.Format("Could not find embedded resource file:\n" + "'{0}' or '{1}'", streamName, fqStreamName ); m_Kernel.Log.Write(errStr); throw new System.Reflection.TargetException(errStr); } } // Create an XML URL Resolver with default credentials xr = new System.Xml.XmlUrlResolver(); xr.Credentials = CredentialCache.DefaultCredentials; // Create a default evidence - no need to limit access e = new System.Security.Policy.Evidence(); // Load the autotools XML autotoolsDoc = new XmlDocument(); autotoolsDoc.Load(autotoolsStream); /* rootDir is the filesystem location where the Autotools * build tree will be created - for now we'll make it * $PWD/autotools */ string pwd = Directory.GetCurrentDirectory(); //string pwd = System.Environment.GetEnvironmentVariable("PWD"); //if (pwd.Length != 0) //{ string rootDir = Path.Combine(pwd, "autotools"); //} //else //{ // pwd = Assembly.GetExecutingAssembly() //} chkMkDir(rootDir); foreach (SolutionNode solution in kern.Solutions) { m_Kernel.Log.Write(String.Format("Writing solution: {0}", solution.Name)); WriteCombine(solution); } m_Kernel = null; } /// <summary> /// Cleans the specified kern. /// </summary> /// <param name="kern">The kern.</param> public virtual void Clean(Kernel kern) { if (kern == null) { throw new ArgumentNullException("kern"); } m_Kernel = kern; foreach (SolutionNode sol in kern.Solutions) { CleanSolution(sol); } m_Kernel = null; } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get { return "autotools"; } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Newtonsoft.Json.Linq; using AutoRest.Core; using AutoRest.Core.Model; using AutoRest.Core.Utilities; using AutoRest.Core.Utilities.Collections; using AutoRest.Extensions; using AutoRest.Extensions.Azure; using AutoRest.Java.Azure.Model; using AutoRest.Java.Model; using static AutoRest.Core.Utilities.DependencyInjection; namespace AutoRest.Java.Azure { public class TransformerJva : TransformerJv, ITransformer<CodeModelJva> { /// <summary> /// A type-specific method for code model tranformation. /// Note: This is the method you want to override. /// </summary> /// <param name="codeModel"></param> /// <returns></returns> public override CodeModelJv TransformCodeModel(CodeModel cm) { var codeModel = cm as CodeModelJva; // we're guaranteed to be in our language-specific context here. Settings.Instance.AddCredentials = true; // This extension from general extensions must be run prior to Azure specific extensions. AzureExtensions.ProcessParameterizedHost(codeModel); AzureExtensions.ProcessClientRequestIdExtension(codeModel); AzureExtensions.UpdateHeadMethods(codeModel); AzureExtensions.ProcessGlobalParameters(codeModel); AzureExtensions.FlattenModels(codeModel); AzureExtensions.FlattenMethodParameters(codeModel); ParameterGroupExtensionHelper.AddParameterGroups(codeModel); AddLongRunningOperations(codeModel); AzureExtensions.AddAzureProperties(codeModel); AzureExtensions.SetDefaultResponses(codeModel); // set Parent on responses (required for pageable) foreach (MethodJva method in codeModel.Methods) { foreach (ResponseJva response in method.Responses.Values) { response.Parent = method; } (method.DefaultResponse as ResponseJva).Parent = method; method.ReturnTypeJva.Parent = method; } AzureExtensions.AddPageableMethod(codeModel); // pluralize method groups foreach (var mg in codeModel.Operations) { mg.Name.OnGet += name => name.IsNullOrEmpty() || name.EndsWith("s", StringComparison.OrdinalIgnoreCase) ? name : $"{name}s"; } NormalizePaginatedMethods(codeModel, codeModel.pageClasses); // param order (PATH first) foreach (MethodJva method in codeModel.Methods) { var ps = method.Parameters.ToList(); method.ClearParameters(); foreach (var p in ps.Where(x => x.Location == ParameterLocation.Path)) { method.Add(p); } foreach (var p in ps.Where(x => x.Location != ParameterLocation.Path)) { method.Add(p); } } return codeModel; } public static void AddLongRunningOperations(CodeModel codeModel) { if (codeModel == null) { throw new ArgumentNullException("codeModel"); } foreach (var operation in codeModel.Operations) { var methods = operation.Methods.ToArray(); operation.ClearMethods(); foreach (var method in methods) { operation.Add(method); if (true == method.Extensions.Get<bool>(AzureExtensions.LongRunningExtension)) { // copy the method var m = Duplicate(method); // change the name, remove the extension. m.Name = "Begin" + m.Name.ToPascalCase(); m.Extensions.Remove(AzureExtensions.LongRunningExtension); operation.Add(m); } } } } CodeModelJva ITransformer<CodeModelJva>.TransformCodeModel(CodeModel codeModel) { return this.TransformCodeModel(codeModel) as CodeModelJva; } /// <summary> /// Changes paginated method signatures to return Page type. /// </summary> /// <param name="serviceClient"></param> /// <param name="pageClasses"></param> public void NormalizePaginatedMethods(CodeModel serviceClient, IDictionary<KeyValuePair<string, string>, string> pageClasses) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } var convertedTypes = new Dictionary<IModelType, IModelType>(); foreach (MethodJva method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension))) { string nextLinkString; string pageClassName = GetPagingSetting(method.Extensions, pageClasses, out nextLinkString); if (string.IsNullOrEmpty(pageClassName)) { continue; } if (string.IsNullOrEmpty(nextLinkString)) { method.Extensions[AzureExtensions.PageableExtension] = null; } foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeTypeJva).Select(s => s.Key).ToArray()) { var compositType = (CompositeTypeJva)method.Responses[responseStatus].Body; var sequenceType = compositType.Properties.Select(p => p.ModelType).FirstOrDefault(t => t is SequenceTypeJva) as SequenceTypeJva; // if the type is a wrapper over page-able response if (sequenceType != null) { IModelType pagedResult; pagedResult = new SequenceTypeJva { ElementType = sequenceType.ElementType, PageImplType = pageClassName }; convertedTypes[method.Responses[responseStatus].Body] = pagedResult; var resp = New<Response>(pagedResult, method.Responses[responseStatus].Headers) as ResponseJva; resp.Parent = method; method.Responses[responseStatus] = resp; } } if (convertedTypes.ContainsKey(method.ReturnType.Body)) { var resp = New<Response>(convertedTypes[method.ReturnType.Body], method.ReturnType.Headers) as ResponseJva; resp.Parent = method; method.ReturnType = resp; } } SwaggerExtensions.RemoveUnreferencedTypes(serviceClient, new HashSet<string>(convertedTypes.Keys.Cast<CompositeTypeJva>().Select(t => t.Name.ToString()))); } public virtual void NormalizeODataMethods(CodeModel client) { if (client == null) { throw new ArgumentNullException("client"); } foreach (var method in client.Methods) { if (method.Extensions.ContainsKey(AzureExtensions.ODataExtension)) { var odataFilter = method.Parameters.FirstOrDefault(p => p.SerializedName.EqualsIgnoreCase("$filter") && (p.Location == ParameterLocation.Query) && p.ModelType is CompositeType); if (odataFilter == null) { continue; } // Remove all odata parameters method.Remove(source => (source.SerializedName.EqualsIgnoreCase("$filter") || source.SerializedName.EqualsIgnoreCase("$top") || source.SerializedName.EqualsIgnoreCase("$orderby") || source.SerializedName.EqualsIgnoreCase("$skip") || source.SerializedName.EqualsIgnoreCase("$expand")) && (source.Location == ParameterLocation.Query)); var odataQuery = New<Parameter>(new { SerializedName = "$filter", Name = "odataQuery", ModelType = New<CompositeType>($"Microsoft.Rest.Azure.OData.ODataQuery<{odataFilter.ModelType.Name}>"), Documentation = "OData parameters to apply to the operation.", Location = ParameterLocation.Query, odataFilter.IsRequired }); odataQuery.Extensions[AzureExtensions.ODataExtension] = method.Extensions[AzureExtensions.ODataExtension]; method.Insert(odataQuery); } } } private static string GetPagingSetting(Dictionary<string, object> extensions, IDictionary<KeyValuePair<string, string>, string> pageClasses, out string nextLinkName) { // default value nextLinkName = null; var ext = extensions[AzureExtensions.PageableExtension] as JContainer; if (ext == null) { return null; } nextLinkName = (string)ext["nextLinkName"]; var itemName = (string)ext["itemName"] ?? "value"; var keypair = new KeyValuePair<string, string>(nextLinkName, itemName); if (!pageClasses.ContainsKey(keypair)) { var className = (string)ext["className"]; if (string.IsNullOrEmpty(className)) { if (pageClasses.Count > 0) { className = string.Format(CultureInfo.InvariantCulture, "PageImpl{0}", pageClasses.Count); } else { className = "PageImpl"; } } pageClasses.Add(keypair, className); } return pageClasses[keypair]; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Drawing; using System.IO; using System.Linq; using Newtonsoft.Json; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Textures; using osu.Framework.Input; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Online.API.Requests; using osu.Game.Tournament.IPC; using osu.Game.Tournament.Models; using osu.Game.Users; using osuTK.Graphics; using osuTK.Input; namespace osu.Game.Tournament { [Cached(typeof(TournamentGameBase))] public abstract class TournamentGameBase : OsuGameBase { private const string bracket_filename = "bracket.json"; private LadderInfo ladder; private Storage storage; private DependencyContainer dependencies; private Bindable<Size> windowSize; private FileBasedIPC ipc; private Drawable heightWarning; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { return dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); } [BackgroundDependencyLoader] private void load(Storage storage, FrameworkConfigManager frameworkConfig) { Resources.AddStore(new DllResourceStore(typeof(TournamentGameBase).Assembly)); Textures.AddStore(new TextureLoaderStore(new ResourceStore<byte[]>(new StorageBackedResourceStore(storage)))); this.storage = storage; windowSize = frameworkConfig.GetBindable<Size>(FrameworkSetting.WindowedSize); windowSize.BindValueChanged(size => ScheduleAfterChildren(() => { var minWidth = (int)(size.NewValue.Height / 9f * 16 + 400); heightWarning.Alpha = size.NewValue.Width < minWidth ? 1 : 0; }), true); readBracket(); ladder.CurrentMatch.Value = ladder.Matches.FirstOrDefault(p => p.Current.Value); dependencies.CacheAs<MatchIPCInfo>(ipc = new FileBasedIPC()); Add(ipc); AddRange(new[] { new TourneyButton { Text = "Save Changes", Width = 140, Height = 50, Depth = float.MinValue, Anchor = Anchor.BottomRight, Origin = Anchor.BottomRight, Padding = new MarginPadding(10), Action = SaveChanges, }, heightWarning = new Container { Masking = true, CornerRadius = 5, Depth = float.MinValue, Anchor = Anchor.Centre, Origin = Anchor.Centre, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new Box { Colour = Color4.Red, RelativeSizeAxes = Axes.Both, }, new TournamentSpriteText { Text = "Please make the window wider", Font = OsuFont.Torus.With(weight: FontWeight.Bold), Colour = Color4.White, Padding = new MarginPadding(20) } } }, }); } private void readBracket() { if (storage.Exists(bracket_filename)) { using (Stream stream = storage.GetStream(bracket_filename, FileAccess.Read, FileMode.Open)) using (var sr = new StreamReader(stream)) ladder = JsonConvert.DeserializeObject<LadderInfo>(sr.ReadToEnd()); } if (ladder == null) ladder = new LadderInfo(); if (ladder.Ruleset.Value == null) ladder.Ruleset.Value = RulesetStore.AvailableRulesets.First(); Ruleset.BindTo(ladder.Ruleset); dependencies.Cache(ladder); bool addedInfo = false; // assign teams foreach (var match in ladder.Matches) { match.Team1.Value = ladder.Teams.FirstOrDefault(t => t.Acronym.Value == match.Team1Acronym); match.Team2.Value = ladder.Teams.FirstOrDefault(t => t.Acronym.Value == match.Team2Acronym); foreach (var conditional in match.ConditionalMatches) { conditional.Team1.Value = ladder.Teams.FirstOrDefault(t => t.Acronym.Value == conditional.Team1Acronym); conditional.Team2.Value = ladder.Teams.FirstOrDefault(t => t.Acronym.Value == conditional.Team2Acronym); conditional.Round.Value = match.Round.Value; } } // assign progressions foreach (var pair in ladder.Progressions) { var src = ladder.Matches.FirstOrDefault(p => p.ID == pair.SourceID); var dest = ladder.Matches.FirstOrDefault(p => p.ID == pair.TargetID); if (src == null) continue; if (dest != null) { if (pair.Losers) src.LosersProgression.Value = dest; else src.Progression.Value = dest; } } // link matches to rounds foreach (var round in ladder.Rounds) { foreach (var id in round.Matches) { var found = ladder.Matches.FirstOrDefault(p => p.ID == id); if (found != null) { found.Round.Value = round; if (round.StartDate.Value > found.Date.Value) found.Date.Value = round.StartDate.Value; } } } addedInfo |= addPlayers(); addedInfo |= addBeatmaps(); if (addedInfo) SaveChanges(); } /// <summary> /// Add missing player info based on user IDs. /// </summary> /// <returns></returns> private bool addPlayers() { bool addedInfo = false; foreach (var t in ladder.Teams) { foreach (var p in t.Players) { if (string.IsNullOrEmpty(p.Username) || p.Statistics == null) { PopulateUser(p); addedInfo = true; } } } return addedInfo; } /// <summary> /// Add missing beatmap info based on beatmap IDs /// </summary> private bool addBeatmaps() { bool addedInfo = false; foreach (var r in ladder.Rounds) { foreach (var b in r.Beatmaps.ToList()) { if (b.BeatmapInfo != null) continue; if (b.ID > 0) { var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = b.ID }); API.Perform(req); b.BeatmapInfo = req.Result?.ToBeatmap(RulesetStore); addedInfo = true; } if (b.BeatmapInfo == null) // if online population couldn't be performed, ensure we don't leave a null value behind r.Beatmaps.Remove(b); } } foreach (var t in ladder.Teams) { foreach (var s in t.SeedingResults) { foreach (var b in s.Beatmaps) { if (b.BeatmapInfo == null && b.ID > 0) { var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = b.ID }); req.Perform(API); b.BeatmapInfo = req.Result?.ToBeatmap(RulesetStore); addedInfo = true; } } } } return addedInfo; } public void PopulateUser(User user, Action success = null, Action failure = null) { var req = new GetUserRequest(user.Id, Ruleset.Value); req.Success += res => { user.Username = res.Username; user.Statistics = res.Statistics; user.Country = res.Country; user.Cover = res.Cover; success?.Invoke(); }; req.Failure += _ => { user.Id = 1; failure?.Invoke(); }; API.Queue(req); } protected override void LoadComplete() { MenuCursorContainer.Cursor.AlwaysPresent = true; // required for tooltip display MenuCursorContainer.Cursor.Alpha = 0; base.LoadComplete(); } protected virtual void SaveChanges() { foreach (var r in ladder.Rounds) r.Matches = ladder.Matches.Where(p => p.Round.Value == r).Select(p => p.ID).ToList(); ladder.Progressions = ladder.Matches.Where(p => p.Progression.Value != null).Select(p => new TournamentProgression(p.ID, p.Progression.Value.ID)).Concat( ladder.Matches.Where(p => p.LosersProgression.Value != null).Select(p => new TournamentProgression(p.ID, p.LosersProgression.Value.ID, true))) .ToList(); using (var stream = storage.GetStream(bracket_filename, FileAccess.Write, FileMode.Create)) using (var sw = new StreamWriter(stream)) { sw.Write(JsonConvert.SerializeObject(ladder, new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore, })); } } protected override UserInputManager CreateUserInputManager() => new TournamentInputManager(); private class TournamentInputManager : UserInputManager { protected override MouseButtonEventManager CreateButtonEventManagerFor(MouseButton button) { switch (button) { case MouseButton.Right: return new RightMouseManager(button); } return base.CreateButtonEventManagerFor(button); } private class RightMouseManager : MouseButtonEventManager { public RightMouseManager(MouseButton button) : base(button) { } public override bool EnableDrag => true; // allow right-mouse dragging for absolute scroll in scroll containers. public override bool EnableClick => true; public override bool ChangeFocusOnClick => false; } } } }
#region Apache License // // 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. // #endregion using System; using System.Collections; using System.Globalization; using System.Reflection; using System.Text; using Ctrip.Log4.Core; using Ctrip.Log4.Util.TypeConverters; namespace Ctrip.Log4.Util { /// <summary> /// A convenience class to convert property values to specific types. /// </summary> /// <remarks> /// <para> /// Utility functions for converting types and parsing values. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public sealed class OptionConverter { #region Private Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="OptionConverter" /> class. /// </summary> /// <remarks> /// <para> /// Uses a private access modifier to prevent instantiation of this class. /// </para> /// </remarks> private OptionConverter() { } #endregion Private Instance Constructors #region Public Static Methods // /// <summary> // /// Concatenates two string arrays. // /// </summary> // /// <param name="l">Left array.</param> // /// <param name="r">Right array.</param> // /// <returns>Array containing both left and right arrays.</returns> // public static string[] ConcatenateArrays(string[] l, string[] r) // { // return (string[])ConcatenateArrays(l, r); // } // /// <summary> // /// Concatenates two arrays. // /// </summary> // /// <param name="l">Left array</param> // /// <param name="r">Right array</param> // /// <returns>Array containing both left and right arrays.</returns> // public static Array ConcatenateArrays(Array l, Array r) // { // if (l == null) // { // throw new ArgumentNullException("l"); // } // if (r == null) // { // throw new ArgumentNullException("r"); // } // // int len = l.Length + r.Length; // Array a = Array.CreateInstance(l.GetType(), len); // // Array.Copy(l, 0, a, 0, l.Length); // Array.Copy(r, 0, a, l.Length, r.Length); // // return a; // } // /// <summary> // /// Converts string escape characters back to their correct values. // /// </summary> // /// <param name="s">String to convert.</param> // /// <returns>Converted result.</returns> // public static string ConvertSpecialChars(string s) // { // if (s == null) // { // throw new ArgumentNullException("s"); // } // char c; // int len = s.Length; // StringBuilder buf = new StringBuilder(len); // // int i = 0; // while(i < len) // { // c = s[i++]; // if (c == '\\') // { // c = s[i++]; // if (c == 'n') c = '\n'; // else if (c == 'r') c = '\r'; // else if (c == 't') c = '\t'; // else if (c == 'f') c = '\f'; // else if (c == '\b') c = '\b'; // else if (c == '\"') c = '\"'; // else if (c == '\'') c = '\''; // else if (c == '\\') c = '\\'; // } // buf.Append(c); // } // return buf.ToString(); // } /// <summary> /// Converts a string to a <see cref="bool" /> value. /// </summary> /// <param name="argValue">String to convert.</param> /// <param name="defaultValue">The default value.</param> /// <returns>The <see cref="bool" /> value of <paramref name="argValue" />.</returns> /// <remarks> /// <para> /// If <paramref name="argValue"/> is "true", then <c>true</c> is returned. /// If <paramref name="argValue"/> is "false", then <c>false</c> is returned. /// Otherwise, <paramref name="defaultValue"/> is returned. /// </para> /// </remarks> public static bool ToBoolean(string argValue, bool defaultValue) { if (argValue != null && argValue.Length > 0) { try { return bool.Parse(argValue); } catch(Exception e) { LogLog.Error(declaringType, "[" + argValue + "] is not in proper bool form.", e); } } return defaultValue; } // /// <summary> // /// Converts a string to an integer. // /// </summary> // /// <param name="argValue">String to convert.</param> // /// <param name="defaultValue">The default value.</param> // /// <returns>The <see cref="int" /> value of <paramref name="argValue" />.</returns> // /// <remarks> // /// <para> // /// <paramref name="defaultValue"/> is returned when <paramref name="argValue"/> // /// cannot be converted to a <see cref="int" /> value. // /// </para> // /// </remarks> // public static int ToInt(string argValue, int defaultValue) // { // if (argValue != null) // { // string s = argValue.Trim(); // try // { // return int.Parse(s, NumberFormatInfo.InvariantInfo); // } // catch (Exception e) // { // LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in proper int form.", e); // } // } // return defaultValue; // } /// <summary> /// Parses a file size into a number. /// </summary> /// <param name="argValue">String to parse.</param> /// <param name="defaultValue">The default value.</param> /// <returns>The <see cref="long" /> value of <paramref name="argValue" />.</returns> /// <remarks> /// <para> /// Parses a file size of the form: number[KB|MB|GB] into a /// long value. It is scaled with the appropriate multiplier. /// </para> /// <para> /// <paramref name="defaultValue"/> is returned when <paramref name="argValue"/> /// cannot be converted to a <see cref="long" /> value. /// </para> /// </remarks> public static long ToFileSize(string argValue, long defaultValue) { if (argValue == null) { return defaultValue; } string s = argValue.Trim().ToUpper(CultureInfo.InvariantCulture); long multiplier = 1; int index; if ((index = s.IndexOf("KB")) != -1) { multiplier = 1024; s = s.Substring(0, index); } else if ((index = s.IndexOf("MB")) != -1) { multiplier = 1024 * 1024; s = s.Substring(0, index); } else if ((index = s.IndexOf("GB")) != -1) { multiplier = 1024 * 1024 * 1024; s = s.Substring(0, index); } if (s != null) { // Try again to remove whitespace between the number and the size specifier s = s.Trim(); long longVal; if (SystemInfo.TryParse(s, out longVal)) { return longVal * multiplier; } else { LogLog.Error(declaringType, "OptionConverter: ["+ s +"] is not in the correct file size syntax."); } } return defaultValue; } /// <summary> /// Converts a string to an object. /// </summary> /// <param name="target">The target type to convert to.</param> /// <param name="txt">The string to convert to an object.</param> /// <returns> /// The object converted from a string or <c>null</c> when the /// conversion failed. /// </returns> /// <remarks> /// <para> /// Converts a string to an object. Uses the converter registry to try /// to convert the string value into the specified target type. /// </para> /// </remarks> public static object ConvertStringTo(Type target, string txt) { if (target == null) { throw new ArgumentNullException("target"); } // If we want a string we already have the correct type if (typeof(string) == target || typeof(object) == target) { return txt; } // First lets try to find a type converter IConvertFrom typeConverter = ConverterRegistry.GetConvertFrom(target); if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string))) { // Found appropriate converter return typeConverter.ConvertFrom(txt); } else { if (target.IsEnum) { // Target type is an enum. // Use the Enum.Parse(EnumType, string) method to get the enum value return ParseEnum(target, txt, true); } else { // We essentially make a guess that to convert from a string // to an arbitrary type T there will be a static method defined on type T called Parse // that will take an argument of type string. i.e. T.Parse(string)->T we call this // method to convert the string to the type required by the property. System.Reflection.MethodInfo meth = target.GetMethod("Parse", new Type[] {typeof(string)}); if (meth != null) { // Call the Parse method return meth.Invoke(null, BindingFlags.InvokeMethod, null, new object[] {txt}, CultureInfo.InvariantCulture); } else { // No Parse() method found. } } } return null; } // /// <summary> // /// Looks up the <see cref="IConvertFrom"/> for the target type. // /// </summary> // /// <param name="target">The type to lookup the converter for.</param> // /// <returns>The converter for the specified type.</returns> // public static IConvertFrom GetTypeConverter(Type target) // { // IConvertFrom converter = ConverterRegistry.GetConverter(target); // if (converter == null) // { // throw new InvalidOperationException("No type converter defined for [" + target + "]"); // } // return converter; // } /// <summary> /// Checks if there is an appropriate type conversion from the source type to the target type. /// </summary> /// <param name="sourceType">The type to convert from.</param> /// <param name="targetType">The type to convert to.</param> /// <returns><c>true</c> if there is a conversion from the source type to the target type.</returns> /// <remarks> /// Checks if there is an appropriate type conversion from the source type to the target type. /// <para> /// </para> /// </remarks> public static bool CanConvertTypeTo(Type sourceType, Type targetType) { if (sourceType == null || targetType == null) { return false; } // Check if we can assign directly from the source type to the target type if (targetType.IsAssignableFrom(sourceType)) { return true; } // Look for a To converter IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType); if (tcSource != null) { if (tcSource.CanConvertTo(targetType)) { return true; } } // Look for a From converter IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType); if (tcTarget != null) { if (tcTarget.CanConvertFrom(sourceType)) { return true; } } return false; } /// <summary> /// Converts an object to the target type. /// </summary> /// <param name="sourceInstance">The object to convert to the target type.</param> /// <param name="targetType">The type to convert to.</param> /// <returns>The converted object.</returns> /// <remarks> /// <para> /// Converts an object to the target type. /// </para> /// </remarks> public static object ConvertTypeTo(object sourceInstance, Type targetType) { Type sourceType = sourceInstance.GetType(); // Check if we can assign directly from the source type to the target type if (targetType.IsAssignableFrom(sourceType)) { return sourceInstance; } // Look for a TO converter IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType); if (tcSource != null) { if (tcSource.CanConvertTo(targetType)) { return tcSource.ConvertTo(sourceInstance, targetType); } } // Look for a FROM converter IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType); if (tcTarget != null) { if (tcTarget.CanConvertFrom(sourceType)) { return tcTarget.ConvertFrom(sourceInstance); } } throw new ArgumentException("Cannot convert source object [" + sourceInstance.ToString() + "] to target type [" + targetType.Name + "]", "sourceInstance"); } // /// <summary> // /// Finds the value corresponding to <paramref name="key"/> in // /// <paramref name="props"/> and then perform variable substitution // /// on the found value. // /// </summary> // /// <param name="key">The key to lookup.</param> // /// <param name="props">The association to use for lookups.</param> // /// <returns>The substituted result.</returns> // public static string FindAndSubst(string key, System.Collections.IDictionary props) // { // if (props == null) // { // throw new ArgumentNullException("props"); // } // // string v = props[key] as string; // if (v == null) // { // return null; // } // // try // { // return SubstituteVariables(v, props); // } // catch(Exception e) // { // LogLog.Error(declaringType, "OptionConverter: Bad option value [" + v + "].", e); // return v; // } // } /// <summary> /// Instantiates an object given a class name. /// </summary> /// <param name="className">The fully qualified class name of the object to instantiate.</param> /// <param name="superClass">The class to which the new object should belong.</param> /// <param name="defaultValue">The object to return in case of non-fulfillment.</param> /// <returns> /// An instance of the <paramref name="className"/> or <paramref name="defaultValue"/> /// if the object could not be instantiated. /// </returns> /// <remarks> /// <para> /// Checks that the <paramref name="className"/> is a subclass of /// <paramref name="superClass"/>. If that test fails or the object could /// not be instantiated, then <paramref name="defaultValue"/> is returned. /// </para> /// </remarks> public static object InstantiateByClassName(string className, Type superClass, object defaultValue) { if (className != null) { try { Type classObj = SystemInfo.GetTypeFromString(className, true, true); if (!superClass.IsAssignableFrom(classObj)) { LogLog.Error(declaringType, "OptionConverter: A [" + className + "] object is not assignable to a [" + superClass.FullName + "] variable."); return defaultValue; } return Activator.CreateInstance(classObj); } catch (Exception e) { LogLog.Error(declaringType, "Could not instantiate class [" + className + "].", e); } } return defaultValue; } /// <summary> /// Performs variable substitution in string <paramref name="value"/> from the /// values of keys found in <paramref name="props"/>. /// </summary> /// <param name="value">The string on which variable substitution is performed.</param> /// <param name="props">The dictionary to use to lookup variables.</param> /// <returns>The result of the substitutions.</returns> /// <remarks> /// <para> /// The variable substitution delimiters are <b>${</b> and <b>}</b>. /// </para> /// <para> /// For example, if props contains <c>key=value</c>, then the call /// </para> /// <para> /// <code lang="C#"> /// string s = OptionConverter.SubstituteVariables("Value of key is ${key}."); /// </code> /// </para> /// <para> /// will set the variable <c>s</c> to "Value of key is value.". /// </para> /// <para> /// If no value could be found for the specified key, then substitution /// defaults to an empty string. /// </para> /// <para> /// For example, if system properties contains no value for the key /// "nonExistentKey", then the call /// </para> /// <para> /// <code lang="C#"> /// string s = OptionConverter.SubstituteVariables("Value of nonExistentKey is [${nonExistentKey}]"); /// </code> /// </para> /// <para> /// will set <s>s</s> to "Value of nonExistentKey is []". /// </para> /// <para> /// An Exception is thrown if <paramref name="value"/> contains a start /// delimiter "${" which is not balanced by a stop delimiter "}". /// </para> /// </remarks> public static string SubstituteVariables(string value, System.Collections.IDictionary props) { StringBuilder buf = new StringBuilder(); int i = 0; int j, k; while(true) { j = value.IndexOf(DELIM_START, i); if (j == -1) { if (i == 0) { return value; } else { buf.Append(value.Substring(i, value.Length - i)); return buf.ToString(); } } else { buf.Append(value.Substring(i, j - i)); k = value.IndexOf(DELIM_STOP, j); if (k == -1) { throw new LogException("[" + value + "] has no closing brace. Opening brace at position [" + j + "]"); } else { j += DELIM_START_LEN; string key = value.Substring(j, k - j); string replacement = props[key] as string; if (replacement != null) { buf.Append(replacement); } i = k + DELIM_STOP_LEN; } } } } #endregion Public Static Methods #region Private Static Methods /// <summary> /// Converts the string representation of the name or numeric value of one or /// more enumerated constants to an equivalent enumerated object. /// </summary> /// <param name="enumType">The type to convert to.</param> /// <param name="value">The enum string value.</param> /// <param name="ignoreCase">If <c>true</c>, ignore case; otherwise, regard case.</param> /// <returns>An object of type <paramref name="enumType" /> whose value is represented by <paramref name="value" />.</returns> private static object ParseEnum(System.Type enumType, string value, bool ignoreCase) { #if !NETCF return Enum.Parse(enumType, value, ignoreCase); #else FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); string[] names = value.Split(new char[] {','}); for (int i = 0; i < names.Length; ++i) { names[i] = names [i].Trim(); } long retVal = 0; try { // Attempt to convert to numeric type return Enum.ToObject(enumType, Convert.ChangeType(value, typeof(long), CultureInfo.InvariantCulture)); } catch {} foreach (string name in names) { bool found = false; foreach(FieldInfo field in fields) { if (String.Compare(name, field.Name, ignoreCase) == 0) { retVal |= ((IConvertible) field.GetValue(null)).ToInt64(CultureInfo.InvariantCulture); found = true; break; } } if (!found) { throw new ArgumentException("Failed to lookup member [" + name + "] from Enum type [" + enumType.Name + "]"); } } return Enum.ToObject(enumType, retVal); #endif } #endregion Private Static Methods #region Private Static Fields /// <summary> /// The fully qualified type of the OptionConverter class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(OptionConverter); private const string DELIM_START = "${"; private const char DELIM_STOP = '}'; private const int DELIM_START_LEN = 2; private const int DELIM_STOP_LEN = 1; #endregion Private Static Fields } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.XPath; namespace MS.Internal.Xml.Cache { /// <summary> /// This is the default XPath/XQuery data model cache implementation. It will be used whenever /// the user does not supply his own XPathNavigator implementation. /// </summary> internal sealed class XPathDocumentNavigator : XPathNavigator, IXmlLineInfo { private XPathNode[] _pageCurrent; private XPathNode[] _pageParent; private int _idxCurrent; private int _idxParent; private string _atomizedLocalName; //----------------------------------------------- // Constructors //----------------------------------------------- /// <summary> /// Create a new navigator positioned on the specified current node. If the current node is a namespace or a collapsed /// text node, then the parent is a virtualized parent (may be different than .Parent on the current node). /// </summary> public XPathDocumentNavigator(XPathNode[] pageCurrent, int idxCurrent, XPathNode[] pageParent, int idxParent) { Debug.Assert(pageCurrent != null && idxCurrent != 0); Debug.Assert((pageParent == null) == (idxParent == 0)); _pageCurrent = pageCurrent; _pageParent = pageParent; _idxCurrent = idxCurrent; _idxParent = idxParent; } /// <summary> /// Copy constructor. /// </summary> public XPathDocumentNavigator(XPathDocumentNavigator nav) : this(nav._pageCurrent, nav._idxCurrent, nav._pageParent, nav._idxParent) { _atomizedLocalName = nav._atomizedLocalName; } //----------------------------------------------- // XPathItem //----------------------------------------------- /// <summary> /// Get the string value of the current node, computed using data model dm:string-value rules. /// If the node has a typed value, return the string representation of the value. If the node /// is not a parent type (comment, text, pi, etc.), get its simple text value. Otherwise, /// concatenate all text node descendants of the current node. /// </summary> public override string Value { get { string value; XPathNode[] page, pageEnd; int idx, idxEnd; // Try to get the pre-computed string value of the node value = _pageCurrent[_idxCurrent].Value; if (value != null) return value; #if DEBUG switch (this.pageCurrent[this.idxCurrent].NodeType) { case XPathNodeType.Namespace: case XPathNodeType.Attribute: case XPathNodeType.Comment: case XPathNodeType.ProcessingInstruction: Debug.Assert(false, "ReadStringValue() should have taken care of these node types."); break; case XPathNodeType.Text: Debug.Assert(this.idxParent != 0 && this.pageParent[this.idxParent].HasCollapsedText, "ReadStringValue() should have taken care of anything but collapsed text."); break; } #endif // If current node is collapsed text, then parent element has a simple text value if (_idxParent != 0) { Debug.Assert(_pageCurrent[_idxCurrent].NodeType == XPathNodeType.Text); return _pageParent[_idxParent].Value; } // Must be node with complex content, so concatenate the string values of all text descendants string s = string.Empty; StringBuilder bldr = null; // Get all text nodes which follow the current node in document order, but which are still descendants page = pageEnd = _pageCurrent; idx = idxEnd = _idxCurrent; if (!XPathNodeHelper.GetNonDescendant(ref pageEnd, ref idxEnd)) { pageEnd = null; idxEnd = 0; } while (XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd)) { Debug.Assert(page[idx].NodeType == XPathNodeType.Element || page[idx].IsText); if (s.Length == 0) { s = page[idx].Value; } else { if (bldr == null) { bldr = new StringBuilder(); bldr.Append(s); } bldr.Append(page[idx].Value); } } return (bldr != null) ? bldr.ToString() : s; } } //----------------------------------------------- // XPathNavigator //----------------------------------------------- /// <summary> /// Create a copy of this navigator, positioned to the same node in the tree. /// </summary> public override XPathNavigator Clone() { return new XPathDocumentNavigator(_pageCurrent, _idxCurrent, _pageParent, _idxParent); } /// <summary> /// Get the XPath node type of the current node. /// </summary> public override XPathNodeType NodeType { get { return _pageCurrent[_idxCurrent].NodeType; } } /// <summary> /// Get the local name portion of the current node's name. /// </summary> public override string LocalName { get { return _pageCurrent[_idxCurrent].LocalName; } } /// <summary> /// Get the namespace portion of the current node's name. /// </summary> public override string NamespaceURI { get { return _pageCurrent[_idxCurrent].NamespaceUri; } } /// <summary> /// Get the name of the current node. /// </summary> public override string Name { get { return _pageCurrent[_idxCurrent].Name; } } /// <summary> /// Get the prefix portion of the current node's name. /// </summary> public override string Prefix { get { return _pageCurrent[_idxCurrent].Prefix; } } /// <summary> /// Get the base URI of the current node. /// </summary> public override string BaseURI { get { XPathNode[] page; int idx; if (_idxParent != 0) { // Get BaseUri of parent for attribute, namespace, and collapsed text nodes page = _pageParent; idx = _idxParent; } else { page = _pageCurrent; idx = _idxCurrent; } do { switch (page[idx].NodeType) { case XPathNodeType.Element: case XPathNodeType.Root: case XPathNodeType.ProcessingInstruction: // BaseUri is always stored with Elements, Roots, and PIs return page[idx].BaseUri; } // Get BaseUri of parent idx = page[idx].GetParent(out page); } while (idx != 0); return string.Empty; } } /// <summary> /// Return true if this is an element which used a shortcut tag in its Xml 1.0 serialized form. /// </summary> public override bool IsEmptyElement { get { return _pageCurrent[_idxCurrent].AllowShortcutTag; } } /// <summary> /// Return the xml name table which was used to atomize all prefixes, local-names, and /// namespace uris in the document. /// </summary> public override XmlNameTable NameTable { get { return _pageCurrent[_idxCurrent].Document.NameTable; } } /// <summary> /// Position the navigator on the first attribute of the current node and return true. If no attributes /// can be found, return false. /// </summary> public override bool MoveToFirstAttribute() { XPathNode[] page = _pageCurrent; int idx = _idxCurrent; if (XPathNodeHelper.GetFirstAttribute(ref _pageCurrent, ref _idxCurrent)) { // Save element parent in order to make node-order comparison simpler _pageParent = page; _idxParent = idx; return true; } return false; } /// <summary> /// If positioned on an attribute, move to its next sibling attribute. If no attributes can be found, /// return false. /// </summary> public override bool MoveToNextAttribute() { return XPathNodeHelper.GetNextAttribute(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// True if the current node has one or more attributes. /// </summary> public override bool HasAttributes { get { return _pageCurrent[_idxCurrent].HasAttribute; } } /// <summary> /// Position the navigator on the attribute with the specified name and return true. If no matching /// attribute can be found, return false. Don't assume the name parts are atomized with respect /// to this document. /// </summary> public override bool MoveToAttribute(string localName, string namespaceURI) { XPathNode[] page = _pageCurrent; int idx = _idxCurrent; if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; if (XPathNodeHelper.GetAttribute(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI)) { // Save element parent in order to make node-order comparison simpler _pageParent = page; _idxParent = idx; return true; } return false; } /// <summary> /// Position the navigator on the namespace within the specified scope. If no matching namespace /// can be found, return false. /// </summary> public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) { XPathNode[] page; int idx; if (namespaceScope == XPathNamespaceScope.Local) { // Get local namespaces only idx = XPathNodeHelper.GetLocalNamespaces(_pageCurrent, _idxCurrent, out page); } else { // Get all in-scope namespaces idx = XPathNodeHelper.GetInScopeNamespaces(_pageCurrent, _idxCurrent, out page); } while (idx != 0) { // Don't include the xmlns:xml namespace node if scope is ExcludeXml if (namespaceScope != XPathNamespaceScope.ExcludeXml || !page[idx].IsXmlNamespaceNode) { _pageParent = _pageCurrent; _idxParent = _idxCurrent; _pageCurrent = page; _idxCurrent = idx; return true; } // Skip past xmlns:xml idx = page[idx].GetSibling(out page); } return false; } /// <summary> /// Position the navigator on the next namespace within the specified scope. If no matching namespace /// can be found, return false. /// </summary> public override bool MoveToNextNamespace(XPathNamespaceScope scope) { XPathNode[] page = _pageCurrent, pageParent; int idx = _idxCurrent, idxParent; // If current node is not a namespace node, return false if (page[idx].NodeType != XPathNodeType.Namespace) return false; while (true) { // Get next namespace sibling idx = page[idx].GetSibling(out page); // If there are no more nodes, return false if (idx == 0) return false; switch (scope) { case XPathNamespaceScope.Local: // Once parent changes, there are no longer any local namespaces idxParent = page[idx].GetParent(out pageParent); if (idxParent != _idxParent || (object)pageParent != (object)_pageParent) return false; break; case XPathNamespaceScope.ExcludeXml: // If node is xmlns:xml, then skip it if (page[idx].IsXmlNamespaceNode) continue; break; } // Found a matching next namespace node, so return it break; } _pageCurrent = page; _idxCurrent = idx; return true; } /// <summary> /// If the current node is an attribute or namespace (not content), return false. Otherwise, /// move to the next content node. Return false if there are no more content nodes. /// </summary> public override bool MoveToNext() { return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// If the current node is an attribute or namespace (not content), return false. Otherwise, /// move to the previous (sibling) content node. Return false if there are no previous content nodes. /// </summary> public override bool MoveToPrevious() { // If parent exists, then this is a namespace, an attribute, or a collapsed text node, all of which do // not have previous siblings. if (_idxParent != 0) return false; return XPathNodeHelper.GetPreviousContentSibling(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Move to the first content-typed child of the current node. Return false if the current /// node has no content children. /// </summary> public override bool MoveToFirstChild() { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Virtualize collapsed text nodes _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Position the navigator on the parent of the current node. If the current node has no parent, /// return false. /// </summary> public override bool MoveToParent() { if (_idxParent != 0) { // 1. For attribute nodes, element parent is always stored in order to make node-order // comparison simpler. // 2. For namespace nodes, parent is always stored in navigator in order to virtualize // XPath 1.0 namespaces. // 3. For collapsed text nodes, element parent is always stored in navigator. Debug.Assert(_pageParent != null); _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetParent(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Position this navigator to the same position as the "other" navigator. If the "other" navigator /// is not of the same type as this navigator, then return false. /// </summary> public override bool MoveTo(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { _pageCurrent = that._pageCurrent; _idxCurrent = that._idxCurrent; _pageParent = that._pageParent; _idxParent = that._idxParent; return true; } return false; } /// <summary> /// Position to the navigator to the element whose id is equal to the specified "id" string. /// </summary> public override bool MoveToId(string id) { XPathNode[] page; int idx; idx = _pageCurrent[_idxCurrent].Document.LookupIdElement(id, out page); if (idx != 0) { // Move to ID element and clear parent state Debug.Assert(page[idx].NodeType == XPathNodeType.Element); _pageCurrent = page; _idxCurrent = idx; _pageParent = null; _idxParent = 0; return true; } return false; } /// <summary> /// Returns true if this navigator is positioned to the same node as the "other" navigator. Returns false /// if not, or if the "other" navigator is not the same type as this navigator. /// </summary> public override bool IsSamePosition(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { return _idxCurrent == that._idxCurrent && _pageCurrent == that._pageCurrent && _idxParent == that._idxParent && _pageParent == that._pageParent; } return false; } /// <summary> /// Returns true if the current node has children. /// </summary> public override bool HasChildren { get { return _pageCurrent[_idxCurrent].HasContentChild; } } /// <summary> /// Position the navigator on the root node of the current document. /// </summary> public override void MoveToRoot() { if (_idxParent != 0) { // Clear parent state _pageParent = null; _idxParent = 0; } _idxCurrent = _pageCurrent[_idxCurrent].GetRoot(out _pageCurrent); } /// <summary> /// Move to the first element child of the current node with the specified name. Return false /// if the current node has no matching element children. /// </summary> public override bool MoveToChild(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; return XPathNodeHelper.GetElementChild(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the first element sibling of the current node with the specified name. Return false /// if the current node has no matching element siblings. /// </summary> public override bool MoveToNext(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; return XPathNodeHelper.GetElementSibling(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the first content child of the current node with the specified type. Return false /// if the current node has no matching children. /// </summary> public override bool MoveToChild(XPathNodeType type) { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Only XPathNodeType.Text and XPathNodeType.All matches collapsed text node if (type != XPathNodeType.Text && type != XPathNodeType.All) return false; // Virtualize collapsed text nodes _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent, type); } /// <summary> /// Move to the first content sibling of the current node with the specified type. Return false /// if the current node has no matching siblings. /// </summary> public override bool MoveToNext(XPathNodeType type) { return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent, type); } /// <summary> /// Move to the next element that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered) /// 3. Has the specified QName /// Return false if the current node has no matching following elements. /// </summary> public override bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end) { XPathNode[] pageEnd; int idxEnd; if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; // Get node on which scan ends (null if rest of document should be scanned) idxEnd = GetFollowingEnd(end as XPathDocumentNavigator, false, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { if (!XPathNodeHelper.GetElementFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI)) return false; _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetElementFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the next node that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered) /// 3. Has the specified XPathNodeType /// Return false if the current node has no matching following nodes. /// </summary> public override bool MoveToFollowing(XPathNodeType type, XPathNavigator end) { XPathDocumentNavigator endTiny = end as XPathDocumentNavigator; XPathNode[] page, pageEnd; int idx, idxEnd; // If searching for text, make sure to handle collapsed text nodes correctly if (type == XPathNodeType.Text || type == XPathNodeType.All) { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Positioned on an element with collapsed text, so return the virtual text node, assuming it's before "end" if (endTiny != null && _idxCurrent == endTiny._idxParent && _pageCurrent == endTiny._pageParent) { // "end" is positioned to a virtual attribute, namespace, or text node return false; } _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } if (type == XPathNodeType.Text) { // Get node on which scan ends (null if rest of document should be scanned, parent if positioned on virtual node) idxEnd = GetFollowingEnd(endTiny, true, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { page = _pageParent; idx = _idxParent; } else { page = _pageCurrent; idx = _idxCurrent; } // If ending node is a virtual node, and current node is its parent, then we're done if (endTiny != null && endTiny._idxParent != 0 && idx == idxEnd && page == pageEnd) return false; // Get all virtual (collapsed) and physical text nodes which follow the current node if (!XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd)) return false; if (page[idx].NodeType == XPathNodeType.Element) { // Virtualize collapsed text nodes Debug.Assert(page[idx].HasCollapsedText); _idxCurrent = page[idx].Document.GetCollapsedTextNode(out _pageCurrent); _pageParent = page; _idxParent = idx; } else { // Physical text node Debug.Assert(page[idx].IsText); _pageCurrent = page; _idxCurrent = idx; _pageParent = null; _idxParent = 0; } return true; } } // Get node on which scan ends (null if rest of document should be scanned, parent + 1 if positioned on virtual node) idxEnd = GetFollowingEnd(endTiny, false, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { if (!XPathNodeHelper.GetContentFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, type)) return false; _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetContentFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, type); } /// <summary> /// Return an iterator that ranges over all children of the current node that match the specified XPathNodeType. /// </summary> public override XPathNodeIterator SelectChildren(XPathNodeType type) { return new XPathDocumentKindChildIterator(this, type); } /// <summary> /// Return an iterator that ranges over all children of the current node that match the specified QName. /// </summary> public override XPathNodeIterator SelectChildren(string name, string namespaceURI) { // If local name is wildcard, then call XPathNavigator.SelectChildren if (name == null || name.Length == 0) return base.SelectChildren(name, namespaceURI); return new XPathDocumentElementChildIterator(this, name, namespaceURI); } /// <summary> /// Return an iterator that ranges over all descendants of the current node that match the specified /// XPathNodeType. If matchSelf is true, then also perform the match on the current node. /// </summary> public override XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf) { return new XPathDocumentKindDescendantIterator(this, type, matchSelf); } /// <summary> /// Return an iterator that ranges over all descendants of the current node that match the specified /// QName. If matchSelf is true, then also perform the match on the current node. /// </summary> public override XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf) { // If local name is wildcard, then call XPathNavigator.SelectDescendants if (name == null || name.Length == 0) return base.SelectDescendants(name, namespaceURI, matchSelf); return new XPathDocumentElementDescendantIterator(this, name, namespaceURI, matchSelf); } /// <summary> /// Returns: /// XmlNodeOrder.Unknown -- This navigator and the "other" navigator are not of the same type, or the /// navigator's are not positioned on nodes in the same document. /// XmlNodeOrder.Before -- This navigator's current node is before the "other" navigator's current node /// in document order. /// XmlNodeOrder.After -- This navigator's current node is after the "other" navigator's current node /// in document order. /// XmlNodeOrder.Same -- This navigator is positioned on the same node as the "other" navigator. /// </summary> public override XmlNodeOrder ComparePosition(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { XPathDocument thisDoc = _pageCurrent[_idxCurrent].Document; XPathDocument thatDoc = that._pageCurrent[that._idxCurrent].Document; if ((object)thisDoc == (object)thatDoc) { int locThis = GetPrimaryLocation(); int locThat = that.GetPrimaryLocation(); if (locThis == locThat) { locThis = GetSecondaryLocation(); locThat = that.GetSecondaryLocation(); if (locThis == locThat) return XmlNodeOrder.Same; } return (locThis < locThat) ? XmlNodeOrder.Before : XmlNodeOrder.After; } } return XmlNodeOrder.Unknown; } /// <summary> /// Return true if the "other" navigator's current node is a descendant of this navigator's current node. /// </summary> public override bool IsDescendant(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { XPathNode[] pageThat; int idxThat; // If that current node's parent is virtualized, then start with the virtual parent if (that._idxParent != 0) { pageThat = that._pageParent; idxThat = that._idxParent; } else { idxThat = that._pageCurrent[that._idxCurrent].GetParent(out pageThat); } while (idxThat != 0) { if (idxThat == _idxCurrent && pageThat == _pageCurrent) return true; idxThat = pageThat[idxThat].GetParent(out pageThat); } } return false; } /// <summary> /// Construct a primary location for this navigator. The location is an integer that can be /// easily compared with other locations in the same document in order to determine the relative /// document order of two nodes. If two locations compare equal, then secondary locations should /// be compared. /// </summary> private int GetPrimaryLocation() { // Is the current node virtualized? if (_idxParent == 0) { // No, so primary location should be derived from current node return XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); } // Yes, so primary location should be derived from parent node return XPathNodeHelper.GetLocation(_pageParent, _idxParent); } /// <summary> /// Construct a secondary location for this navigator. This location should only be used if /// primary locations previously compared equal. /// </summary> private int GetSecondaryLocation() { // Is the current node virtualized? if (_idxParent == 0) { // No, so secondary location is int.MinValue (always first) return int.MinValue; } // Yes, so secondary location should be derived from current node // This happens with attributes nodes, namespace nodes, collapsed text nodes, and atomic values switch (_pageCurrent[_idxCurrent].NodeType) { case XPathNodeType.Namespace: // Namespace nodes come first (make location negative, but greater than int.MinValue) return int.MinValue + 1 + XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); case XPathNodeType.Attribute: // Attribute nodes come next (location is always positive) return XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); default: // Collapsed text nodes are always last return int.MaxValue; } } /// <summary> /// Create a unique id for the current node. This is used by the generate-id() function. /// </summary> internal override string UniqueId { get { // 32-bit integer is split into 5-bit groups, the maximum number of groups is 7 char[] buf = new char[1 + 7 + 1 + 7]; int idx = 0; int loc; // Ensure distinguishing attributes, namespaces and child nodes buf[idx++] = NodeTypeLetter[(int)_pageCurrent[_idxCurrent].NodeType]; // If the current node is virtualized, code its parent if (_idxParent != 0) { loc = (_pageParent[0].PageInfo.PageNumber - 1) << 16 | (_idxParent - 1); do { buf[idx++] = UniqueIdTbl[loc & 0x1f]; loc >>= 5; } while (loc != 0); buf[idx++] = '0'; } // Code the node itself loc = (_pageCurrent[0].PageInfo.PageNumber - 1) << 16 | (_idxCurrent - 1); do { buf[idx++] = UniqueIdTbl[loc & 0x1f]; loc >>= 5; } while (loc != 0); return new string(buf, 0, idx); } } public override object UnderlyingObject { get { // Since we don't have any underlying PUBLIC object // the best one we can return is a clone of the navigator. // Note that it should be a clone as the user might Move the returned navigator // around and thus cause unexpected behavior of the caller of this class (For example the validator) return this.Clone(); } } //----------------------------------------------- // IXmlLineInfo //----------------------------------------------- /// <summary> /// Return true if line number information is recorded in the cache. /// </summary> public bool HasLineInfo() { return _pageCurrent[_idxCurrent].Document.HasLineInfo; } /// <summary> /// Return the source line number of the current node. /// </summary> public int LineNumber { get { // If the current node is a collapsed text node, then return parent element's line number if (_idxParent != 0 && NodeType == XPathNodeType.Text) return _pageParent[_idxParent].LineNumber; return _pageCurrent[_idxCurrent].LineNumber; } } /// <summary> /// Return the source line position of the current node. /// </summary> public int LinePosition { get { // If the current node is a collapsed text node, then get position from parent element if (_idxParent != 0 && NodeType == XPathNodeType.Text) return _pageParent[_idxParent].CollapsedLinePosition; return _pageCurrent[_idxCurrent].LinePosition; } } //----------------------------------------------- // Helper methods //----------------------------------------------- /// <summary> /// Get hashcode based on current position of the navigator. /// </summary> public int GetPositionHashCode() { return _idxCurrent ^ _idxParent; } /// <summary> /// Return true if navigator is positioned to an element having the specified name. /// </summary> public bool IsElementMatch(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; // Cannot be an element if parent is stored if (_idxParent != 0) return false; return _pageCurrent[_idxCurrent].ElementMatch(_atomizedLocalName, namespaceURI); } /// <summary> /// Return true if navigator is positioned to a node of the specified kind. Whitespace/SignficantWhitespace/Text are /// all treated the same (i.e. they all match each other). /// </summary> public bool IsKindMatch(XPathNodeType typ) { return (((1 << (int)_pageCurrent[_idxCurrent].NodeType) & XPathNavigatorEx.GetKindMask(typ)) != 0); } /// <summary> /// "end" is positioned on a node which terminates a following scan. Return the page and index of "end" if it /// is positioned to a non-virtual node. If "end" is positioned to a virtual node: /// 1. If useParentOfVirtual is true, then return the page and index of the virtual node's parent /// 2. If useParentOfVirtual is false, then return the page and index of the virtual node's parent + 1. /// </summary> private int GetFollowingEnd(XPathDocumentNavigator end, bool useParentOfVirtual, out XPathNode[] pageEnd) { // If ending navigator is positioned to a node in another document, then return null if (end != null && _pageCurrent[_idxCurrent].Document == end._pageCurrent[end._idxCurrent].Document) { // If the ending navigator is not positioned on a virtual node, then return its current node if (end._idxParent == 0) { pageEnd = end._pageCurrent; return end._idxCurrent; } // If the ending navigator is positioned on an attribute, namespace, or virtual text node, then use the // next physical node instead, as the results will be the same. pageEnd = end._pageParent; return (useParentOfVirtual) ? end._idxParent : end._idxParent + 1; } // No following, so set pageEnd to null and return an index of 0 pageEnd = null; return 0; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Threading; using System.Web; using System.Web.UI; using AjaxPro; using ASC.Common.Logging; using ASC.Core; using ASC.Core.Billing; using ASC.Core.Tenants; using ASC.Geolocation; using ASC.Web.Core; using ASC.Web.Studio.Core; using ASC.Web.Studio.Core.Notify; using ASC.Web.Studio.PublicResources; using ASC.Web.Studio.UserControls.Statistics; using ASC.Web.Studio.Utility; using PhoneNumbers; namespace ASC.Web.Studio.UserControls.Management { [AjaxNamespace("TariffUsageController")] public partial class TariffCustom : UserControl { public static string Location { get { return "~/UserControls/Management/TariffSettings/TariffCustom.ascx"; } } protected int UsersCount; protected long UsedSize; protected Tariff CurrentTariff; protected TenantQuota CurrentQuota; protected bool MonthIsDisable; protected bool YearIsDisable; protected int MinActiveUser; protected RegionInfo RegionDefault = new RegionInfo("RU"); protected RegionInfo CurrentRegion; protected string PhoneCountry = "RU"; private IEnumerable<TenantQuota> _quotaList; protected List<TenantQuota> QuotasYear; private TenantQuota _quotaForDisplay; protected int MonthPrice; protected int YearPrice; protected TenantQuota QuotaForDisplay { get { if (_quotaForDisplay != null) return _quotaForDisplay; TenantQuota quota = null; if (CurrentQuota.Trial || CurrentQuota.Free || !CurrentQuota.Visible) { var rightQuotaId = TenantExtra.GetRightQuotaId(); quota = _quotaList.FirstOrDefault(q => q.Id == rightQuotaId); } _quotaForDisplay = quota ?? CurrentQuota; return _quotaForDisplay; } } protected bool PeopleModuleAvailable { get { var peopleProduct = WebItemManager.Instance[WebItemManager.PeopleProductID]; return peopleProduct != null && !peopleProduct.IsDisabled(); } } protected void Page_Load(object sender, EventArgs e) { Page .RegisterBodyScripts("~/UserControls/Management/TariffSettings/js/tariffcustom.js", "~/js/asc/plugins/countries.js", "~/js/asc/plugins/phonecontroller.js") .RegisterStyle( "~/skins/default/phonecontroller.css", "~/UserControls/Management/TariffSettings/css/tariff.less", "~/UserControls/Management/TariffSettings/css/tariffusage.less", "~/UserControls/Management/TariffSettings/css/tariffcustom.less") .RegisterClientScript(new CountriesResources()); CurrentRegion = RegionDefault; UsersCount = TenantStatisticsProvider.GetUsersCount(); UsedSize = TenantStatisticsProvider.GetUsedSize(); CurrentTariff = TenantExtra.GetCurrentTariff(); CurrentQuota = TenantExtra.GetTenantQuota(); if (_quotaList == null || !_quotaList.Any()) { _quotaList = TenantExtra.GetTenantQuotas(); } else if (!CurrentQuota.Trial) { CurrentQuota = _quotaList.FirstOrDefault(q => q.Id == CurrentQuota.Id) ?? CurrentQuota; } _quotaList = _quotaList.OrderBy(r => r.ActiveUsers).ToList().Where(r => !r.Trial); QuotasYear = _quotaList.Where(r => r.Year).ToList(); MonthIsDisable = !CurrentQuota.Free && (CurrentQuota.Year || CurrentQuota.Year3) && CurrentTariff.State == TariffState.Paid; YearIsDisable = !CurrentQuota.Free && CurrentQuota.Year3 && CurrentTariff.State == TariffState.Paid; var minYearQuota = QuotasYear.FirstOrDefault(q => q.ActiveUsers >= UsersCount && q.MaxTotalSize >= UsedSize); MinActiveUser = minYearQuota != null ? minYearQuota.ActiveUsers : (QuotasYear.Count > 0 ? QuotasYear.Last().ActiveUsers : 0 + 1); MonthPrice = Convert.ToInt32(ConfigurationManager.AppSettings["core.custom-mode.month-price"] ?? "290"); YearPrice = Convert.ToInt32(ConfigurationManager.AppSettings["core.custom-mode.year-price"] ?? "175"); AjaxPro.Utility.RegisterTypeForAjax(GetType()); CurrencyCheck(); } private void CurrencyCheck() { var findRegion = FindRegionInfo(); CurrentRegion = findRegion ?? CurrentRegion; PhoneCountry = (findRegion ?? new RegionInfo(Thread.CurrentThread.CurrentCulture.LCID)).TwoLetterISORegionName; var requestCur = Request["cur"]; if (!string.IsNullOrEmpty(requestCur)) { try { CurrentRegion = new RegionInfo(requestCur); } catch { } } } private static RegionInfo FindRegionInfo() { RegionInfo ri = null; var ownerId = CoreContext.TenantManager.GetCurrentTenant().OwnerId; var owner = CoreContext.UserManager.GetUsers(ownerId); if (!string.IsNullOrEmpty(owner.MobilePhone)) { try { var phoneUtil = PhoneNumberUtil.GetInstance(); var number = phoneUtil.Parse("+" + owner.MobilePhone.TrimStart('+'), "en-US"); var regionCode = phoneUtil.GetRegionCodeForNumber(number); if (!string.IsNullOrEmpty(regionCode)) { ri = new RegionInfo(regionCode); } } catch (Exception err) { LogManager.GetLogger("ASC.Web.Tariff").WarnFormat("Can not find country by phone {0}: {1}", owner.MobilePhone, err); } } if (ri == null) { var geoinfo = new GeolocationHelper("teamlabsite").GetIPGeolocationFromHttpContext(); if (!string.IsNullOrEmpty(geoinfo.Key)) { try { ri = new RegionInfo(geoinfo.Key); } catch (Exception) { // ignore } } } return ri; } protected string TariffDescription() { if (CurrentQuota.Trial) { if (CurrentTariff.State == TariffState.Trial) { return "<b>" + Resource.TariffTrial + "</b> " + (CurrentTariff.DueDate.Date != DateTime.MaxValue.Date ? string.Format(Resource.TariffExpiredDate, CurrentTariff.DueDate.Date.ToLongDateString()) : "") + "<br />" + Resource.TariffChooseLabel; } return String.Format(Resource.TariffTrialOverdue.HtmlEncode(), "<span class='tarifff-marked'>", "</span>", "<br />", string.Empty, string.Empty); } if (CurrentQuota.Free) { return "<b>" + Resource.TariffFree + "</b><br />" + Resource.TariffChooseLabel; } if (CurrentTariff.State == TariffState.Paid && CurrentTariff.DueDate.Date >= DateTime.Today) { if (CurrentQuota.NonProfit) { return "<b>" + UserControlsCommonResource.TariffNonProfit + "</b>"; } var str = "<b>" + String.Format(UserControlsCommonResource.TariffPaidPlan, TenantExtra.GetPrevUsersCount(CurrentQuota), CurrentQuota.ActiveUsers) + "</b> "; if (CurrentTariff.DueDate.Date != DateTime.MaxValue.Date) str += string.Format(Resource.TariffExpiredDate, CurrentTariff.DueDate.Date.ToLongDateString()); if (CurrentTariff.Autorenewal) return str; str += "<br />" + Resource.TariffCanProlong; return str; } return String.Format(UserControlsCommonResource.TariffOverduePlan.HtmlEncode(), TenantExtra.GetPrevUsersCount(CurrentQuota), CurrentQuota.ActiveUsers, "<span class='tariff-marked'>", "</span>", "<br />"); } protected TenantQuota GetQuotaMonth(TenantQuota quota) { return _quotaList.FirstOrDefault(r => r.ActiveUsers == quota.ActiveUsers && (!r.Year || quota.Free) && !r.Year3); } [AjaxMethod] public void RequestTariff(string fname, string lname, string title, string email, string phone, string ctitle, string csize, string site, string message) { var key = HttpContext.Current.Request.UserHostAddress + "requesttariff"; var count = Convert.ToInt32(HttpContext.Current.Cache[key]); if (2 < count) { throw new ArgumentOutOfRangeException("Messages count", "Rate limit exceeded."); } HttpContext.Current.Cache.Insert(key, ++count, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(2)); StudioNotifyService.Instance.SendRequestTariff(false, fname, lname, title, email, phone, ctitle, csize, site, message); } } }
using System; using System.Collections.Generic; using System.Linq; using RestSharp; using Client; using Model; namespace Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IUserApi { /// <summary> /// List Users /// </summary> /// <remarks> /// You can retrieve a list of users /// </remarks> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Users</returns> Users FindAll(bool? parameter = null, int? depth = null); /// <summary> /// List Users /// </summary> /// <remarks> /// You can retrieve a list of users /// </remarks> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>ApiResponse of Users</returns> ApiResponse<Users> FindAllWithHttpInfo(bool? parameter = null, int? depth = null); /// <summary> /// List Users /// </summary> /// <remarks> /// You can retrieve a list of users /// </remarks> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of Users</returns> System.Threading.Tasks.Task<Users> FindAllAsync(bool? parameter = null, int? depth = null); /// <summary> /// List Users /// </summary> /// <remarks> /// You can retrieve a list of users /// </remarks> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of ApiResponse (Users)</returns> System.Threading.Tasks.Task<ApiResponse<Users>> FindAllAsyncWithHttpInfo(bool? parameter = null, int? depth = null); /// <summary> /// Create a User /// </summary> /// <remarks> /// Creates a user /// </remarks> /// <param name="user">User to be created</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>User</returns> User Create(User user, bool? parameter = null, int? depth = null); /// <summary> /// Create a User /// </summary> /// <remarks> /// Creates a user /// </remarks> /// <param name="user">User to be created</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>ApiResponse of User</returns> ApiResponse<User> CreateWithHttpInfo(User user, bool? parameter = null, int? depth = null); /// <summary> /// Create a User /// </summary> /// <remarks> /// Creates a user /// </remarks> /// <param name="user">User to be created</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of User</returns> System.Threading.Tasks.Task<User> CreateAsync(User user, bool? parameter = null, int? depth = null); /// <summary> /// Create a User /// </summary> /// <remarks> /// Creates a user /// </remarks> /// <param name="user">User to be created</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of ApiResponse (User)</returns> System.Threading.Tasks.Task<ApiResponse<User>> CreateAsyncWithHttpInfo(User user, bool? parameter = null, int? depth = null); /// <summary> /// Retrieve a User /// </summary> /// <remarks> /// Returns information about a user /// </remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>User</returns> User FindById(string userId, bool? parameter = null, int? depth = null); /// <summary> /// Retrieve a User /// </summary> /// <remarks> /// Returns information about a user /// </remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>ApiResponse of User</returns> ApiResponse<User> FindByIdWithHttpInfo(string userId, bool? parameter = null, int? depth = null); /// <summary> /// Retrieve a User /// </summary> /// <remarks> /// Returns information about a user /// </remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of User</returns> System.Threading.Tasks.Task<User> FindByIdAsync(string userId, bool? parameter = null, int? depth = null); /// <summary> /// Retrieve a User /// </summary> /// <remarks> /// Returns information about a user /// </remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of ApiResponse (User)</returns> System.Threading.Tasks.Task<ApiResponse<User>> FindByIdAsyncWithHttpInfo(string userId, bool? parameter = null, int? depth = null); /// <summary> /// Modify a User /// </summary> /// <remarks> /// You can use update attributes of a user /// </remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="user">Modified User</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>User</returns> User Update(string userId, User user, bool? parameter = null, int? depth = null); /// <summary> /// Modify a User /// </summary> /// <remarks> /// You can use update attributes of a user /// </remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="user">Modified User</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>ApiResponse of User</returns> ApiResponse<User> UpdateWithHttpInfo(string userId, User user, bool? parameter = null, int? depth = null); /// <summary> /// Modify a User /// </summary> /// <remarks> /// You can use update attributes of a user /// </remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="user">Modified User</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of User</returns> System.Threading.Tasks.Task<User> UpdateAsync(string userId, User user, bool? parameter = null, int? depth = null); /// <summary> /// Modify a User /// </summary> /// <remarks> /// You can use update attributes of a user /// </remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="user">Modified User</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of ApiResponse (User)</returns> System.Threading.Tasks.Task<ApiResponse<User>> UpdateAsyncWithHttpInfo(string userId, User user, bool? parameter = null, int? depth = null); /// <summary> /// Delete a User /// </summary> /// <remarks> /// This will delete a user /// </remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>InlineResponse202</returns> InlineResponse202 Delete(string userId, bool? parameter = null, int? depth = null); /// <summary> /// Delete a User /// </summary> /// <remarks> /// This will delete a user /// </remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>ApiResponse of InlineResponse202</returns> ApiResponse<InlineResponse202> DeleteWithHttpInfo(string userId, bool? parameter = null, int? depth = null); /// <summary> /// Delete a User /// </summary> /// <remarks> /// This will delete a user /// </remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of InlineResponse202</returns> System.Threading.Tasks.Task<InlineResponse202> DeleteAsync(string userId, bool? parameter = null, int? depth = null); /// <summary> /// Delete a User /// </summary> /// <remarks> /// This will delete a user /// </remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of ApiResponse (InlineResponse202)</returns> System.Threading.Tasks.Task<ApiResponse<InlineResponse202>> DeleteAsyncWithHttpInfo(string userId, bool? parameter = null, int? depth = null); } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public class UserApi : IUserApi { /// <summary> /// Initializes a new instance of the <see cref="UserApi"/> class. /// </summary> /// <returns></returns> public UserApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); } /// <summary> /// Initializes a new instance of the <see cref="UserApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public UserApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration { get; set; } /// <summary> /// List Users /// </summary> /// <remarks>You can retrieve a list of users</remarks> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Users</returns> public Users FindAll(bool? parameter = null, int? depth = null) { ApiResponse<Users> response = FindAllWithHttpInfo(parameter, depth); return response.Data; } /// <summary> /// List Users /// </summary> /// <remarks>You can retrieve a list of users</remarks> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>ApiResponse of Users</returns> public ApiResponse<Users> FindAllWithHttpInfo(bool? parameter = null, int? depth = null) { var path_ = "/um/users"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); Object postBody = null; // to determine the Content-Type header String[] httpContentTypes = new String[] { "*/*" }; String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header String[] httpHeaderAccepts = new String[] { "application/json" }; String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); } // make the HTTP request IRestResponse response = (IRestResponse)Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, httpContentType); int statusCode = (int)response.StatusCode; if (statusCode >= 400) throw new ApiException(statusCode, "Error calling FindAll: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException(statusCode, "Error calling FindAll: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<Users>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Users)Configuration.ApiClient.Deserialize(response, typeof(Users))); } /// <summary> /// List Users /// </summary> /// <remarks>You can retrieve a list of users</remarks> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of Users</returns> public async System.Threading.Tasks.Task<Users> FindAllAsync(bool? parameter = null, int? depth = null) { ApiResponse<Users> response = await FindAllAsyncWithHttpInfo(parameter, depth); return response.Data; } /// <summary> /// List Users /// </summary> /// <remarks>You can retrieve a list of users</remarks> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of ApiResponse (Users)</returns> public async System.Threading.Tasks.Task<ApiResponse<Users>> FindAllAsyncWithHttpInfo(bool? parameter = null, int? depth = null) { var path_ = "/um/users"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); Object postBody = null; // to determine the Content-Type header String[] httpContentTypes = new String[] { "*/*" }; String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header String[] httpHeaderAccepts = new String[] { "application/json" }; String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); } // make the HTTP request IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, httpContentType); int statusCode = (int)response.StatusCode; if (statusCode >= 400) throw new ApiException(statusCode, "Error calling FindAll: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException(statusCode, "Error calling FindAll: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<Users>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Users)Configuration.ApiClient.Deserialize(response, typeof(Users))); } /// <summary> /// Create a User /// </summary> /// <remarks>You can create a user</remarks> /// <param name="user">User to be created</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>User</returns> public User Create(User user, bool? parameter = null, int? depth = null) { ApiResponse<User> response = CreateWithHttpInfo(user, parameter, depth); response.Data.Request = response.Headers["Location"]; return response.Data; } /// <summary> /// Create a User /// </summary> /// <remarks>You can create a user</remarks> /// <param name="user">User to be created</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>ApiResponse of User</returns> public ApiResponse<User> CreateWithHttpInfo(User user, bool? parameter = null, int? depth = null) { // verify the required parameter 'user' is set if (user == null) throw new ApiException(400, "Missing required parameter 'user' when calling UserApi->Create"); var path_ = "/um/users"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); Object postBody = null; // to determine the Content-Type header String[] httpContentTypes = new String[] { "application/json" }; String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header String[] httpHeaderAccepts = new String[] { "application/json" }; String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter if (user.GetType() != typeof(byte[])) { postBody = Configuration.ApiClient.Serialize(user); // http body (model) parameter } else { postBody = user; // byte array } // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); } // make the HTTP request IRestResponse response = (IRestResponse)Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, httpContentType); int statusCode = (int)response.StatusCode; if (statusCode >= 400) throw new ApiException(statusCode, "Error calling Create: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException(statusCode, "Error calling Create: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<User>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (User)Configuration.ApiClient.Deserialize(response, typeof(User))); } /// <summary> /// Create a User /// </summary> /// <remarks>You can create a user</remarks> /// <param name="user">User to be created</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of User</returns> public async System.Threading.Tasks.Task<User> CreateAsync(User user, bool? parameter = null, int? depth = null) { ApiResponse<User> response = await CreateAsyncWithHttpInfo(user, parameter, depth); return response.Data; } /// <summary> /// Create a User /// </summary> /// <remarks>You can create a user</remarks> /// <param name="user">User to be created</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of ApiResponse (User)</returns> public async System.Threading.Tasks.Task<ApiResponse<User>> CreateAsyncWithHttpInfo(User user, bool? parameter = null, int? depth = null) { // verify the required parameter 'user' is set if (user == null) throw new ApiException(400, "Missing required parameter 'user' when calling Create"); var path_ = "/um/users"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); Object postBody = null; // to determine the Content-Type header String[] httpContentTypes = new String[] { "application/json" }; String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header String[] httpHeaderAccepts = new String[] { "application/json" }; String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter postBody = Configuration.ApiClient.Serialize(user); // http body (model) parameter // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); } // make the HTTP request IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, httpContentType); int statusCode = (int)response.StatusCode; if (statusCode >= 400) throw new ApiException(statusCode, "Error calling Create: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException(statusCode, "Error calling Create: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<User>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (User)Configuration.ApiClient.Deserialize(response, typeof(User))); } /// <summary> /// Retrieve a User /// </summary> /// <remarks>Returns information about a user</remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>User</returns> public User FindById(string userId, bool? parameter = null, int? depth = null) { ApiResponse<User> response = FindByIdWithHttpInfo(userId, parameter, depth); return response.Data; } /// <summary> /// Retrieve a User /// </summary> /// <remarks>Returns information about a user</remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>ApiResponse of User</returns> public ApiResponse<User> FindByIdWithHttpInfo(string userId, bool? parameter = null, int? depth = null) { // verify the required parameter 'userId' is set if (string.IsNullOrEmpty(userId)) throw new ApiException(400, "Missing required parameter 'userId' when calling UserApi->FindById"); var path_ = "/um/users/{userId}"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); Object postBody = null; // to determine the Content-Type header String[] httpContentTypes = new String[] { "*/*" }; String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header String[] httpHeaderAccepts = new String[] { "application/json" }; String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); pathParams.Add("userId", Configuration.ApiClient.ParameterToString(userId)); // path parameter if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); } // make the HTTP request IRestResponse response = (IRestResponse)Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, httpContentType); int statusCode = (int)response.StatusCode; if (statusCode >= 400) throw new ApiException(statusCode, "Error calling FindById: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException(statusCode, "Error calling FindById: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<User>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (User)Configuration.ApiClient.Deserialize(response, typeof(User))); } /// <summary> /// Retrieve a User /// </summary> /// <remarks>Returns information about a user</remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of User</returns> public async System.Threading.Tasks.Task<User> FindByIdAsync(string userId, bool? parameter = null, int? depth = null) { ApiResponse<User> response = await FindByIdAsyncWithHttpInfo(userId, parameter, depth); return response.Data; } /// <summary> /// Retrieve a User /// </summary> /// <remarks>Returns information about a user</remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of ApiResponse (User)</returns> public async System.Threading.Tasks.Task<ApiResponse<User>> FindByIdAsyncWithHttpInfo(string userId, bool? parameter = null, int? depth = null) { // verify the required parameter 'userId' is set if (string.IsNullOrEmpty(userId)) throw new ApiException(400, "Missing required parameter 'userId' when calling FindById"); var path_ = "/um/users/{userId}"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); Object postBody = null; // to determine the Content-Type header String[] httpContentTypes = new String[] { "*/*" }; String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header String[] httpHeaderAccepts = new String[] { "application/json" }; String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); pathParams.Add("userId", Configuration.ApiClient.ParameterToString(userId)); // path parameter if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); } // make the HTTP request IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, httpContentType); int statusCode = (int)response.StatusCode; if (statusCode >= 400) throw new ApiException(statusCode, "Error calling FindById: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException(statusCode, "Error calling FindById: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<User>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (User)Configuration.ApiClient.Deserialize(response, typeof(User))); } /// <summary> /// Modify a User /// </summary> /// <remarks>You can update attributes of a user</remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="user">Modified User</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>User</returns> public User Update(string userId, User user, bool? parameter = null, int? depth = null) { ApiResponse<User> response = UpdateWithHttpInfo(userId, user, parameter, depth); return response.Data; } /// <summary> /// Modify a User /// </summary> /// <remarks>You can update attributes of a user</remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="user">Modified User</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>ApiResponse of User</returns> public ApiResponse<User> UpdateWithHttpInfo(string userId, User user, bool? parameter = null, int? depth = null) { // verify the required parameter 'userId' is set if (string.IsNullOrEmpty(userId)) throw new ApiException(400, "Missing required parameter 'userId' when calling UserApi->Update"); // verify the required parameter 'user' is set if (user == null) throw new ApiException(400, "Missing required parameter 'user' when calling UserApi->Update"); var path_ = "/um/users/{userId}"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); Object postBody = null; // to determine the Content-Type header String[] httpContentTypes = new String[] { "application/json" }; String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header String[] httpHeaderAccepts = new String[] { "application/json" }; String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); pathParams.Add("userId", Configuration.ApiClient.ParameterToString(userId)); // path parameter if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter if (user.GetType() != typeof(byte[])) { postBody = Configuration.ApiClient.Serialize(user); // http body (model) parameter } else { postBody = user; // byte array } // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); } // make the HTTP request IRestResponse response = (IRestResponse)Configuration.ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, httpContentType); int statusCode = (int)response.StatusCode; if (statusCode >= 400) throw new ApiException(statusCode, "Error calling Update: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException(statusCode, "Error calling Update: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<User>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (User)Configuration.ApiClient.Deserialize(response, typeof(User))); } /// <summary> /// Modify a User /// </summary> /// <remarks>You can update attributes of a user</remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="user">Modified User</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of User</returns> public async System.Threading.Tasks.Task<User> UpdateAsync(string userId, User user, bool? parameter = null, int? depth = null) { ApiResponse<User> response = await UpdateAsyncWithHttpInfo(userId, user, parameter, depth); return response.Data; } /// <summary> /// Modify a User /// </summary> /// <remarks>You can update attributes of a user</remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="user">Modified User</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of ApiResponse (User)</returns> public async System.Threading.Tasks.Task<ApiResponse<User>> UpdateAsyncWithHttpInfo(string userId, User user, bool? parameter = null, int? depth = null) { // verify the required parameter 'userId' is set if (string.IsNullOrEmpty(userId)) throw new ApiException(400, "Missing required parameter 'userId' when calling Update"); // verify the required parameter 'user' is set if (user == null) throw new ApiException(400, "Missing required parameter 'user' when calling Update"); var path_ = "/um/users/{userId}"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); Object postBody = null; // to determine the Content-Type header String[] httpContentTypes = new String[] { "application/json" }; String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header String[] httpHeaderAccepts = new String[] { "application/json" }; String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); pathParams.Add("userId", Configuration.ApiClient.ParameterToString(userId)); // path parameter if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter postBody = Configuration.ApiClient.Serialize(user); // http body (model) parameter // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); } // make the HTTP request IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, httpContentType); int statusCode = (int)response.StatusCode; if (statusCode >= 400) throw new ApiException(statusCode, "Error calling Update: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException(statusCode, "Error calling Update: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<User>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (User)Configuration.ApiClient.Deserialize(response, typeof(User))); } /// <summary> /// Delete a User /// </summary> /// <remarks>This will delete a user</remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>InlineResponse202</returns> public InlineResponse202 Delete(string userId, bool? parameter = null, int? depth = null) { ApiResponse<InlineResponse202> response = DeleteWithHttpInfo(userId, parameter, depth); return response.Data; } /// <summary> /// Delete a User /// </summary> /// <remarks>This will delete a user</remarks> /// <param name="userId">The unique ID of the user</param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>ApiResponse of InlineResponse202</returns> public ApiResponse<InlineResponse202> DeleteWithHttpInfo(string userId, bool? parameter = null, int? depth = null) { // verify the required parameter 'userId' is set if (string.IsNullOrEmpty(userId)) throw new ApiException(400, "Missing required parameter 'userId' when calling UserApi->Delete"); var path_ = "/um/users/{userId}"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); Object postBody = null; // to determine the Content-Type header String[] httpContentTypes = new String[] { "*/*" }; String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header String[] httpHeaderAccepts = new String[] { "application/json" }; String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); pathParams.Add("userId", Configuration.ApiClient.ParameterToString(userId)); // path parameter if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); } // make the HTTP request IRestResponse response = (IRestResponse)Configuration.ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, httpContentType); int statusCode = (int)response.StatusCode; if (statusCode >= 400) throw new ApiException(statusCode, "Error calling Delete: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException(statusCode, "Error calling Delete: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<InlineResponse202>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (InlineResponse202)Configuration.ApiClient.Deserialize(response, typeof(InlineResponse202))); } /// <summary> /// Delete a User /// </summary> /// <remarks>This will delete a user</remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of InlineResponse202</returns> public async System.Threading.Tasks.Task<InlineResponse202> DeleteAsync(string userId, bool? parameter = null, int? depth = null) { ApiResponse<InlineResponse202> response = await DeleteAsyncWithHttpInfo(userId, parameter, depth); return response.Data; } /// <summary> /// Delete a User /// </summary> /// <remarks>This will delete a user</remarks> /// <param name="userId"></param> /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> /// <param name="depth">Controls the details depth of response objects.</param> /// <returns>Task of ApiResponse (InlineResponse202)</returns> public async System.Threading.Tasks.Task<ApiResponse<InlineResponse202>> DeleteAsyncWithHttpInfo(string userId, bool? parameter = null, int? depth = null) { // verify the required parameter 'userId' is set if (string.IsNullOrEmpty(userId)) throw new ApiException(400, "Missing required parameter 'userId' when calling Delete"); var path_ = "/um/users/{userId}"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); Object postBody = null; // to determine the Content-Type header String[] httpContentTypes = new String[] { "*/*" }; String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header String[] httpHeaderAccepts = new String[] { "application/json" }; String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); pathParams.Add("userId", Configuration.ApiClient.ParameterToString(userId)); // path parameter if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); } // make the HTTP request IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, httpContentType); int statusCode = (int)response.StatusCode; if (statusCode >= 400) throw new ApiException(statusCode, "Error calling Delete: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException(statusCode, "Error calling Delete: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<InlineResponse202>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (InlineResponse202)Configuration.ApiClient.Deserialize(response, typeof(InlineResponse202))); } } }
/* * 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. */ namespace Apache.Ignite.Service { using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.ServiceProcess; using System.Text; using Apache.Ignite.Config; using Apache.Ignite.Core; using Apache.Ignite.Core.Common; /// <summary> /// Ignite windows service. /// </summary> internal class IgniteService : ServiceBase { /** Service name. */ internal static readonly string SvcName = "Apache Ignite.NET"; /** Service display name. */ internal static readonly string SvcDisplayName = "Apache Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version.ToString(4); /** Service description. */ internal static readonly string SvcDesc = "Apache Ignite.NET Service."; /** Current executable name. */ internal static readonly string ExeName = new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath).FullName; /** Current executable fully qualified name. */ internal static readonly string FullExeName = Path.GetFileName(FullExeName); /** Ignite configuration to start with. */ private readonly IgniteConfiguration _cfg; /// <summary> /// Constructor. /// </summary> public IgniteService(IgniteConfiguration cfg) { AutoLog = true; CanStop = true; ServiceName = SvcName; _cfg = cfg; } /** <inheritDoc /> */ protected override void OnStart(string[] args) { Ignition.Start(_cfg); } /** <inheritDoc /> */ protected override void OnStop() { Ignition.StopAll(true); } /// <summary> /// Install service programmatically. /// </summary> /// <param name="cfg">Ignite configuration.</param> internal static void DoInstall(IgniteConfiguration cfg) { // 1. Check if already defined. if (ServiceController.GetServices().Any(svc => SvcName.Equals(svc.ServiceName))) { throw new IgniteException("Ignite service is already installed (uninstall it using \"" + ExeName + " " + IgniteRunner.SvcUninstall + "\" first)"); } // 2. Create startup arguments. var args = ArgsConfigurator.ToArgs(cfg); if (args.Length > 0) { Console.WriteLine("Installing \"" + SvcName + "\" service with the following startup " + "arguments:"); foreach (var arg in args) Console.WriteLine("\t" + arg); } else Console.WriteLine("Installing \"" + SvcName + "\" service ..."); // 3. Actual installation. Install0(args); Console.WriteLine("\"" + SvcName + "\" service installed successfully."); } /// <summary> /// Uninstall service programmatically. /// </summary> internal static void Uninstall() { var svc = ServiceController.GetServices().FirstOrDefault(x => SvcName == x.ServiceName); if (svc == null) { Console.WriteLine("\"" + SvcName + "\" service is not installed."); } else if (svc.Status != ServiceControllerStatus.Stopped) { throw new IgniteException("Ignite service is running, please stop it first."); } else { Console.WriteLine("Uninstalling \"" + SvcName + "\" service ..."); Uninstall0(); Console.WriteLine("\"" + SvcName + "\" service uninstalled successfully."); } } /// <summary> /// Native service installation. /// </summary> /// <param name="args">Arguments.</param> private static void Install0(string[] args) { // 1. Prepare arguments. var binPath = new StringBuilder(FullExeName).Append(" ").Append(IgniteRunner.Svc); foreach (var arg in args) binPath.Append(" ").Append(arg); // 2. Get SC manager. var scMgr = OpenServiceControlManager(); // 3. Create service. var svc = NativeMethods.CreateService( scMgr, SvcName, SvcDisplayName, 983551, // Access constant. 0x10, // Service type SERVICE_WIN32_OWN_PROCESS. 0x2, // Start type SERVICE_AUTO_START. 0x2, // Error control SERVICE_ERROR_SEVERE. binPath.ToString(), null, IntPtr.Zero, null, null, // Use priviliged LocalSystem account. null ); if (svc == IntPtr.Zero) throw new IgniteException("Failed to create the service.", new Win32Exception()); // 4. Set description. var desc = new ServiceDescription {desc = Marshal.StringToHGlobalUni(SvcDesc)}; try { if (!NativeMethods.ChangeServiceConfig2(svc, 1u, ref desc)) throw new IgniteException("Failed to set service description.", new Win32Exception()); } finally { Marshal.FreeHGlobal(desc.desc); } } /// <summary> /// Native service uninstallation. /// </summary> private static void Uninstall0() { var scMgr = OpenServiceControlManager(); var svc = NativeMethods.OpenService(scMgr, SvcName, 65536); if (svc == IntPtr.Zero) throw new IgniteException("Failed to uninstall the service.", new Win32Exception()); NativeMethods.DeleteService(svc); } /// <summary> /// Opens SC manager. /// </summary> /// <returns>SC manager pointer.</returns> private static IntPtr OpenServiceControlManager() { var ptr = NativeMethods.OpenSCManager(null, null, 983103); if (ptr == IntPtr.Zero) throw new IgniteException("Failed to initialize Service Control manager " + "(did you run the command as administrator?)", new Win32Exception()); return ptr; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using OrchardCore.Admin; using OrchardCore.Deployment.ViewModels; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Settings; using YesSql; namespace OrchardCore.Deployment.Controllers { [Admin] public class StepController : Controller { private readonly IAuthorizationService _authorizationService; private readonly IDisplayManager<DeploymentStep> _displayManager; private readonly IEnumerable<IDeploymentStepFactory> _factories; private readonly ISession _session; private readonly ISiteService _siteService; private readonly INotifier _notifier; private readonly IUpdateModelAccessor _updateModelAccessor; private readonly IHtmlLocalizer H; private readonly dynamic New; public StepController( IAuthorizationService authorizationService, IDisplayManager<DeploymentStep> displayManager, IEnumerable<IDeploymentStepFactory> factories, ISession session, ISiteService siteService, IShapeFactory shapeFactory, IHtmlLocalizer<StepController> htmlLocalizer, INotifier notifier, IUpdateModelAccessor updateModelAccessor) { _displayManager = displayManager; _factories = factories; _authorizationService = authorizationService; _session = session; _siteService = siteService; _notifier = notifier; _updateModelAccessor = updateModelAccessor; New = shapeFactory; H = htmlLocalizer; } public async Task<IActionResult> Create(int id, string type) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } var deploymentPlan = await _session.GetAsync<DeploymentPlan>(id); if (deploymentPlan == null) { return NotFound(); } var step = _factories.FirstOrDefault(x => x.Name == type)?.Create(); if (step == null) { return NotFound(); } step.Id = Guid.NewGuid().ToString("n"); var model = new EditDeploymentPlanStepViewModel { DeploymentPlanId = id, DeploymentStep = step, DeploymentStepId = step.Id, DeploymentStepType = type, Editor = await _displayManager.BuildEditorAsync(step, updater: _updateModelAccessor.ModelUpdater, isNew: true) }; model.Editor.DeploymentStep = step; return View(model); } [HttpPost] public async Task<IActionResult> Create(EditDeploymentPlanStepViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } var deploymentPlan = await _session.GetAsync<DeploymentPlan>(model.DeploymentPlanId); if (deploymentPlan == null) { return NotFound(); } var step = _factories.FirstOrDefault(x => x.Name == model.DeploymentStepType)?.Create(); if (step == null) { return NotFound(); } dynamic editor = await _displayManager.UpdateEditorAsync(step, updater: _updateModelAccessor.ModelUpdater, isNew: true); editor.DeploymentStep = step; if (ModelState.IsValid) { step.Id = model.DeploymentStepId; deploymentPlan.DeploymentSteps.Add(step); _session.Save(deploymentPlan); await _notifier.SuccessAsync(H["Deployment plan step added successfully."]); return RedirectToAction("Display", "DeploymentPlan", new { id = model.DeploymentPlanId }); } model.Editor = editor; // If we got this far, something failed, redisplay form return View(model); } public async Task<IActionResult> Edit(int id, string stepId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } var deploymentPlan = await _session.GetAsync<DeploymentPlan>(id); if (deploymentPlan == null) { return NotFound(); } var step = deploymentPlan.DeploymentSteps.FirstOrDefault(x => String.Equals(x.Id, stepId, StringComparison.OrdinalIgnoreCase)); if (step == null) { return NotFound(); } var model = new EditDeploymentPlanStepViewModel { DeploymentPlanId = id, DeploymentStep = step, DeploymentStepId = step.Id, DeploymentStepType = step.GetType().Name, Editor = await _displayManager.BuildEditorAsync(step, updater: _updateModelAccessor.ModelUpdater, isNew: false) }; model.Editor.DeploymentStep = step; return View(model); } [HttpPost] public async Task<IActionResult> Edit(EditDeploymentPlanStepViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } var deploymentPlan = await _session.GetAsync<DeploymentPlan>(model.DeploymentPlanId); if (deploymentPlan == null) { return NotFound(); } var step = deploymentPlan.DeploymentSteps.FirstOrDefault(x => String.Equals(x.Id, model.DeploymentStepId, StringComparison.OrdinalIgnoreCase)); if (step == null) { return NotFound(); } var editor = await _displayManager.UpdateEditorAsync(step, updater: _updateModelAccessor.ModelUpdater, isNew: false); if (ModelState.IsValid) { _session.Save(deploymentPlan); await _notifier.SuccessAsync(H["Deployment plan step updated successfully."]); return RedirectToAction("Display", "DeploymentPlan", new { id = model.DeploymentPlanId }); } await _notifier.ErrorAsync(H["The deployment plan step has validation errors."]); model.Editor = editor; // If we got this far, something failed, redisplay form return View(model); } [HttpPost] public async Task<IActionResult> Delete(int id, string stepId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } var deploymentPlan = await _session.GetAsync<DeploymentPlan>(id); if (deploymentPlan == null) { return NotFound(); } var step = deploymentPlan.DeploymentSteps.FirstOrDefault(x => String.Equals(x.Id, stepId, StringComparison.OrdinalIgnoreCase)); if (step == null) { return NotFound(); } deploymentPlan.DeploymentSteps.Remove(step); _session.Save(deploymentPlan); await _notifier.SuccessAsync(H["Deployment step deleted successfully."]); return RedirectToAction("Display", "DeploymentPlan", new { id }); } [HttpPost] public async Task<IActionResult> UpdateOrder(int id, int oldIndex, int newIndex) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } var deploymentPlan = await _session.GetAsync<DeploymentPlan>(id); if (deploymentPlan == null) { return NotFound(); } var step = deploymentPlan.DeploymentSteps.ElementAtOrDefault(oldIndex); if (step == null) { return NotFound(); } deploymentPlan.DeploymentSteps.RemoveAt(oldIndex); deploymentPlan.DeploymentSteps.Insert(newIndex, step); _session.Save(deploymentPlan); return Ok(); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using System.Diagnostics; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Streams; using Orleans.Configuration; namespace Orleans.Providers.Streams.Generator { /// <summary> /// Stream generator commands /// </summary> public enum StreamGeneratorCommand { /// <summary> /// Command to configure the generator /// </summary> Configure = PersistentStreamProviderCommand.AdapterFactoryCommandStartRange } /// <summary> /// Adapter factory for stream generator stream provider. /// This factory acts as the adapter and the adapter factory. It creates receivers that use configurable generator /// to generate event streams, rather than reading them from storage. /// </summary> public class GeneratorAdapterFactory : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache, IControllable { /// <summary> /// Configuration property name for generator configuration type /// </summary> private readonly HashRingStreamQueueMapperOptions queueMapperOptions; private readonly StreamStatisticOptions statisticOptions; private readonly IServiceProvider serviceProvider; private readonly SerializationManager serializationManager; private readonly ITelemetryProducer telemetryProducer; private readonly ILoggerFactory loggerFactory; private readonly ILogger<GeneratorAdapterFactory> logger; private IStreamGeneratorConfig generatorConfig; private IStreamQueueMapper streamQueueMapper; private IStreamFailureHandler streamFailureHandler; private ConcurrentDictionary<QueueId, Receiver> receivers; private IObjectPool<FixedSizeBuffer> bufferPool; private BlockPoolMonitorDimensions blockPoolMonitorDimensions; /// <summary> /// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time. /// </summary> /// <returns>True if this is a rewindable stream adapter, false otherwise.</returns> public bool IsRewindable => true; /// <summary> /// Direction of this queue adapter: Read, Write or ReadWrite. /// </summary> /// <returns>The direction in which this adapter provides data.</returns> public StreamProviderDirection Direction => StreamProviderDirection.ReadOnly; /// <summary> /// Name of the adapter. From IQueueAdapter. /// </summary> public string Name { get; } /// <summary> /// Create a cache monitor to report cache related metrics /// Return a ICacheMonitor /// </summary> protected Func<CacheMonitorDimensions, ITelemetryProducer, ICacheMonitor> CacheMonitorFactory; /// <summary> /// Create a block pool monitor to monitor block pool related metrics /// Return a IBlockPoolMonitor /// </summary> protected Func<BlockPoolMonitorDimensions, ITelemetryProducer, IBlockPoolMonitor> BlockPoolMonitorFactory; /// <summary> /// Create a monitor to monitor QueueAdapterReceiver related metrics /// Return a IQueueAdapterReceiverMonitor /// </summary> protected Func<ReceiverMonitorDimensions, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory; public GeneratorAdapterFactory(string providerName, HashRingStreamQueueMapperOptions queueMapperOptions, StreamStatisticOptions statisticOptions, IServiceProvider serviceProvider, SerializationManager serializationManager, ITelemetryProducer telemetryProducer, ILoggerFactory loggerFactory) { this.Name = providerName; this.queueMapperOptions = queueMapperOptions ?? throw new ArgumentNullException(nameof(queueMapperOptions)); this.statisticOptions = statisticOptions ?? throw new ArgumentNullException(nameof(statisticOptions)); this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); this.serializationManager = serializationManager ?? throw new ArgumentNullException(nameof(serializationManager)); this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer)); this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); this.logger = loggerFactory.CreateLogger<GeneratorAdapterFactory>(); } /// <summary> /// Initialize the factory /// </summary> public void Init() { this.receivers = new ConcurrentDictionary<QueueId, Receiver>(); if (CacheMonitorFactory == null) this.CacheMonitorFactory = (dimensions, telemetryProducer) => new DefaultCacheMonitor(dimensions, telemetryProducer); if (this.BlockPoolMonitorFactory == null) this.BlockPoolMonitorFactory = (dimensions, telemetryProducer) => new DefaultBlockPoolMonitor(dimensions, telemetryProducer); if (this.ReceiverMonitorFactory == null) this.ReceiverMonitorFactory = (dimensions, telemetryProducer) => new DefaultQueueAdapterReceiverMonitor(dimensions, telemetryProducer); generatorConfig = this.serviceProvider.GetServiceByName<IStreamGeneratorConfig>(this.Name); if(generatorConfig == null) { this.logger.LogInformation("No generator configuration found for stream provider {0}. Inactive until provided with configuration by command.", this.Name); } } private void CreateBufferPoolIfNotCreatedYet() { if (this.bufferPool == null) { // 1 meg block size pool this.blockPoolMonitorDimensions = new BlockPoolMonitorDimensions($"BlockPool-{Guid.NewGuid()}"); var oneMb = 1 << 20; var objectPoolMonitor = new ObjectPoolMonitorBridge(this.BlockPoolMonitorFactory(blockPoolMonitorDimensions, this.telemetryProducer), oneMb); this.bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(oneMb), objectPoolMonitor, this.statisticOptions.StatisticMonitorWriteInterval); } } /// <summary> /// Create an adapter /// </summary> /// <returns></returns> public Task<IQueueAdapter> CreateAdapter() { return Task.FromResult<IQueueAdapter>(this); } /// <summary> /// Get the cache adapter /// </summary> /// <returns></returns> public IQueueAdapterCache GetQueueAdapterCache() { return this; } /// <summary> /// Get the stream queue mapper /// </summary> /// <returns></returns> public IStreamQueueMapper GetStreamQueueMapper() { return streamQueueMapper ?? (streamQueueMapper = new HashRingBasedStreamQueueMapper(this.queueMapperOptions, this.Name)); } /// <summary> /// Get the delivery failure handler /// </summary> /// <param name="queueId"></param> /// <returns></returns> public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId) { return Task.FromResult(streamFailureHandler ?? (streamFailureHandler = new NoOpStreamDeliveryFailureHandler())); } /// <summary> /// Stores a batch of messages /// </summary> /// <typeparam name="T"></typeparam> /// <param name="streamGuid"></param> /// <param name="streamNamespace"></param> /// <param name="events"></param> /// <param name="token"></param> /// <param name="requestContext"></param> /// <returns></returns> public Task QueueMessageBatchAsync<T>(Guid streamGuid, string streamNamespace, IEnumerable<T> events, StreamSequenceToken token, Dictionary<string, object> requestContext) { return Task.CompletedTask; } /// <summary> /// Creates a quere receiver for the specificed queueId /// </summary> /// <param name="queueId"></param> /// <returns></returns> public IQueueAdapterReceiver CreateReceiver(QueueId queueId) { var dimensions = new ReceiverMonitorDimensions(queueId.ToString()); var receiverMonitor = this.ReceiverMonitorFactory(dimensions, this.telemetryProducer); Receiver receiver = receivers.GetOrAdd(queueId, qid => new Receiver(receiverMonitor)); SetGeneratorOnReciever(receiver); return receiver; } /// <summary> /// A function to execute a control command. /// </summary> /// <param name="command">A serial number of the command.</param> /// <param name="arg">An opaque command argument</param> public Task<object> ExecuteCommand(int command, object arg) { if (arg == null) { throw new ArgumentNullException("arg"); } generatorConfig = arg as IStreamGeneratorConfig; if (generatorConfig == null) { throw new ArgumentOutOfRangeException("arg", "Arg must by of type IStreamGeneratorConfig"); } // update generator on recievers foreach (Receiver receiver in receivers.Values) { SetGeneratorOnReciever(receiver); } return Task.FromResult<object>(true); } private class Receiver : IQueueAdapterReceiver { const int MaxDelayMs = 20; private readonly Random random = new Random((int)DateTime.UtcNow.Ticks % int.MaxValue); private IQueueAdapterReceiverMonitor receiverMonitor; public IStreamGenerator QueueGenerator { private get; set; } public Receiver(IQueueAdapterReceiverMonitor receiverMonitor) { this.receiverMonitor = receiverMonitor; } public Task Initialize(TimeSpan timeout) { this.receiverMonitor?.TrackInitialization(true, TimeSpan.MinValue, null); return Task.CompletedTask; } public async Task<IList<IBatchContainer>> GetQueueMessagesAsync(int maxCount) { var watch = Stopwatch.StartNew(); await Task.Delay(random.Next(1,MaxDelayMs)); List<IBatchContainer> batches; if (QueueGenerator == null || !QueueGenerator.TryReadEvents(DateTime.UtcNow, out batches)) { return new List<IBatchContainer>(); } watch.Stop(); this.receiverMonitor?.TrackRead(true, watch.Elapsed, null); if (batches.Count > 0) { var oldestMessage = batches[0] as GeneratedBatchContainer; var newestMessage = batches[batches.Count - 1] as GeneratedBatchContainer; this.receiverMonitor?.TrackMessagesReceived(batches.Count, oldestMessage?.EnqueueTimeUtc, newestMessage?.EnqueueTimeUtc); } return batches; } public Task MessagesDeliveredAsync(IList<IBatchContainer> messages) { return Task.CompletedTask; } public Task Shutdown(TimeSpan timeout) { this.receiverMonitor?.TrackShutdown(true, TimeSpan.MinValue, null); return Task.CompletedTask; } } private void SetGeneratorOnReciever(Receiver receiver) { // if we don't have generator configuration, don't set generator if (generatorConfig == null) { return; } var generator = (IStreamGenerator)(serviceProvider?.GetService(generatorConfig.StreamGeneratorType) ?? Activator.CreateInstance(generatorConfig.StreamGeneratorType)); if (generator == null) { throw new OrleansException($"StreamGenerator type not supported: {generatorConfig.StreamGeneratorType}"); } generator.Configure(serviceProvider, generatorConfig); receiver.QueueGenerator = generator; } /// <summary> /// Create a cache for a given queue id /// </summary> /// <param name="queueId"></param> public IQueueCache CreateQueueCache(QueueId queueId) { //move block pool creation from init method to here, to avoid unnecessary block pool creation when stream provider is initialized in client side. CreateBufferPoolIfNotCreatedYet(); var dimensions = new CacheMonitorDimensions(queueId.ToString(), this.blockPoolMonitorDimensions.BlockPoolId); var cacheMonitor = this.CacheMonitorFactory(dimensions, this.telemetryProducer); return new GeneratorPooledCache(bufferPool, this.loggerFactory.CreateLogger($"{typeof(GeneratorPooledCache).FullName}.{this.Name}.{queueId}"), serializationManager, cacheMonitor, this.statisticOptions.StatisticMonitorWriteInterval); } public static GeneratorAdapterFactory Create(IServiceProvider services, string name) { var queueMapperOptions = services.GetOptionsByName<HashRingStreamQueueMapperOptions>(name); var statisticOptions = services.GetOptionsByName<StreamStatisticOptions>(name); var factory = ActivatorUtilities.CreateInstance<GeneratorAdapterFactory>(services, name, queueMapperOptions, statisticOptions); factory.Init(); return factory; } } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; using FILE = System.IO.TextWriter; using i64 = System.Int64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; using u64 = System.UInt64; using unsigned = System.UIntPtr; using Pgno = System.UInt32; #if !SQLITE_MAX_VARIABLE_NUMBER using ynVar = System.Int16; #else using ynVar = System.Int32; #endif /* ** The yDbMask datatype for the bitmask of all attached databases. */ #if SQLITE_MAX_ATTACHED//>30 // typedef sqlite3_uint64 yDbMask; using yDbMask = System.Int64; #else // typedef unsigned int yDbMask; using yDbMask = System.Int32; #endif namespace Community.CsharpSqlite { using Op = Sqlite3.VdbeOp; public partial class Sqlite3 { /* ** 2003 September 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the header file for information that is private to the ** VDBE. This information used to all be at the top of the single ** source code file "vdbe.c". When that file became too big (over ** 6000 lines long) it was split up into several smaller files and ** this header information was factored out. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ //#if !_VDBEINT_H_ //#define _VDBEINT_H_ /* ** SQL is translated into a sequence of instructions to be ** executed by a virtual machine. Each instruction is an instance ** of the following structure. */ //typedef struct VdbeOp Op; /* ** Boolean values */ //typedef unsigned char Bool; /* ** A cursor is a pointer into a single BTree within a database file. ** The cursor can seek to a BTree entry with a particular key, or ** loop over all entries of the Btree. You can also insert new BTree ** entries or retrieve the key or data from the entry that the cursor ** is currently pointing to. ** ** Every cursor that the virtual machine has open is represented by an ** instance of the following structure. */ public class VdbeCursor { public BtCursor pCursor; /* The cursor structure of the backend */ public Btree pBt; /* Separate file holding temporary table */ public KeyInfo pKeyInfo; /* Info about index keys needed by index cursors */ public int iDb; /* Index of cursor database in db->aDb[] (or -1) */ public int pseudoTableReg; /* Register holding pseudotable content. */ public int nField; /* Number of fields in the header */ public bool zeroed; /* True if zeroed out and ready for reuse */ public bool rowidIsValid; /* True if lastRowid is valid */ public bool atFirst; /* True if pointing to first entry */ public bool useRandomRowid; /* Generate new record numbers semi-randomly */ public bool nullRow; /* True if pointing to a row with no data */ public bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */ public bool isTable; /* True if a table requiring integer keys */ public bool isIndex; /* True if an index containing keys only - no data */ public bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */ #if !SQLITE_OMIT_VIRTUALTABLE public sqlite3_vtab_cursor pVtabCursor; /* The cursor for a virtual table */ public readonly sqlite3_module pModule; /* Module for cursor pVtabCursor */ #endif public i64 seqCount; /* Sequence counter */ public i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */ public i64 lastRowid; /* Last rowid from a Next or NextIdx operation */ /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or ** OP_IsUnique opcode on this cursor. */ public int seekResult; /* Cached information about the header for the data record that the ** cursor is currently pointing to. Only valid if cacheStatus matches ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that ** the cache is out of date. ** ** aRow might point to (ephemeral) data for the current row, or it might ** be NULL. */ public u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */ public Pgno payloadSize; /* Total number of bytes in the record */ public u32[] aType; /* Type values for all entries in the record */ public u32[] aOffset; /* Cached offsets to the start of each columns data */ public int aRow; /* Pointer to Data for the current row, if all on one page */ public VdbeCursor Copy() { return (VdbeCursor)MemberwiseClone(); } }; //typedef struct VdbeCursor VdbeCursor; /* ** When a sub-program is executed (OP_Program), a structure of this type ** is allocated to store the current value of the program counter, as ** well as the current memory cell array and various other frame specific ** values stored in the Vdbe struct. When the sub-program is finished, ** these values are copied back to the Vdbe from the VdbeFrame structure, ** restoring the state of the VM to as it was before the sub-program ** began executing. ** ** The memory for a VdbeFrame object is allocated and managed by a memory ** cell in the parent (calling) frame. When the memory cell is deleted or ** overwritten, the VdbeFrame object is not freed immediately. Instead, it ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing ** this instead of deleting the VdbeFrame immediately is to avoid recursive ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the ** child frame are released. ** ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is ** set to NULL if the currently executing frame is the main program. */ //typedef struct VdbeFrame VdbeFrame; public class VdbeFrame { public Vdbe v; /* VM this frame belongs to */ public int pc; /* Program Counter in parent (calling) frame */ public Op[] aOp; /* Program instructions for parent frame */ public int nOp; /* Size of aOp array */ public Mem[] aMem; /* Array of memory cells for parent frame */ public int nMem; /* Number of entries in aMem */ public VdbeCursor[] apCsr; /* Array of Vdbe cursors for parent frame */ public u16 nCursor; /* Number of entries in apCsr */ public int token; /* Copy of SubProgram.token */ public int nChildMem; /* Number of memory cells for child frame */ public int nChildCsr; /* Number of cursors for child frame */ public i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */ public int nChange; /* Statement changes (Vdbe.nChanges) */ public VdbeFrame pParent; /* Parent of this frame, or NULL if parent is main */ // // Needed for C# Implementation // public Mem[] aChildMem; /* Array of memory cells for child frame */ public VdbeCursor[] aChildCsr; /* Array of cursors for child frame */ }; //#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))]) /* ** A value for VdbeCursor.cacheValid that means the cache is always invalid. */ const int CACHE_STALE = 0; /* ** Internally, the vdbe manipulates nearly all SQL values as Mem ** structures. Each Mem struct may cache multiple representations (string, ** integer etc.) of the same value. */ public class Mem { public sqlite3 db; /* The associated database connection */ public string z; /* String value */ public double r; /* Real value */ public struct union_ip { #if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL public i64 _i; /* First operand */ public i64 i { get { return _i; } set { _i = value; } } #else public i64 i; /* Integer value used when MEM_Int is set in flags */ #endif public int nZero; /* Used when bit MEM_Zero is set in flags */ public FuncDef pDef; /* Used only when flags==MEM_Agg */ public RowSet pRowSet; /* Used only when flags==MEM_RowSet */ public VdbeFrame pFrame; /* Used when flags==MEM_Frame */ }; public union_ip u; public byte[] zBLOB; /* BLOB value */ public int n; /* Number of characters in string value, excluding '\0' */ #if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL public u16 _flags; /* First operand */ public u16 flags { get { return _flags; } set { _flags = value; } } #else public u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */ #endif public u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */ public u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */ #if SQLITE_DEBUG public Mem pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */ public object pFiller; /* So that sizeof(Mem) is a multiple of 8 */ #endif public dxDel xDel; /* If not null, call this function to delete Mem.z */ // Not used under c# //public string zMalloc; /* Dynamic buffer allocated by sqlite3Malloc() */ public Mem _Mem; /* Used when C# overload Z as MEM space */ public SumCtx _SumCtx; /* Used when C# overload Z as Sum context */ public SubProgram[] _SubProgram;/* Used when C# overload Z as SubProgram*/ public StrAccum _StrAccum; /* Used when C# overload Z as STR context */ public object _MD5Context; /* Used when C# overload Z as MD5 context */ public Mem() { } public Mem( sqlite3 db, string z, double r, int i, int n, u16 flags, u8 type, u8 enc #if SQLITE_DEBUG , Mem pScopyFrom, object pFiller /* pScopyFrom, pFiller */ #endif ) { this.db = db; this.z = z; this.r = r; this.u.i = i; this.n = n; this.flags = flags; #if SQLITE_DEBUG this.pScopyFrom = pScopyFrom; this.pFiller = pFiller; #endif this.type = type; this.enc = enc; } public void CopyTo( ref Mem ct ) { if ( ct == null ) ct = new Mem(); ct.u = u; ct.r = r; ct.db = db; ct.z = z; if ( zBLOB == null ) ct.zBLOB = null; else { ct.zBLOB = sqlite3Malloc( zBLOB.Length ); Buffer.BlockCopy( zBLOB, 0, ct.zBLOB, 0, zBLOB.Length ); } ct.n = n; ct.flags = flags; ct.type = type; ct.enc = enc; ct.xDel = xDel; } }; /* One or more of the following flags are set to indicate the validOK ** representations of the value stored in the Mem struct. ** ** If the MEM_Null flag is set, then the value is an SQL NULL value. ** No other flags may be set in this case. ** ** If the MEM_Str flag is set then Mem.z points at a string representation. ** Usually this is encoded in the same unicode encoding as the main ** database (see below for exceptions). If the MEM_Term flag is also ** set, then the string is nul terminated. The MEM_Int and MEM_Real ** flags may coexist with the MEM_Str flag. */ //#define MEM_Null 0x0001 /* Value is NULL */ //#define MEM_Str 0x0002 /* Value is a string */ //#define MEM_Int 0x0004 /* Value is an integer */ //#define MEM_Real 0x0008 /* Value is a real number */ //#define MEM_Blob 0x0010 /* Value is a BLOB */ //#define MEM_RowSet 0x0020 /* Value is a RowSet object */ //#define MEM_Frame 0x0040 /* Value is a VdbeFrame object */ //#define MEM_Invalid 0x0080 /* Value is undefined */ //#define MEM_TypeMask 0x00ff /* Mask of type bits */ const int MEM_Null = 0x0001; const int MEM_Str = 0x0002; const int MEM_Int = 0x0004; const int MEM_Real = 0x0008; const int MEM_Blob = 0x0010; const int MEM_RowSet = 0x0020; const int MEM_Frame = 0x0040; const int MEM_Invalid = 0x0080; const int MEM_TypeMask = 0x00ff; /* Whenever Mem contains a valid string or blob representation, one of ** the following flags must be set to determine the memory management ** policy for Mem.z. The MEM_Term flag tells us whether or not the ** string is \000 or \u0000 terminated // */ //#define MEM_Term 0x0200 /* String rep is nul terminated */ //#define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */ //#define MEM_Static 0x0800 /* Mem.z points to a static string */ //#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */ //#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */ //#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */ //#ifdef SQLITE_OMIT_INCRBLOB // #undef MEM_Zero // #define MEM_Zero 0x0000 //#endif const int MEM_Term = 0x0200; const int MEM_Dyn = 0x0400; const int MEM_Static = 0x0800; const int MEM_Ephem = 0x1000; const int MEM_Agg = 0x2000; #if !SQLITE_OMIT_INCRBLOB const int MEM_Zero = 0x4000; #else const int MEM_Zero = 0x0000; #endif /* ** Clear any existing type flags from a Mem and replace them with f */ //#define MemSetTypeFlag(p, f) \ // ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f) static void MemSetTypeFlag( Mem p, int f ) { p.flags = (u16)( p.flags & ~( MEM_TypeMask | MEM_Zero ) | f ); }// TODO -- Convert back to inline for speed /* ** Return true if a memory cell is not marked as invalid. This macro ** is for use inside assert() statements only. */ #if SQLITE_DEBUG //#define memIsValid(M) ((M)->flags & MEM_Invalid)==0 static bool memIsValid( Mem M ) { return ( ( M ).flags & MEM_Invalid ) == 0; } #else static bool memIsValid( Mem M ) { return true; } #endif /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains ** additional information about auxiliary information bound to arguments ** of the function. This is used to implement the sqlite3_get_auxdata() ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data ** that can be associated with a constant argument to a function. This ** allows functions such as "regexp" to compile their constant regular ** expression argument once and reused the compiled code for multiple ** invocations. */ public class AuxData { public object pAux; /* Aux data for the i-th argument */ //(void *); /* Destructor for the aux data */ }; public class VdbeFunc : FuncDef { public FuncDef pFunc; /* The definition of the function */ public int nAux; /* Number of entries allocated for apAux[] */ public AuxData[] apAux = new AuxData[2]; /* One slot for each function argument */ }; /* ** The "context" argument for a installable function. A pointer to an ** instance of this structure is the first argument to the routines used ** implement the SQL functions. ** ** There is a typedef for this structure in sqlite.h. So all routines, ** even the public interface to SQLite, can use a pointer to this structure. ** But this file is the only place where the internal details of this ** structure are known. ** ** This structure is defined inside of vdbeInt.h because it uses substructures ** (Mem) which are only defined there. */ public class sqlite3_context { public FuncDef pFunc; /* Pointer to function information. MUST BE FIRST */ public VdbeFunc pVdbeFunc; /* Auxilary data, if created. */ public Mem s = new Mem(); /* The return value is stored here */ public Mem pMem; /* Memory cell used to store aggregate context */ public int isError; /* Error code returned by the function. */ public CollSeq pColl; /* Collating sequence */ }; /* ** An instance of the virtual machine. This structure contains the complete ** state of the virtual machine. ** ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare() ** is really a pointer to an instance of this structure. ** ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of ** any virtual table method invocations made by the vdbe program. It is ** set to 2 for xDestroy method calls and 1 for all other methods. This ** variable is used for two purposes: to allow xDestroy methods to execute ** "DROP TABLE" statements and to prevent some nasty side effects of ** malloc failure when SQLite is invoked recursively by a virtual table ** method function. */ public class Vdbe { public sqlite3 db; /* The database connection that owns this statement */ public Op[] aOp; /* Space to hold the virtual machine's program */ public Mem[] aMem; /* The memory locations */ public Mem[] apArg; /* Arguments to currently executing user function */ public Mem[] aColName; /* Column names to return */ public Mem[] pResultSet; /* Pointer to an array of results */ public int nMem; /* Number of memory locations currently allocated */ public int nOp; /* Number of instructions in the program */ public int nOpAlloc; /* Number of slots allocated for aOp[] */ public int nLabel; /* Number of labels used */ public int nLabelAlloc; /* Number of slots allocated in aLabel[] */ public int[] aLabel; /* Space to hold the labels */ public u16 nResColumn; /* Number of columns in one row of the result set */ public u16 nCursor; /* Number of slots in apCsr[] */ public u32 magic; /* Magic number for sanity checking */ public string zErrMsg; /* Error message written here */ public Vdbe pPrev; /* Linked list of VDBEs with the same Vdbe.db */ public Vdbe pNext; /* Linked list of VDBEs with the same Vdbe.db */ public VdbeCursor[] apCsr; /* One element of this array for each open cursor */ public Mem[] aVar; /* Values for the OP_Variable opcode. */ public string[] azVar; /* Name of variables */ public ynVar nVar; /* Number of entries in aVar[] */ public u32 cacheCtr; /* VdbeCursor row cache generation counter */ public int pc; /* The program counter */ public int rc; /* Value to return */ public u8 errorAction; /* Recovery action to do in case of an error */ public u8 okVar; /* True if azVar[] has been initialized */ public int explain; /* True if EXPLAIN present on SQL command */ public bool changeCntOn; /* True to update the change-counter */ public bool expired; /* True if the VM needs to be recompiled */ public u8 runOnlyOnce; /* Automatically expire on reset */ public int minWriteFileFormat; /* Minimum file format for writable database files */ public int inVtabMethod; /* See comments above */ public bool usesStmtJournal; /* True if uses a statement journal */ public bool readOnly; /* True for read-only statements */ public int nChange; /* Number of db changes made since last reset */ public bool isPrepareV2; /* True if prepared with prepare_v2() */ public yDbMask btreeMask; /* Bitmask of db.aDb[] entries referenced */ public yDbMask lockMask; /* Subset of btreeMask that requires a lock */ public int iStatement; /* Statement number (or 0 if has not opened stmt) */ public int[] aCounter = new int[3]; /* Counters used by sqlite3_stmt_status() */ #if !SQLITE_OMIT_TRACE public i64 startTime; /* Time when query started - used for profiling */ #endif public i64 nFkConstraint; /* Number of imm. FK constraints this VM */ public i64 nStmtDefCons; /* Number of def. constraints when stmt started */ public string zSql = ""; /* Text of the SQL statement that generated this */ public object pFree; /* Free this when deleting the vdbe */ #if SQLITE_DEBUG public FILE trace; /* Write an execution trace here, if not NULL */ #endif public VdbeFrame pFrame; /* Parent frame */ public VdbeFrame pDelFrame; /* List of frame objects to free on VM reset */ public int nFrame; /* Number of frames in pFrame list */ public u32 expmask; /* Binding to these vars invalidates VM */ public SubProgram pProgram; /* Linked list of all sub-programs used by VM */ public Vdbe Copy() { Vdbe cp = (Vdbe)MemberwiseClone(); return cp; } public void CopyTo( Vdbe ct ) { ct.db = db; ct.pPrev = pPrev; ct.pNext = pNext; ct.nOp = nOp; ct.nOpAlloc = nOpAlloc; ct.aOp = aOp; ct.nLabel = nLabel; ct.nLabelAlloc = nLabelAlloc; ct.aLabel = aLabel; ct.apArg = apArg; ct.aColName = aColName; ct.nCursor = nCursor; ct.apCsr = apCsr; ct.nVar = nVar; ct.aVar = aVar; ct.azVar = azVar; ct.okVar = okVar; ct.magic = magic; ct.nMem = nMem; ct.aMem = aMem; ct.cacheCtr = cacheCtr; ct.pc = pc; ct.rc = rc; ct.errorAction = errorAction; ct.nResColumn = nResColumn; ct.zErrMsg = zErrMsg; ct.pResultSet = pResultSet; ct.explain = explain; ct.changeCntOn = changeCntOn; ct.expired = expired; ct.minWriteFileFormat = minWriteFileFormat; ct.inVtabMethod = inVtabMethod; ct.usesStmtJournal = usesStmtJournal; ct.readOnly = readOnly; ct.nChange = nChange; ct.isPrepareV2 = isPrepareV2; #if !SQLITE_OMIT_TRACE ct.startTime = startTime; #endif ct.btreeMask = btreeMask; ct.lockMask = lockMask; aCounter.CopyTo( ct.aCounter, 0 ); ct.zSql = zSql; ct.pFree = pFree; #if SQLITE_DEBUG ct.trace = trace; #endif ct.nFkConstraint = nFkConstraint; ct.nStmtDefCons = nStmtDefCons; ct.iStatement = iStatement; ct.pFrame = pFrame; ct.nFrame = nFrame; ct.expmask = expmask; ct.pProgram = pProgram; #if SQLITE_SSE ct.fetchId=fetchId; ct.lru=lru; #endif #if SQLITE_ENABLE_MEMORY_MANAGEMENT ct.pLruPrev=pLruPrev; ct.pLruNext=pLruNext; #endif } }; /* ** The following are allowed values for Vdbe.magic */ //#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */ //#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */ //#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */ //#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */ const u32 VDBE_MAGIC_INIT = 0x26bceaa5; /* Building a VDBE program */ const u32 VDBE_MAGIC_RUN = 0xbdf20da3; /* VDBE is ready to execute */ const u32 VDBE_MAGIC_HALT = 0x519c2973; /* VDBE has completed execution */ const u32 VDBE_MAGIC_DEAD = 0xb606c3c8; /* The VDBE has been deallocated */ /* ** Function prototypes */ //void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*); //void sqliteVdbePopStack(Vdbe*,int); //int sqlite3VdbeCursorMoveto(VdbeCursor*); //#if (SQLITE_DEBUG) || defined(VDBE_PROFILE) //void sqlite3VdbePrintOp(FILE*, int, Op*); //#endif //u32 sqlite3VdbeSerialTypeLen(u32); //u32 sqlite3VdbeSerialType(Mem*, int); //u32sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int); //u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*); //void sqlite3VdbeDeleteAuxData(VdbeFunc*, int); //int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *); //int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*); //int sqlite3VdbeIdxRowid(sqlite3 *, i64 *); //int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*); //int sqlite3VdbeExec(Vdbe*); //int sqlite3VdbeList(Vdbe*); //int sqlite3VdbeHalt(Vdbe*); //int sqlite3VdbeChangeEncoding(Mem *, int); //int sqlite3VdbeMemTooBig(Mem*); //int sqlite3VdbeMemCopy(Mem*, const Mem*); //void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); //void sqlite3VdbeMemMove(Mem*, Mem*); //int sqlite3VdbeMemNulTerminate(Mem*); //int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*)); //void sqlite3VdbeMemSetInt64(Mem*, i64); #if SQLITE_OMIT_FLOATING_POINT //# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64 #else //void sqlite3VdbeMemSetDouble(Mem*, double); #endif //void sqlite3VdbeMemSetNull(Mem*); //void sqlite3VdbeMemSetZeroBlob(Mem*,int); //void sqlite3VdbeMemSetRowSet(Mem*); //int sqlite3VdbeMemMakeWriteable(Mem*); //int sqlite3VdbeMemStringify(Mem*, int); //i64 sqlite3VdbeIntValue(Mem*); //int sqlite3VdbeMemIntegerify(Mem*); //double sqlite3VdbeRealValue(Mem*); //void sqlite3VdbeIntegerAffinity(Mem*); //int sqlite3VdbeMemRealify(Mem*); //int sqlite3VdbeMemNumerify(Mem*); //int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*); //void sqlite3VdbeMemRelease(Mem p); //void sqlite3VdbeMemReleaseExternal(Mem p); //int sqlite3VdbeMemFinalize(Mem*, FuncDef*); //const char *sqlite3OpcodeName(int); //int sqlite3VdbeMemGrow(Mem pMem, int n, int preserve); //int sqlite3VdbeCloseStatement(Vdbe *, int); //void sqlite3VdbeFrameDelete(VdbeFrame*); //int sqlite3VdbeFrameRestore(VdbeFrame *); //void sqlite3VdbeMemStoreType(Mem *pMem); #if !(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE//>0 //void sqlite3VdbeEnter(Vdbe*); //void sqlite3VdbeLeave(Vdbe*); #else //# define sqlite3VdbeEnter(X) static void sqlite3VdbeEnter( Vdbe p ) { } //# define sqlite3VdbeLeave(X) static void sqlite3VdbeLeave( Vdbe p ) { } #endif #if SQLITE_DEBUG //void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*); #endif #if !SQLITE_OMIT_FOREIGN_KEY //int sqlite3VdbeCheckFk(Vdbe *, int); #else //# define sqlite3VdbeCheckFk(p,i) 0 static int sqlite3VdbeCheckFk( Vdbe p, int i ) { return 0; } #endif //int sqlite3VdbeMemTranslate(Mem*, u8); //#if SQLITE_DEBUG // void sqlite3VdbePrintSql(Vdbe*); // void sqlite3VdbeMemPrettyPrint(Mem pMem, char *zBuf); //#endif //int sqlite3VdbeMemHandleBom(Mem pMem); #if !SQLITE_OMIT_INCRBLOB // int sqlite3VdbeMemExpandBlob(Mem *); #else // #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK static int sqlite3VdbeMemExpandBlob( Mem x ) { return SQLITE_OK; } #endif //#endif //* !_VDBEINT_H_) */ } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * 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. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// Description /// First published in Citrix Hypervisor 8.2. /// </summary> public partial class Certificate : XenObject<Certificate> { #region Constructors public Certificate() { } public Certificate(string uuid, string name, certificate_type type, XenRef<Host> host, DateTime not_before, DateTime not_after, string fingerprint) { this.uuid = uuid; this.name = name; this.type = type; this.host = host; this.not_before = not_before; this.not_after = not_after; this.fingerprint = fingerprint; } /// <summary> /// Creates a new Certificate from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Certificate(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Certificate from a Proxy_Certificate. /// </summary> /// <param name="proxy"></param> public Certificate(Proxy_Certificate proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Certificate. /// </summary> public override void UpdateFrom(Certificate record) { uuid = record.uuid; name = record.name; type = record.type; host = record.host; not_before = record.not_before; not_after = record.not_after; fingerprint = record.fingerprint; } internal void UpdateFrom(Proxy_Certificate proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; name = proxy.name == null ? null : proxy.name; type = proxy.type == null ? (certificate_type) 0 : (certificate_type)Helper.EnumParseDefault(typeof(certificate_type), (string)proxy.type); host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host); not_before = proxy.not_before; not_after = proxy.not_after; fingerprint = proxy.fingerprint == null ? null : proxy.fingerprint; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Certificate /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("name")) name = Marshalling.ParseString(table, "name"); if (table.ContainsKey("type")) type = (certificate_type)Helper.EnumParseDefault(typeof(certificate_type), Marshalling.ParseString(table, "type")); if (table.ContainsKey("host")) host = Marshalling.ParseRef<Host>(table, "host"); if (table.ContainsKey("not_before")) not_before = Marshalling.ParseDateTime(table, "not_before"); if (table.ContainsKey("not_after")) not_after = Marshalling.ParseDateTime(table, "not_after"); if (table.ContainsKey("fingerprint")) fingerprint = Marshalling.ParseString(table, "fingerprint"); } public Proxy_Certificate ToProxy() { Proxy_Certificate result_ = new Proxy_Certificate(); result_.uuid = uuid ?? ""; result_.name = name ?? ""; result_.type = certificate_type_helper.ToString(type); result_.host = host ?? ""; result_.not_before = not_before; result_.not_after = not_after; result_.fingerprint = fingerprint ?? ""; return result_; } public bool DeepEquals(Certificate other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name, other._name) && Helper.AreEqual2(this._type, other._type) && Helper.AreEqual2(this._host, other._host) && Helper.AreEqual2(this._not_before, other._not_before) && Helper.AreEqual2(this._not_after, other._not_after) && Helper.AreEqual2(this._fingerprint, other._fingerprint); } public override string SaveChanges(Session session, string opaqueRef, Certificate server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given Certificate. /// First published in Citrix Hypervisor 8.2. /// </summary> /// <param name="session">The session</param> /// <param name="_certificate">The opaque_ref of the given certificate</param> public static Certificate get_record(Session session, string _certificate) { if (session.JsonRpcClient != null) return session.JsonRpcClient.certificate_get_record(session.opaque_ref, _certificate); else return new Certificate(session.XmlRpcProxy.certificate_get_record(session.opaque_ref, _certificate ?? "").parse()); } /// <summary> /// Get a reference to the Certificate instance with the specified UUID. /// First published in Citrix Hypervisor 8.2. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Certificate> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.certificate_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Certificate>.Create(session.XmlRpcProxy.certificate_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given Certificate. /// First published in Citrix Hypervisor 8.2. /// </summary> /// <param name="session">The session</param> /// <param name="_certificate">The opaque_ref of the given certificate</param> public static string get_uuid(Session session, string _certificate) { if (session.JsonRpcClient != null) return session.JsonRpcClient.certificate_get_uuid(session.opaque_ref, _certificate); else return session.XmlRpcProxy.certificate_get_uuid(session.opaque_ref, _certificate ?? "").parse(); } /// <summary> /// Get the name field of the given Certificate. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_certificate">The opaque_ref of the given certificate</param> public static string get_name(Session session, string _certificate) { if (session.JsonRpcClient != null) return session.JsonRpcClient.certificate_get_name(session.opaque_ref, _certificate); else return session.XmlRpcProxy.certificate_get_name(session.opaque_ref, _certificate ?? "").parse(); } /// <summary> /// Get the type field of the given Certificate. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_certificate">The opaque_ref of the given certificate</param> public static certificate_type get_type(Session session, string _certificate) { if (session.JsonRpcClient != null) return session.JsonRpcClient.certificate_get_type(session.opaque_ref, _certificate); else return (certificate_type)Helper.EnumParseDefault(typeof(certificate_type), (string)session.XmlRpcProxy.certificate_get_type(session.opaque_ref, _certificate ?? "").parse()); } /// <summary> /// Get the host field of the given Certificate. /// First published in Citrix Hypervisor 8.2. /// </summary> /// <param name="session">The session</param> /// <param name="_certificate">The opaque_ref of the given certificate</param> public static XenRef<Host> get_host(Session session, string _certificate) { if (session.JsonRpcClient != null) return session.JsonRpcClient.certificate_get_host(session.opaque_ref, _certificate); else return XenRef<Host>.Create(session.XmlRpcProxy.certificate_get_host(session.opaque_ref, _certificate ?? "").parse()); } /// <summary> /// Get the not_before field of the given Certificate. /// First published in Citrix Hypervisor 8.2. /// </summary> /// <param name="session">The session</param> /// <param name="_certificate">The opaque_ref of the given certificate</param> public static DateTime get_not_before(Session session, string _certificate) { if (session.JsonRpcClient != null) return session.JsonRpcClient.certificate_get_not_before(session.opaque_ref, _certificate); else return session.XmlRpcProxy.certificate_get_not_before(session.opaque_ref, _certificate ?? "").parse(); } /// <summary> /// Get the not_after field of the given Certificate. /// First published in Citrix Hypervisor 8.2. /// </summary> /// <param name="session">The session</param> /// <param name="_certificate">The opaque_ref of the given certificate</param> public static DateTime get_not_after(Session session, string _certificate) { if (session.JsonRpcClient != null) return session.JsonRpcClient.certificate_get_not_after(session.opaque_ref, _certificate); else return session.XmlRpcProxy.certificate_get_not_after(session.opaque_ref, _certificate ?? "").parse(); } /// <summary> /// Get the fingerprint field of the given Certificate. /// First published in Citrix Hypervisor 8.2. /// </summary> /// <param name="session">The session</param> /// <param name="_certificate">The opaque_ref of the given certificate</param> public static string get_fingerprint(Session session, string _certificate) { if (session.JsonRpcClient != null) return session.JsonRpcClient.certificate_get_fingerprint(session.opaque_ref, _certificate); else return session.XmlRpcProxy.certificate_get_fingerprint(session.opaque_ref, _certificate ?? "").parse(); } /// <summary> /// Return a list of all the Certificates known to the system. /// First published in Citrix Hypervisor 8.2. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Certificate>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.certificate_get_all(session.opaque_ref); else return XenRef<Certificate>.Create(session.XmlRpcProxy.certificate_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the Certificate Records at once, in a single XML RPC call /// First published in Citrix Hypervisor 8.2. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Certificate>, Certificate> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.certificate_get_all_records(session.opaque_ref); else return XenRef<Certificate>.Create<Proxy_Certificate>(session.XmlRpcProxy.certificate_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// The name of the certificate, only present on certificates of type 'ca' /// First published in Unreleased. /// </summary> public virtual string name { get { return _name; } set { if (!Helper.AreEqual(value, _name)) { _name = value; NotifyPropertyChanged("name"); } } } private string _name = ""; /// <summary> /// The type of the certificate, either 'ca', 'host' or 'host_internal' /// First published in Unreleased. /// </summary> [JsonConverter(typeof(certificate_typeConverter))] public virtual certificate_type type { get { return _type; } set { if (!Helper.AreEqual(value, _type)) { _type = value; NotifyPropertyChanged("type"); } } } private certificate_type _type = certificate_type.host; /// <summary> /// The host where the certificate is installed /// </summary> [JsonConverter(typeof(XenRefConverter<Host>))] public virtual XenRef<Host> host { get { return _host; } set { if (!Helper.AreEqual(value, _host)) { _host = value; NotifyPropertyChanged("host"); } } } private XenRef<Host> _host = new XenRef<Host>("OpaqueRef:NULL"); /// <summary> /// Date after which the certificate is valid /// </summary> [JsonConverter(typeof(XenDateTimeConverter))] public virtual DateTime not_before { get { return _not_before; } set { if (!Helper.AreEqual(value, _not_before)) { _not_before = value; NotifyPropertyChanged("not_before"); } } } private DateTime _not_before = DateTime.ParseExact("19700101T00:00:00Z", "yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture); /// <summary> /// Date before which the certificate is valid /// </summary> [JsonConverter(typeof(XenDateTimeConverter))] public virtual DateTime not_after { get { return _not_after; } set { if (!Helper.AreEqual(value, _not_after)) { _not_after = value; NotifyPropertyChanged("not_after"); } } } private DateTime _not_after = DateTime.ParseExact("19700101T00:00:00Z", "yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture); /// <summary> /// The certificate's fingerprint / hash /// </summary> public virtual string fingerprint { get { return _fingerprint; } set { if (!Helper.AreEqual(value, _fingerprint)) { _fingerprint = value; NotifyPropertyChanged("fingerprint"); } } } private string _fingerprint = ""; } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using MyMeta; namespace MyGeneration { /// <summary> /// Summary description for AddLanguageMappingDialog. /// </summary> public class AddLanguageMappingDialog : System.Windows.Forms.Form { private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.TextBox txtTo; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cboxBasedUpon; private System.Windows.Forms.Label label3; public string BasedUpon = string.Empty; public string NewLanguage = string.Empty; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public AddLanguageMappingDialog(string[] languages, string dbDriver) { InitializeComponent(); this.Text += " for " + dbDriver; if(languages != null) { for(int i = 0; i < languages.Length; i++) { this.cboxBasedUpon.Items.Add(languages[i]); } } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(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.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.txtTo = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.cboxBasedUpon = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // btnOK // this.btnOK.Location = new System.Drawing.Point(328, 104); this.btnOK.Name = "btnOK"; this.btnOK.TabIndex = 2; this.btnOK.Text = "OK"; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(240, 104); this.btnCancel.Name = "btnCancel"; this.btnCancel.TabIndex = 2; this.btnCancel.Text = "&Cancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.cboxBasedUpon); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.txtTo); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Location = new System.Drawing.Point(8, 8); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(392, 88); this.groupBox1.TabIndex = 5; this.groupBox1.TabStop = false; // // txtTo // this.txtTo.Location = new System.Drawing.Point(96, 16); this.txtTo.Name = "txtTo"; this.txtTo.Size = new System.Drawing.Size(288, 20); this.txtTo.TabIndex = 5; this.txtTo.Text = ""; // // label2 // this.label2.Location = new System.Drawing.Point(8, 16); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(72, 23); this.label2.TabIndex = 2; this.label2.Text = "Language:"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // cboxBasedUpon // this.cboxBasedUpon.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboxBasedUpon.Location = new System.Drawing.Point(96, 48); this.cboxBasedUpon.Name = "cboxBasedUpon"; this.cboxBasedUpon.Size = new System.Drawing.Size(288, 21); this.cboxBasedUpon.TabIndex = 7; // // label3 // this.label3.Location = new System.Drawing.Point(8, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(80, 23); this.label3.TabIndex = 6; this.label3.Text = "Based Upon:"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // AddLanguageMappingDialog // this.AcceptButton = this.btnOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(416, 135); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnCancel); this.Controls.Add(this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "AddLanguageMappingDialog"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Add New Language Mapping"; this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void btnCancel_Click(object sender, System.EventArgs e) { this.DialogResult = DialogResult.Cancel; } private void btnOK_Click(object sender, System.EventArgs e) { NewLanguage = this.txtTo.Text; if(this.cboxBasedUpon.SelectedIndex >= 0) { BasedUpon = this.cboxBasedUpon.SelectedItem.ToString(); } if(NewLanguage == string.Empty) { MessageBox.Show("You must supply a Language", "Error"); return; } else { string lang = ""; for(int i = 0; i < this.cboxBasedUpon.Items.Count; i++) { lang = this.cboxBasedUpon.Items[i] as string; if(lang == NewLanguage) { MessageBox.Show(NewLanguage + " already exits", "Error"); return; } } } this.DialogResult = DialogResult.OK; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Threading; namespace System.Net.Security { // // This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context. // internal class _SslStream { private const int PinnableReadBufferSize = 4096 * 4 + 32; // We read in 16K chunks + headers. private static PinnableBufferCache s_PinnableReadBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableReadBufferSize); private const int PinnableWriteBufferSize = 4096 + 1024; // We write in 4K chunks + encryption overhead. private static PinnableBufferCache s_PinnableWriteBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableWriteBufferSize); private SslState _SslState; private int _NestedWrite; private int _NestedRead; // Never updated directly, special properties are used. This is the read buffer. private byte[] _InternalBuffer; private bool _InternalBufferFromPinnableCache; private byte[] _PinnableOutputBuffer; // Used for writes when we can do it. private byte[] _PinnableOutputBufferInUse; // Remembers what UNENCRYPTED buffer is using _PinnableOutputBuffer. private int _InternalOffset; private int _InternalBufferCount; private FixedSizeReader _Reader; internal _SslStream(SslState sslState) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage1("CTOR: In System.Net._SslStream.SslStream", this.GetHashCode()); } _SslState = sslState; _Reader = new FixedSizeReader(_SslState.InnerStream); } // If we have a read buffer from the pinnable cache, return it. private void FreeReadBuffer() { if (_InternalBufferFromPinnableCache) { s_PinnableReadBufferCache.FreeBuffer(_InternalBuffer); _InternalBufferFromPinnableCache = false; } _InternalBuffer = null; } ~_SslStream() { if (_InternalBufferFromPinnableCache) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Read Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_InternalBuffer)); } FreeReadBuffer(); } if (_PinnableOutputBuffer != null) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Write Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_PinnableOutputBuffer)); } s_PinnableWriteBufferCache.FreeBuffer(_PinnableOutputBuffer); } } internal int Read(byte[] buffer, int offset, int count) { return ProcessRead(buffer, offset, count); } internal void Write(byte[] buffer, int offset, int count) { ProcessWrite(buffer, offset, count); } internal bool DataAvailable { get { return InternalBufferCount != 0; } } private byte[] InternalBuffer { get { return _InternalBuffer; } } private int InternalOffset { get { return _InternalOffset; } } private int InternalBufferCount { get { return _InternalBufferCount; } } private void SkipBytes(int decrCount) { _InternalOffset += decrCount; _InternalBufferCount -= decrCount; } // // This will set the internal offset to "curOffset" and ensure internal buffer. // If not enough, reallocate and copy up to "curOffset". // private void EnsureInternalBufferSize(int curOffset, int addSize) { if (_InternalBuffer == null || _InternalBuffer.Length < addSize + curOffset) { bool wasPinnable = _InternalBufferFromPinnableCache; byte[] saved = _InternalBuffer; int newSize = addSize + curOffset; if (newSize <= PinnableReadBufferSize) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize IS pinnable", this.GetHashCode(), newSize); } _InternalBufferFromPinnableCache = true; _InternalBuffer = s_PinnableReadBufferCache.AllocateBuffer(); } else { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize NOT pinnable", this.GetHashCode(), newSize); } _InternalBufferFromPinnableCache = false; _InternalBuffer = new byte[newSize]; } if (saved != null && curOffset != 0) { Buffer.BlockCopy(saved, 0, _InternalBuffer, 0, curOffset); } if (wasPinnable) { s_PinnableReadBufferCache.FreeBuffer(saved); } } _InternalOffset = curOffset; _InternalBufferCount = curOffset + addSize; } // // Validates user parameteres for all Read/Write methods. // private void ValidateParameters(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (count > buffer.Length - offset) { throw new ArgumentOutOfRangeException("count", SR.net_offset_plus_count); } } // // Sync write method. // private void ProcessWrite(byte[] buffer, int offset, int count) { ValidateParameters(buffer, offset, count); if (Interlocked.Exchange(ref _NestedWrite, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "Write", "write")); } try { StartWriting(buffer, offset, count); } catch (Exception e) { _SslState.FinishWrite(); if (e is IOException) { throw; } throw new IOException(SR.net_io_write, e); } finally { _NestedWrite = 0; } } private void StartWriting(byte[] buffer, int offset, int count) { // We loop to this method from the callback. // If the last chunk was just completed from async callback (count < 0), we complete user request. if (count >= 0) { byte[] outBuffer = null; if (_PinnableOutputBufferInUse == null) { if (_PinnableOutputBuffer == null) { _PinnableOutputBuffer = s_PinnableWriteBufferCache.AllocateBuffer(); } _PinnableOutputBufferInUse = buffer; outBuffer = _PinnableOutputBuffer; if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Trying Pinnable", this.GetHashCode(), count, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer)); } } else { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.StartWriting BufferInUse", this.GetHashCode(), count); } } do { // Request a write IO slot. if (_SslState.CheckEnqueueWrite(null)) { // Operation is async and has been queued, return. return; } int chunkBytes = Math.Min(count, _SslState.MaxDataSize); int encryptedBytes; SecurityStatusPal errorCode = _SslState.EncryptData(buffer, offset, chunkBytes, ref outBuffer, out encryptedBytes); if (errorCode != SecurityStatusPal.OK) { ProtocolToken message = new ProtocolToken(null, errorCode); throw new IOException(SR.net_io_encrypt, message.GetException()); } if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Got Encrypted Buffer", this.GetHashCode(), encryptedBytes, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer)); } _SslState.InnerStream.Write(outBuffer, 0, encryptedBytes); offset += chunkBytes; count -= chunkBytes; // Release write IO slot. _SslState.FinishWrite(); } while (count != 0); } if (buffer == _PinnableOutputBufferInUse) { _PinnableOutputBufferInUse = null; if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage1("In System.Net._SslStream.StartWriting Freeing buffer.", this.GetHashCode()); } } } // // Sync read method. // private int ProcessRead(byte[] buffer, int offset, int count) { ValidateParameters(buffer, offset, count); if (Interlocked.Exchange(ref _NestedRead, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "Read", "read")); } try { int copyBytes; if (InternalBufferCount != 0) { copyBytes = InternalBufferCount > count ? count : InternalBufferCount; if (copyBytes != 0) { Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, copyBytes); SkipBytes(copyBytes); } return copyBytes; } return StartReading(buffer, offset, count); } catch (Exception e) { _SslState.FinishRead(null); if (e is IOException) { throw; } throw new IOException(SR.net_io_read, e); } finally { _NestedRead = 0; } } // // To avoid recursion when decrypted 0 bytes this method will loop until a decrypted result at least 1 byte. // private int StartReading(byte[] buffer, int offset, int count) { int result = 0; GlobalLog.Assert(InternalBufferCount == 0, "SslStream::StartReading()|Previous frame was not consumed. InternalBufferCount:{0}", InternalBufferCount); do { int copyBytes = _SslState.CheckEnqueueRead(buffer, offset, count, null); if (copyBytes == 0) { //Queued but not completed! return 0; } if (copyBytes != -1) { return copyBytes; } } // When we read -1 bytes means we have decrypted 0 bytes or rehandshaking, need looping. while ((result = StartFrameHeader(buffer, offset, count)) == -1); return result; } // // Need read frame size first // private int StartFrameHeader(byte[] buffer, int offset, int count) { int readBytes = 0; // // Always pass InternalBuffer for SSPI "in place" decryption. // A user buffer can be shared by many threads in that case decryption/integrity check may fail cause of data corruption. // // Reset internal buffer for a new frame. EnsureInternalBufferSize(0, SecureChannel.ReadHeaderSize); readBytes = _Reader.ReadPacket(InternalBuffer, 0, SecureChannel.ReadHeaderSize); return StartFrameBody(readBytes, buffer, offset, count); } private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count) { if (readBytes == 0) { //EOF : Reset the buffer as we did not read anything into it. SkipBytes(InternalBufferCount); return 0; } // Now readBytes is a payload size. readBytes = _SslState.GetRemainingFrameSize(InternalBuffer, readBytes); if (readBytes < 0) { throw new IOException(SR.net_frame_read_size); } EnsureInternalBufferSize(SecureChannel.ReadHeaderSize, readBytes); readBytes = _Reader.ReadPacket(InternalBuffer, SecureChannel.ReadHeaderSize, readBytes); return ProcessFrameBody(readBytes, buffer, offset, count); } // // readBytes == SSL Data Payload size on input or 0 on EOF // private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count) { if (readBytes == 0) { // EOF throw new IOException(SR.net_io_eof); } // Set readBytes to total number of received bytes. readBytes += SecureChannel.ReadHeaderSize; // Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_. int data_offset = 0; SecurityStatusPal errorCode = _SslState.DecryptData(InternalBuffer, ref data_offset, ref readBytes); if (errorCode != SecurityStatusPal.OK) { byte[] extraBuffer = null; if (readBytes != 0) { extraBuffer = new byte[readBytes]; Buffer.BlockCopy(InternalBuffer, data_offset, extraBuffer, 0, readBytes); } // Reset internal buffer count. SkipBytes(InternalBufferCount); return ProcessReadErrorCode(errorCode, buffer, offset, count, extraBuffer); } if (readBytes == 0 && count != 0) { // Read again since remote side has sent encrypted 0 bytes. SkipBytes(InternalBufferCount); return -1; } // Decrypted data start from "data_offset" offset, the total count can be shrunk after decryption. EnsureInternalBufferSize(0, data_offset + readBytes); SkipBytes(data_offset); if (readBytes > count) { readBytes = count; } Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, readBytes); // This will adjust both the remaining internal buffer count and the offset. SkipBytes(readBytes); _SslState.FinishRead(null); return readBytes; } // // Only processing SEC_I_RENEGOTIATE. // private int ProcessReadErrorCode(SecurityStatusPal errorCode, byte[] buffer, int offset, int count, byte[] extraBuffer) { // ERROR - examine what kind ProtocolToken message = new ProtocolToken(null, errorCode); GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::***Processing an error Status = " + message.Status.ToString()); if (message.Renegotiate) { _SslState.ReplyOnReAuthentication(extraBuffer); // Loop on read. return -1; } if (message.CloseConnection) { _SslState.FinishRead(null); return 0; } throw new IOException(SR.net_io_decrypt, message.GetException()); } } }
using System; using System.IO; using System.ComponentModel; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ChargeBee.Internal; using ChargeBee.Api; using ChargeBee.Models.Enums; using ChargeBee.Filters.Enums; namespace ChargeBee.Models { public class QuoteLineGroup : Resource { public QuoteLineGroup() { } public QuoteLineGroup(Stream stream) { using (StreamReader reader = new StreamReader(stream)) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } } public QuoteLineGroup(TextReader reader) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } public QuoteLineGroup(String jsonString) { JObj = JToken.Parse(jsonString); apiVersionCheck (JObj); } #region Methods #endregion #region Properties public int? Version { get { return GetValue<int?>("version", false); } } public string Id { get { return GetValue<string>("id", false); } } public int SubTotal { get { return GetValue<int>("sub_total", true); } } public int? Total { get { return GetValue<int?>("total", false); } } public int? CreditsApplied { get { return GetValue<int?>("credits_applied", false); } } public int? AmountPaid { get { return GetValue<int?>("amount_paid", false); } } public int? AmountDue { get { return GetValue<int?>("amount_due", false); } } public ChargeEventEnum? ChargeEvent { get { return GetEnum<ChargeEventEnum>("charge_event", false); } } public int? BillingCycleNumber { get { return GetValue<int?>("billing_cycle_number", false); } } public List<QuoteLineGroupLineItem> LineItems { get { return GetResourceList<QuoteLineGroupLineItem>("line_items"); } } public List<QuoteLineGroupDiscount> Discounts { get { return GetResourceList<QuoteLineGroupDiscount>("discounts"); } } public List<QuoteLineGroupLineItemDiscount> LineItemDiscounts { get { return GetResourceList<QuoteLineGroupLineItemDiscount>("line_item_discounts"); } } public List<QuoteLineGroupTax> Taxes { get { return GetResourceList<QuoteLineGroupTax>("taxes"); } } public List<QuoteLineGroupLineItemTax> LineItemTaxes { get { return GetResourceList<QuoteLineGroupLineItemTax>("line_item_taxes"); } } #endregion public enum ChargeEventEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "immediate")] Immediate, [EnumMember(Value = "subscription_creation")] SubscriptionCreation, [EnumMember(Value = "trial_start")] TrialStart, [EnumMember(Value = "subscription_change")] SubscriptionChange, [EnumMember(Value = "subscription_renewal")] SubscriptionRenewal, [EnumMember(Value = "subscription_cancel")] SubscriptionCancel, } #region Subclasses public class QuoteLineGroupLineItem : Resource { public enum EntityTypeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "plan_setup")] PlanSetup, [EnumMember(Value = "plan")] Plan, [EnumMember(Value = "addon")] Addon, [EnumMember(Value = "adhoc")] Adhoc, [EnumMember(Value = "plan_item_price")] PlanItemPrice, [EnumMember(Value = "addon_item_price")] AddonItemPrice, [EnumMember(Value = "charge_item_price")] ChargeItemPrice, } public string Id { get { return GetValue<string>("id", false); } } public string SubscriptionId { get { return GetValue<string>("subscription_id", false); } } public DateTime DateFrom { get { return (DateTime)GetDateTime("date_from", true); } } public DateTime DateTo { get { return (DateTime)GetDateTime("date_to", true); } } public int UnitAmount { get { return GetValue<int>("unit_amount", true); } } public int? Quantity { get { return GetValue<int?>("quantity", false); } } public int? Amount { get { return GetValue<int?>("amount", false); } } public PricingModelEnum? PricingModel { get { return GetEnum<PricingModelEnum>("pricing_model", false); } } public bool IsTaxed { get { return GetValue<bool>("is_taxed", true); } } public int? TaxAmount { get { return GetValue<int?>("tax_amount", false); } } public double? TaxRate { get { return GetValue<double?>("tax_rate", false); } } public string UnitAmountInDecimal { get { return GetValue<string>("unit_amount_in_decimal", false); } } public string QuantityInDecimal { get { return GetValue<string>("quantity_in_decimal", false); } } public string AmountInDecimal { get { return GetValue<string>("amount_in_decimal", false); } } public int? DiscountAmount { get { return GetValue<int?>("discount_amount", false); } } public int? ItemLevelDiscountAmount { get { return GetValue<int?>("item_level_discount_amount", false); } } public string Description { get { return GetValue<string>("description", true); } } public string EntityDescription { get { return GetValue<string>("entity_description", true); } } public EntityTypeEnum EntityType { get { return GetEnum<EntityTypeEnum>("entity_type", true); } } public TaxExemptReasonEnum? TaxExemptReason { get { return GetEnum<TaxExemptReasonEnum>("tax_exempt_reason", false); } } public string EntityId { get { return GetValue<string>("entity_id", false); } } public string CustomerId { get { return GetValue<string>("customer_id", false); } } } public class QuoteLineGroupDiscount : Resource { public enum EntityTypeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "item_level_coupon")] ItemLevelCoupon, [EnumMember(Value = "document_level_coupon")] DocumentLevelCoupon, [EnumMember(Value = "promotional_credits")] PromotionalCredits, [EnumMember(Value = "prorated_credits")] ProratedCredits, [EnumMember(Value = "item_level_discount")] ItemLevelDiscount, [EnumMember(Value = "document_level_discount")] DocumentLevelDiscount, } public int Amount { get { return GetValue<int>("amount", true); } } public string Description { get { return GetValue<string>("description", false); } } public EntityTypeEnum EntityType { get { return GetEnum<EntityTypeEnum>("entity_type", true); } } public string EntityId { get { return GetValue<string>("entity_id", false); } } } public class QuoteLineGroupLineItemDiscount : Resource { public enum DiscountTypeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "item_level_coupon")] ItemLevelCoupon, [EnumMember(Value = "document_level_coupon")] DocumentLevelCoupon, [EnumMember(Value = "promotional_credits")] PromotionalCredits, [EnumMember(Value = "prorated_credits")] ProratedCredits, [EnumMember(Value = "item_level_discount")] ItemLevelDiscount, [EnumMember(Value = "document_level_discount")] DocumentLevelDiscount, } public string LineItemId { get { return GetValue<string>("line_item_id", true); } } public DiscountTypeEnum DiscountType { get { return GetEnum<DiscountTypeEnum>("discount_type", true); } } public string CouponId { get { return GetValue<string>("coupon_id", false); } } public string EntityId { get { return GetValue<string>("entity_id", false); } } public int DiscountAmount { get { return GetValue<int>("discount_amount", true); } } } public class QuoteLineGroupTax : Resource { public string Name { get { return GetValue<string>("name", true); } } public int Amount { get { return GetValue<int>("amount", true); } } public string Description { get { return GetValue<string>("description", false); } } } public class QuoteLineGroupLineItemTax : Resource { public string LineItemId { get { return GetValue<string>("line_item_id", false); } } public string TaxName { get { return GetValue<string>("tax_name", true); } } public double TaxRate { get { return GetValue<double>("tax_rate", true); } } public bool? IsPartialTaxApplied { get { return GetValue<bool?>("is_partial_tax_applied", false); } } public bool? IsNonComplianceTax { get { return GetValue<bool?>("is_non_compliance_tax", false); } } public int TaxableAmount { get { return GetValue<int>("taxable_amount", true); } } public int TaxAmount { get { return GetValue<int>("tax_amount", true); } } public TaxJurisTypeEnum? TaxJurisType { get { return GetEnum<TaxJurisTypeEnum>("tax_juris_type", false); } } public string TaxJurisName { get { return GetValue<string>("tax_juris_name", false); } } public string TaxJurisCode { get { return GetValue<string>("tax_juris_code", false); } } public int? TaxAmountInLocalCurrency { get { return GetValue<int?>("tax_amount_in_local_currency", false); } } public string LocalCurrencyCode { get { return GetValue<string>("local_currency_code", false); } } } #endregion } }
namespace InControl { using System; using UnityEngine; public class OneAxisInputControl : IInputControl { public ulong UpdateTick { get; protected set; } float sensitivity = 1.0f; float lowerDeadZone = 0.0f; float upperDeadZone = 1.0f; float stateThreshold = 0.0f; public float FirstRepeatDelay = 0.8f; public float RepeatDelay = 0.1f; public bool Raw; internal bool Enabled = true; ulong pendingTick; bool pendingCommit; float nextRepeatTime; float lastPressedTime; bool wasRepeated; bool clearInputState; InputControlState lastState; InputControlState nextState; InputControlState thisState; void PrepareForUpdate( ulong updateTick ) { if (IsNull) { return; } if (updateTick < pendingTick) { throw new InvalidOperationException( "Cannot be updated with an earlier tick." ); } if (pendingCommit && updateTick != pendingTick) { throw new InvalidOperationException( "Cannot be updated for a new tick until pending tick is committed." ); } if (updateTick > pendingTick) { lastState = thisState; nextState.Reset(); pendingTick = updateTick; pendingCommit = true; } } public bool UpdateWithState( bool state, ulong updateTick, float deltaTime ) { if (IsNull) { return false; } PrepareForUpdate( updateTick ); nextState.Set( state || nextState.State ); return state; } public bool UpdateWithValue( float value, ulong updateTick, float deltaTime ) { if (IsNull) { return false; } PrepareForUpdate( updateTick ); if (Utility.Abs( value ) > Utility.Abs( nextState.RawValue )) { nextState.RawValue = value; if (!Raw) { value = Utility.ApplyDeadZone( value, lowerDeadZone, upperDeadZone ); //value = Utility.ApplySmoothing( value, lastState.Value, deltaTime, sensitivity ); } nextState.Set( value, stateThreshold ); return true; } return false; } internal bool UpdateWithRawValue( float value, ulong updateTick, float deltaTime ) { if (IsNull) { return false; } Raw = true; PrepareForUpdate( updateTick ); if (Utility.Abs( value ) > Utility.Abs( nextState.RawValue )) { nextState.RawValue = value; nextState.Set( value, stateThreshold ); return true; } return false; } internal void SetValue( float value, ulong updateTick ) { if (IsNull) { return; } if (updateTick > pendingTick) { lastState = thisState; nextState.Reset(); pendingTick = updateTick; pendingCommit = true; } nextState.RawValue = value; nextState.Set( value, StateThreshold ); } public void ClearInputState() { lastState.Reset(); thisState.Reset(); nextState.Reset(); wasRepeated = false; clearInputState = true; } public void Commit() { if (IsNull) { return; } pendingCommit = false; // nextState.Set( Utility.ApplySmoothing( nextState.Value, lastState.Value, Time.deltaTime, sensitivity ), stateThreshold ); thisState = nextState; if (clearInputState) { // The net result here should be that the entire state will return zero/false // from when ResetState() is called until the next call to Commit(), which is // the next update tick, and WasPressed, WasReleased and WasRepeated will then // return false during this following tick. lastState = nextState; UpdateTick = pendingTick; clearInputState = false; return; } var lastPressed = lastState.State; var thisPressed = thisState.State; wasRepeated = false; if (lastPressed && !thisPressed) // if was released... { nextRepeatTime = 0.0f; } else if (thisPressed) // if is pressed... { if (lastPressed != thisPressed) // if has changed... { nextRepeatTime = Time.realtimeSinceStartup + FirstRepeatDelay; } else if (Time.realtimeSinceStartup >= nextRepeatTime) { wasRepeated = true; nextRepeatTime = Time.realtimeSinceStartup + RepeatDelay; } } if (thisState != lastState) { UpdateTick = pendingTick; } } public void CommitWithState( bool state, ulong updateTick, float deltaTime ) { UpdateWithState( state, updateTick, deltaTime ); Commit(); } public void CommitWithValue( float value, ulong updateTick, float deltaTime ) { UpdateWithValue( value, updateTick, deltaTime ); Commit(); } internal void CommitWithSides( InputControl negativeSide, InputControl positiveSide, ulong updateTick, float deltaTime ) { LowerDeadZone = Mathf.Max( negativeSide.LowerDeadZone, positiveSide.LowerDeadZone ); UpperDeadZone = Mathf.Min( negativeSide.UpperDeadZone, positiveSide.UpperDeadZone ); Raw = negativeSide.Raw || positiveSide.Raw; var value = Utility.ValueFromSides( negativeSide.RawValue, positiveSide.RawValue ); CommitWithValue( value, updateTick, deltaTime ); } public bool State { get { return Enabled && thisState.State; } } public bool LastState { get { return Enabled && lastState.State; } } public float Value { get { return Enabled ? thisState.Value : 0.0f; } } public float LastValue { get { return Enabled ? lastState.Value : 0.0f; } } public float RawValue { get { return Enabled ? thisState.RawValue : 0.0f; } } internal float NextRawValue { get { return Enabled ? nextState.RawValue : 0.0f; } } public bool HasChanged { get { return Enabled && thisState != lastState; } } public bool IsPressed { get { return Enabled && thisState.State; } } public bool WasPressed { get { return Enabled && thisState && !lastState; } } public bool WasReleased { get { return Enabled && !thisState && lastState; } } public bool WasRepeated { get { return Enabled && wasRepeated; } } public float Sensitivity { get { return sensitivity; } set { sensitivity = Mathf.Clamp01( value ); } } public float LowerDeadZone { get { return lowerDeadZone; } set { lowerDeadZone = Mathf.Clamp01( value ); } } public float UpperDeadZone { get { return upperDeadZone; } set { upperDeadZone = Mathf.Clamp01( value ); } } public float StateThreshold { get { return stateThreshold; } set { stateThreshold = Mathf.Clamp01( value ); } } public bool IsNull { get { return ReferenceEquals( this, InputControl.Null ); } } public static implicit operator bool( OneAxisInputControl instance ) { return instance.State; } public static implicit operator float( OneAxisInputControl instance ) { return instance.Value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Threading; using Microsoft.Win32.SafeHandles; using Internal.Cryptography; namespace System.Security.Cryptography { #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS public partial class RSA : AsymmetricAlgorithm { public static RSA Create() { return new RSAImplementation.RSAOpenSsl(); } } internal static partial class RSAImplementation { #endif public sealed partial class RSAOpenSsl : RSA { private const int BitsPerByte = 8; // 65537 (0x10001) in big-endian form private static readonly byte[] s_defaultExponent = { 0x01, 0x00, 0x01 }; private Lazy<SafeRsaHandle> _key; private bool _skipKeySizeCheck; public RSAOpenSsl() : this(2048) { } public RSAOpenSsl(int keySize) { KeySize = keySize; _key = new Lazy<SafeRsaHandle>(GenerateKey); } public override int KeySize { set { if (KeySize == value) { return; } // Set the KeySize first so that an invalid value doesn't throw away the key base.KeySize = value; FreeKey(); _key = new Lazy<SafeRsaHandle>(GenerateKey); } } private void ForceSetKeySize(int newKeySize) { // In the event that a key was loaded via ImportParameters or an IntPtr/SafeHandle // it could be outside of the bounds that we currently represent as "legal key sizes". // Since that is our view into the underlying component it can be detached from the // component's understanding. If it said it has opened a key, and this is the size, trust it. _skipKeySizeCheck = true; try { // Set base.KeySize directly, since we don't want to free the key // (which we would do if the keysize changed on import) base.KeySize = newKeySize; } finally { _skipKeySizeCheck = false; } } public override KeySizes[] LegalKeySizes { get { if (_skipKeySizeCheck) { // When size limitations are in bypass, accept any positive integer. // Many of them may not make sense (like 1), but we're just assigning // the field to whatever value was provided by the native component. return new[] { new KeySizes(minSize: 1, maxSize: int.MaxValue, skipSize: 1) }; } // OpenSSL seems to accept answers of all sizes. // Choosing a non-multiple of 8 would make some calculations misalign // (like assertions of (output.Length * 8) == KeySize). // Choosing a number too small is insecure. // Choosing a number too large will cause GenerateKey to take much // longer than anyone would be willing to wait. // // So, copying the values from RSACryptoServiceProvider return new[] { new KeySizes(384, 16384, 8) }; } } public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (padding == null) throw new ArgumentNullException(nameof(padding)); Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding); SafeRsaHandle key = _key.Value; CheckInvalidKey(key); byte[] buf = new byte[Interop.Crypto.RsaSize(key)]; int returnValue = Interop.Crypto.RsaPrivateDecrypt( data.Length, data, buf, key, rsaPadding); CheckReturn(returnValue); // If the padding mode is RSA_NO_PADDING then the size of the decrypted block // will be RSA_size, so let's just return buf. // // If any padding was used, then some amount (determined by the padding algorithm) // will have been reduced, and only returnValue bytes were part of the decrypted // body, so copy the decrypted bytes to an appropriately sized array before // returning it. if (returnValue == buf.Length) { return buf; } byte[] plainBytes = new byte[returnValue]; Buffer.BlockCopy(buf, 0, plainBytes, 0, returnValue); return plainBytes; } public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (padding == null) throw new ArgumentNullException(nameof(padding)); Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding); SafeRsaHandle key = _key.Value; CheckInvalidKey(key); byte[] buf = new byte[Interop.Crypto.RsaSize(key)]; int returnValue = Interop.Crypto.RsaPublicEncrypt( data.Length, data, buf, key, rsaPadding); CheckReturn(returnValue); return buf; } private static Interop.Crypto.RsaPadding GetInteropPadding(RSAEncryptionPadding padding) { if (padding == RSAEncryptionPadding.Pkcs1) { return Interop.Crypto.RsaPadding.Pkcs1; } else if (padding == RSAEncryptionPadding.OaepSHA1) { return Interop.Crypto.RsaPadding.OaepSHA1; } else { throw PaddingModeNotSupported(); } } public override RSAParameters ExportParameters(bool includePrivateParameters) { // It's entirely possible that this line will cause the key to be generated in the first place. SafeRsaHandle key = _key.Value; CheckInvalidKey(key); RSAParameters rsaParameters = Interop.Crypto.ExportRsaParameters(key, includePrivateParameters); bool hasPrivateKey = rsaParameters.D != null; if (hasPrivateKey != includePrivateParameters || !HasConsistentPrivateKey(ref rsaParameters)) { throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); } return rsaParameters; } public override void ImportParameters(RSAParameters parameters) { ValidateParameters(ref parameters); SafeRsaHandle key = Interop.Crypto.RsaCreate(); bool imported = false; Interop.Crypto.CheckValidOpenSslHandle(key); try { Interop.Crypto.SetRsaParameters( key, parameters.Modulus, parameters.Modulus != null ? parameters.Modulus.Length : 0, parameters.Exponent, parameters.Exponent != null ? parameters.Exponent.Length : 0, parameters.D, parameters.D != null ? parameters.D.Length : 0, parameters.P, parameters.P != null ? parameters.P.Length : 0, parameters.DP, parameters.DP != null ? parameters.DP.Length : 0, parameters.Q, parameters.Q != null ? parameters.Q.Length : 0, parameters.DQ, parameters.DQ != null ? parameters.DQ.Length : 0, parameters.InverseQ, parameters.InverseQ != null ? parameters.InverseQ.Length : 0); imported = true; } finally { if (!imported) { key.Dispose(); } } FreeKey(); _key = new Lazy<SafeRsaHandle>(() => key, LazyThreadSafetyMode.None); // Use ForceSet instead of the property setter to ensure that LegalKeySizes doesn't interfere // with the already loaded key. ForceSetKeySize(BitsPerByte * Interop.Crypto.RsaSize(key)); } protected override void Dispose(bool disposing) { if (disposing) { FreeKey(); } base.Dispose(disposing); } private void FreeKey() { if (_key != null && _key.IsValueCreated) { SafeRsaHandle handle = _key.Value; if (handle != null) { handle.Dispose(); } } } private static void ValidateParameters(ref RSAParameters parameters) { if (parameters.Modulus == null || parameters.Exponent == null) throw new CryptographicException(SR.Argument_InvalidValue); if (!HasConsistentPrivateKey(ref parameters)) throw new CryptographicException(SR.Argument_InvalidValue); } private static bool HasConsistentPrivateKey(ref RSAParameters parameters) { if (parameters.D == null) { if (parameters.P != null || parameters.DP != null || parameters.Q != null || parameters.DQ != null || parameters.InverseQ != null) { return false; } } else { if (parameters.P == null || parameters.DP == null || parameters.Q == null || parameters.DQ == null || parameters.InverseQ == null) { return false; } } return true; } private static void CheckInvalidKey(SafeRsaHandle key) { if (key == null || key.IsInvalid) { throw new CryptographicException(SR.Cryptography_OpenInvalidHandle); } } private static void CheckReturn(int returnValue) { if (returnValue == -1) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } } private static void CheckBoolReturn(int returnValue) { if (returnValue == 1) { return; } throw Interop.Crypto.CreateOpenSslCryptographicException(); } private SafeRsaHandle GenerateKey() { SafeRsaHandle key = Interop.Crypto.RsaCreate(); bool generated = false; Interop.Crypto.CheckValidOpenSslHandle(key); try { using (SafeBignumHandle exponent = Interop.Crypto.CreateBignum(s_defaultExponent)) { // The documentation for RSA_generate_key_ex does not say that it returns only // 0 or 1, so the call marshals it back as a full Int32 and checks for a value // of 1 explicitly. int response = Interop.Crypto.RsaGenerateKeyEx( key, KeySize, exponent); CheckBoolReturn(response); generated = true; } } finally { if (!generated) { key.Dispose(); } } return key; } protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { return OpenSslAsymmetricAlgorithmCore.HashData(data, offset, count, hashAlgorithm); } protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { return OpenSslAsymmetricAlgorithmCore.HashData(data, hashAlgorithm); } public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) throw new ArgumentNullException(nameof(hash)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); if (padding != RSASignaturePadding.Pkcs1) throw PaddingModeNotSupported(); return SignHash(hash, hashAlgorithm); } private byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithmName) { int algorithmNid = GetAlgorithmNid(hashAlgorithmName); SafeRsaHandle rsa = _key.Value; byte[] signature = new byte[Interop.Crypto.RsaSize(rsa)]; int signatureSize; bool success = Interop.Crypto.RsaSign( algorithmNid, hash, hash.Length, signature, out signatureSize, rsa); if (!success) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } Debug.Assert( signatureSize == signature.Length, "RSA_sign reported an unexpected signature size", "RSA_sign reported signatureSize was {0}, when {1} was expected", signatureSize, signature.Length); return signature; } public override bool VerifyHash( byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) throw new ArgumentNullException(nameof(hash)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); if (padding != RSASignaturePadding.Pkcs1) throw PaddingModeNotSupported(); return VerifyHash(hash, signature, hashAlgorithm); } private bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithmName) { int algorithmNid = GetAlgorithmNid(hashAlgorithmName); SafeRsaHandle rsa = _key.Value; return Interop.Crypto.RsaVerify( algorithmNid, hash, hash.Length, signature, signature.Length, rsa); } private static int GetAlgorithmNid(HashAlgorithmName hashAlgorithmName) { // All of the current HashAlgorithmName values correspond to the SN values in OpenSSL 0.9.8. // If there's ever a new one that doesn't, translate it here. string sn = hashAlgorithmName.Name; int nid = Interop.Crypto.ObjSn2Nid(sn); if (nid == Interop.Crypto.NID_undef) { throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmName.Name); } return nid; } private static Exception PaddingModeNotSupported() { return new CryptographicException(SR.Cryptography_InvalidPaddingMode); } private static Exception HashAlgorithmNameNullOrEmpty() { return new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } } #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS } #endif }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Debug = System.Diagnostics.Debug; namespace System.Xml.Linq { internal class XNodeReader : XmlReader, IXmlLineInfo { private static readonly char[] WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' }; // The reader position is encoded by the tuple (source, parent). // Lazy text uses (instance, parent element). Attribute value // uses (instance, parent attribute). End element uses (instance, // instance). Common XObject uses (instance, null). object source; object parent; ReadState state; XNode root; XmlNameTable nameTable; bool omitDuplicateNamespaces; internal XNodeReader(XNode node, XmlNameTable nameTable, ReaderOptions options) { this.source = node; this.root = node; this.nameTable = nameTable != null ? nameTable : CreateNameTable(); this.omitDuplicateNamespaces = (options & ReaderOptions.OmitDuplicateNamespaces) != 0 ? true : false; } internal XNodeReader(XNode node, XmlNameTable nameTable) : this(node, nameTable, (node.GetSaveOptionsFromAnnotations() & SaveOptions.OmitDuplicateNamespaces) != 0 ? ReaderOptions.OmitDuplicateNamespaces : ReaderOptions.None) { } public override int AttributeCount { get { if (!IsInteractive) { return 0; } int count = 0; XElement e = GetElementInAttributeScope(); if (e != null) { XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (!omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { count++; } } while (a != e.lastAttr); } } return count; } } public override string BaseURI { get { XObject o = source as XObject; if (o != null) { return o.BaseUri; } o = parent as XObject; if (o != null) { return o.BaseUri; } return string.Empty; } } public override int Depth { get { if (!IsInteractive) { return 0; } XObject o = source as XObject; if (o != null) { return GetDepth(o); } o = parent as XObject; if (o != null) { return GetDepth(o) + 1; } return 0; } } static int GetDepth(XObject o) { int depth = 0; while (o.parent != null) { depth++; o = o.parent; } if (o is XDocument) { depth--; } return depth; } public override bool EOF { get { return state == ReadState.EndOfFile; } } public override bool HasAttributes { get { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null && e.lastAttr != null) { if (omitDuplicateNamespaces) { return GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next) != null; } else { return true; } } else { return false; } } } public override bool HasValue { get { if (!IsInteractive) { return false; } XObject o = source as XObject; if (o != null) { switch (o.NodeType) { case XmlNodeType.Attribute: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: return true; default: return false; } } return true; } } public override bool IsEmptyElement { get { if (!IsInteractive) { return false; } XElement e = source as XElement; return e != null && e.IsEmpty; } } public override string LocalName { get { return nameTable.Add(GetLocalName()); } } string GetLocalName() { if (!IsInteractive) { return string.Empty; } XElement e = source as XElement; if (e != null) { return e.Name.LocalName; } XAttribute a = source as XAttribute; if (a != null) { return a.Name.LocalName; } XProcessingInstruction p = source as XProcessingInstruction; if (p != null) { return p.Target; } XDocumentType n = source as XDocumentType; if (n != null) { return n.Name; } return string.Empty; } public override string Name { get { string prefix = GetPrefix(); if (prefix.Length == 0) { return nameTable.Add(GetLocalName()); } return nameTable.Add(string.Concat(prefix, ":", GetLocalName())); } } public override string NamespaceURI { get { return nameTable.Add(GetNamespaceURI()); } } string GetNamespaceURI() { if (!IsInteractive) { return string.Empty; } XElement e = source as XElement; if (e != null) { return e.Name.NamespaceName; } XAttribute a = source as XAttribute; if (a != null) { string namespaceName = a.Name.NamespaceName; if (namespaceName.Length == 0 && a.Name.LocalName == "xmlns") { return XNamespace.xmlnsPrefixNamespace; } return namespaceName; } return string.Empty; } public override XmlNameTable NameTable { get { return nameTable; } } public override XmlNodeType NodeType { get { if (!IsInteractive) { return XmlNodeType.None; } XObject o = source as XObject; if (o != null) { if (IsEndElement) { return XmlNodeType.EndElement; } XmlNodeType nt = o.NodeType; if (nt != XmlNodeType.Text) { return nt; } if (o.parent != null && o.parent.parent == null && o.parent is XDocument) { return XmlNodeType.Whitespace; } return XmlNodeType.Text; } if (parent is XDocument) { return XmlNodeType.Whitespace; } return XmlNodeType.Text; } } public override string Prefix { get { return nameTable.Add(GetPrefix()); } } string GetPrefix() { if (!IsInteractive) { return string.Empty; } XElement e = source as XElement; if (e != null) { string prefix = e.GetPrefixOfNamespace(e.Name.Namespace); if (prefix != null) { return prefix; } return string.Empty; } XAttribute a = source as XAttribute; if (a != null) { string prefix = a.GetPrefixOfNamespace(a.Name.Namespace); if (prefix != null) { return prefix; } } return string.Empty; } public override ReadState ReadState { get { return state; } } public override XmlReaderSettings Settings { get { XmlReaderSettings settings = new XmlReaderSettings(); settings.CheckCharacters = false; return settings; } } public override string Value { get { if (!IsInteractive) { return string.Empty; } XObject o = source as XObject; if (o != null) { switch (o.NodeType) { case XmlNodeType.Attribute: return ((XAttribute)o).Value; case XmlNodeType.Text: case XmlNodeType.CDATA: return ((XText)o).Value; case XmlNodeType.Comment: return ((XComment)o).Value; case XmlNodeType.ProcessingInstruction: return ((XProcessingInstruction)o).Data; case XmlNodeType.DocumentType: return ((XDocumentType)o).InternalSubset; default: return string.Empty; } } return (string)source; } } public override string XmlLang { get { if (!IsInteractive) { return string.Empty; } XElement e = GetElementInScope(); if (e != null) { XName name = XNamespace.Xml.GetName("lang"); do { XAttribute a = e.Attribute(name); if (a != null) { return a.Value; } e = e.parent as XElement; } while (e != null); } return string.Empty; } } public override XmlSpace XmlSpace { get { if (!IsInteractive) { return XmlSpace.None; } XElement e = GetElementInScope(); if (e != null) { XName name = XNamespace.Xml.GetName("space"); do { XAttribute a = e.Attribute(name); if (a != null) { switch (a.Value.Trim(WhitespaceChars)) { case "preserve": return XmlSpace.Preserve; case "default": return XmlSpace.Default; default: break; } } e = e.parent as XElement; } while (e != null); } return XmlSpace.None; } } protected override void Dispose(bool disposing) { if (disposing && ReadState != ReadState.Closed) { Close(); } } private void Close() { source = null; parent = null; root = null; state = ReadState.Closed; } public override string GetAttribute(string name) { if (!IsInteractive) { return null; } XElement e = GetElementInAttributeScope(); if (e != null) { string localName, namespaceName; GetNameInAttributeScope(name, e, out localName, out namespaceName); XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { return null; } else { return a.Value; } } } while (a != e.lastAttr); } return null; } XDocumentType n = source as XDocumentType; if (n != null) { switch (name) { case "PUBLIC": return n.PublicId; case "SYSTEM": return n.SystemId; } } return null; } public override string GetAttribute(string localName, string namespaceName) { if (!IsInteractive) { return null; } XElement e = GetElementInAttributeScope(); if (e != null) { if (localName == "xmlns") { if (namespaceName != null && namespaceName.Length == 0) { return null; } if (namespaceName == XNamespace.xmlnsPrefixNamespace) { namespaceName = string.Empty; } } XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { return null; } else { return a.Value; } } } while (a != e.lastAttr); } } return null; } public override string GetAttribute(int index) { if (!IsInteractive) { return null; } if (index < 0) { return null; } XElement e = GetElementInAttributeScope(); if (e != null) { XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (!omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { if (index-- == 0) { return a.Value; } } } while (a != e.lastAttr); } } return null; } public override string LookupNamespace(string prefix) { if (!IsInteractive) { return null; } if (prefix == null) { return null; } XElement e = GetElementInScope(); if (e != null) { XNamespace ns = prefix.Length == 0 ? e.GetDefaultNamespace() : e.GetNamespaceOfPrefix(prefix); if (ns != null) { return nameTable.Add(ns.NamespaceName); } } return null; } public override bool MoveToAttribute(string name) { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null) { string localName, namespaceName; GetNameInAttributeScope(name, e, out localName, out namespaceName); XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { // If it's a duplicate namespace attribute just act as if it doesn't exist return false; } else { source = a; parent = null; return true; } } } while (a != e.lastAttr); } } return false; } public override bool MoveToAttribute(string localName, string namespaceName) { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null) { if (localName == "xmlns") { if (namespaceName != null && namespaceName.Length == 0) { return false; } if (namespaceName == XNamespace.xmlnsPrefixNamespace) { namespaceName = string.Empty; } } XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { // If it's a duplicate namespace attribute just act as if it doesn't exist return false; } else { source = a; parent = null; return true; } } } while (a != e.lastAttr); } } return false; } public override void MoveToAttribute(int index) { if (!IsInteractive) { return; } if (index < 0) throw new ArgumentOutOfRangeException("index"); XElement e = GetElementInAttributeScope(); if (e != null) { XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (!omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { // Only count those which are non-duplicates if we're asked to if (index-- == 0) { source = a; parent = null; return; } } } while (a != e.lastAttr); } } throw new ArgumentOutOfRangeException("index"); } public override bool MoveToElement() { if (!IsInteractive) { return false; } XAttribute a = source as XAttribute; if (a == null) { a = parent as XAttribute; } if (a != null) { if (a.parent != null) { source = a.parent; parent = null; return true; } } return false; } public override bool MoveToFirstAttribute() { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null) { if (e.lastAttr != null) { if (omitDuplicateNamespaces) { object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next); if (na == null) { return false; } source = na; } else { source = e.lastAttr.next; } return true; } } return false; } public override bool MoveToNextAttribute() { if (!IsInteractive) { return false; } XElement e = source as XElement; if (e != null) { if (IsEndElement) { return false; } if (e.lastAttr != null) { if (omitDuplicateNamespaces) { // Skip duplicate namespace attributes // We must NOT modify the this.source until we find the one we're looking for // because if we don't find anything, we need to stay positioned where we're now object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next); if (na == null) { return false; } source = na; } else { source = e.lastAttr.next; } return true; } return false; } XAttribute a = source as XAttribute; if (a == null) { a = parent as XAttribute; } if (a != null) { if (a.parent != null && ((XElement)a.parent).lastAttr != a) { if (omitDuplicateNamespaces) { // Skip duplicate namespace attributes // We must NOT modify the this.source until we find the one we're looking for // because if we don't find anything, we need to stay positioned where we're now object na = GetFirstNonDuplicateNamespaceAttribute(a.next); if (na == null) { return false; } source = na; } else { source = a.next; } parent = null; return true; } } return false; } public override bool Read() { switch (state) { case ReadState.Initial: state = ReadState.Interactive; XDocument d = source as XDocument; if (d != null) { return ReadIntoDocument(d); } return true; case ReadState.Interactive: return Read(false); default: return false; } } public override bool ReadAttributeValue() { if (!IsInteractive) { return false; } XAttribute a = source as XAttribute; if (a != null) { return ReadIntoAttribute(a); } return false; } public override bool ReadToDescendant(string localName, string namespaceName) { if (!IsInteractive) { return false; } MoveToElement(); XElement c = source as XElement; if (c != null && !c.IsEmpty) { if (IsEndElement) { return false; } foreach (XElement e in c.Descendants()) { if (e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName) { source = e; return true; } } IsEndElement = true; } return false; } public override bool ReadToFollowing(string localName, string namespaceName) { while (Read()) { XElement e = source as XElement; if (e != null) { if (IsEndElement) continue; if (e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName) { return true; } } } return false; } public override bool ReadToNextSibling(string localName, string namespaceName) { if (!IsInteractive) { return false; } MoveToElement(); if (source != root) { XNode n = source as XNode; if (n != null) { foreach (XElement e in n.ElementsAfterSelf()) { if (e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName) { source = e; IsEndElement = false; return true; } } if (n.parent is XElement) { source = n.parent; IsEndElement = true; return false; } } else { if (parent is XElement) { source = parent; parent = null; IsEndElement = true; return false; } } } return ReadToEnd(); } public override void ResolveEntity() { } public override void Skip() { if (!IsInteractive) { return; } Read(true); } bool IXmlLineInfo.HasLineInfo() { if (IsEndElement) { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement XElement e = source as XElement; if (e != null) { return e.Annotation<LineInfoEndElementAnnotation>() != null; } } else { IXmlLineInfo li = source as IXmlLineInfo; if (li != null) { return li.HasLineInfo(); } } return false; } int IXmlLineInfo.LineNumber { get { if (IsEndElement) { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement XElement e = source as XElement; if (e != null) { LineInfoEndElementAnnotation a = e.Annotation<LineInfoEndElementAnnotation>(); if (a != null) { return a.lineNumber; } } } else { IXmlLineInfo li = source as IXmlLineInfo; if (li != null) { return li.LineNumber; } } return 0; } } int IXmlLineInfo.LinePosition { get { if (IsEndElement) { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement XElement e = source as XElement; if (e != null) { LineInfoEndElementAnnotation a = e.Annotation<LineInfoEndElementAnnotation>(); if (a != null) { return a.linePosition; } } } else { IXmlLineInfo li = source as IXmlLineInfo; if (li != null) { return li.LinePosition; } } return 0; } } bool IsEndElement { get { return parent == source; } set { parent = value ? source : null; } } bool IsInteractive { get { return state == ReadState.Interactive; } } static XmlNameTable CreateNameTable() { XmlNameTable nameTable = new NameTable(); nameTable.Add(string.Empty); nameTable.Add(XNamespace.xmlnsPrefixNamespace); nameTable.Add(XNamespace.xmlPrefixNamespace); return nameTable; } XElement GetElementInAttributeScope() { XElement e = source as XElement; if (e != null) { if (IsEndElement) { return null; } return e; } XAttribute a = source as XAttribute; if (a != null) { return (XElement)a.parent; } a = parent as XAttribute; if (a != null) { return (XElement)a.parent; } return null; } XElement GetElementInScope() { XElement e = source as XElement; if (e != null) { return e; } XNode n = source as XNode; if (n != null) { return n.parent as XElement; } XAttribute a = source as XAttribute; if (a != null) { return (XElement)a.parent; } e = parent as XElement; if (e != null) { return e; } a = parent as XAttribute; if (a != null) { return (XElement)a.parent; } return null; } static void GetNameInAttributeScope(string qualifiedName, XElement e, out string localName, out string namespaceName) { if (qualifiedName != null && qualifiedName.Length != 0) { int i = qualifiedName.IndexOf(':'); if (i != 0 && i != qualifiedName.Length - 1) { if (i == -1) { localName = qualifiedName; namespaceName = string.Empty; return; } XNamespace ns = e.GetNamespaceOfPrefix(qualifiedName.Substring(0, i)); if (ns != null) { localName = qualifiedName.Substring(i + 1, qualifiedName.Length - i - 1); namespaceName = ns.NamespaceName; return; } } } localName = null; namespaceName = null; } bool Read(bool skipContent) { XElement e = source as XElement; if (e != null) { if (e.IsEmpty || IsEndElement || skipContent) { return ReadOverNode(e); } return ReadIntoElement(e); } XNode n = source as XNode; if (n != null) { return ReadOverNode(n); } XAttribute a = source as XAttribute; if (a != null) { return ReadOverAttribute(a, skipContent); } return ReadOverText(skipContent); } bool ReadIntoDocument(XDocument d) { XNode n = d.content as XNode; if (n != null) { source = n.next; return true; } string s = d.content as string; if (s != null) { if (s.Length > 0) { source = s; parent = d; return true; } } return ReadToEnd(); } bool ReadIntoElement(XElement e) { XNode n = e.content as XNode; if (n != null) { source = n.next; return true; } string s = e.content as string; if (s != null) { if (s.Length > 0) { source = s; parent = e; } else { source = e; IsEndElement = true; } return true; } return ReadToEnd(); } bool ReadIntoAttribute(XAttribute a) { source = a.value; parent = a; return true; } bool ReadOverAttribute(XAttribute a, bool skipContent) { XElement e = (XElement)a.parent; if (e != null) { if (e.IsEmpty || skipContent) { return ReadOverNode(e); } return ReadIntoElement(e); } return ReadToEnd(); } bool ReadOverNode(XNode n) { if (n == root) { return ReadToEnd(); } XNode next = n.next; if (null == next || next == n || n == n.parent.content) { if (n.parent == null || (n.parent.parent == null && n.parent is XDocument)) { return ReadToEnd(); } source = n.parent; IsEndElement = true; } else { source = next; IsEndElement = false; } return true; } bool ReadOverText(bool skipContent) { if (parent is XElement) { source = parent; parent = null; IsEndElement = true; return true; } if (parent is XAttribute) { XAttribute a = (XAttribute)parent; parent = null; return ReadOverAttribute(a, skipContent); } return ReadToEnd(); } bool ReadToEnd() { state = ReadState.EndOfFile; return false; } /// <summary> /// Determines if the specified attribute would be a duplicate namespace declaration /// - one which we already reported on some ancestor, so it's not necessary to report it here /// </summary> /// <param name="candidateAttribute">The attribute to test.</param> /// <returns>true if the attribute is a duplicate namespace declaration attribute</returns> bool IsDuplicateNamespaceAttribute(XAttribute candidateAttribute) { if (!candidateAttribute.IsNamespaceDeclaration) { return false; } else { // Split the method in two to enable inlining of this piece (Which will work for 95% of cases) return IsDuplicateNamespaceAttributeInner(candidateAttribute); } } bool IsDuplicateNamespaceAttributeInner(XAttribute candidateAttribute) { // First of all - if this is an xmlns:xml declaration then it's a duplicate // since xml prefix can't be redeclared and it's declared by default always. if (candidateAttribute.Name.LocalName == "xml") { return true; } // The algorithm we use is: // Go up the tree (but don't go higher than the root of this reader) // and find the closest namespace declaration attribute which declares the same prefix // If it declares that prefix to the exact same URI as ours does then ours is a duplicate // Note that if we find a namespace declaration for the same prefix but with a different URI, then we don't have a dupe! XElement element = candidateAttribute.parent as XElement; if (element == root || element == null) { // If there's only the parent element of our attribute, there can be no duplicates return false; } element = element.parent as XElement; while (element != null) { // Search all attributes of this element for the same prefix declaration // Trick - a declaration for the same prefix will have the exact same XName - so we can do a quick ref comparison of names // (The default ns decl is represented by an XName "xmlns{}", even if you try to create // an attribute with XName "xmlns{http://www.w3.org/2000/xmlns/}" it will fail, // because it's treated as a declaration of prefix "xmlns" which is invalid) XAttribute a = element.lastAttr; if (a != null) { do { if (a.name == candidateAttribute.name) { // Found the same prefix decl if (a.Value == candidateAttribute.Value) { // And it's for the same namespace URI as well - so ours is a duplicate return true; } else { // It's not for the same namespace URI - which means we have to keep ours // (no need to continue the search as this one overrides anything above it) return false; } } a = a.next; } while (a != element.lastAttr); } if (element == root) { return false; } element = element.parent as XElement; } return false; } /// <summary> /// Finds a first attribute (starting with the parameter) which is not a duplicate namespace attribute /// </summary> /// <param name="candidate">The attribute to start with</param> /// <returns>The first attribute which is not a namespace attribute or null if the end of attributes has bean reached</returns> XAttribute GetFirstNonDuplicateNamespaceAttribute(XAttribute candidate) { Debug.Assert(omitDuplicateNamespaces, "This method should only be called if we're omitting duplicate namespace attribute." + "For perf reason it's better to test this flag in the caller method."); if (!IsDuplicateNamespaceAttribute(candidate)) { return candidate; } XElement e = candidate.parent as XElement; if (e != null && candidate != e.lastAttr) { do { candidate = candidate.next; if (!IsDuplicateNamespaceAttribute(candidate)) { return candidate; } } while (candidate != e.lastAttr); } return null; } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using NCsvLib; using NUnit.Framework; namespace NCsvLibTestSuite { [TestFixture] public class CsvSchemaReaderXmlTest { [Test] public void GetSchemaFromFile() { SchemaReaderXml rdr = new SchemaReaderXml(Helpers.SchFileName); Schema sch = rdr.Sch; AssertSchema(sch); } [Test] public void GetSchemaFromStream() { using (StreamReader txtr = new StreamReader(Helpers.SchFileName)) { SchemaReaderXml rdr = new SchemaReaderXml(txtr.BaseStream); Schema sch = rdr.Sch; AssertSchema(sch); } } private void AssertSchema(Schema sch) { SchemaRecord rec; SchemaRecordComposite comp; Assert.That(sch.Count, Is.EqualTo(4)); //options Assert.That(sch.Options.FieldSeparator, Is.EqualTo("|")); Assert.That(sch.Options.LastFieldSeparator, Is.False); Assert.That(sch.Options.Eol, Is.EqualTo(Environment.NewLine)); Assert.That(sch.Options.Quotes, Is.EqualTo("\"")); Assert.That(sch.Options.Enc.EncodingName, Is.StringMatching("UTF-8")); //*** First record Assert.That(sch[0], Is.TypeOf(typeof(SchemaRecord))); rec = (SchemaRecord)sch[0]; Assert.That(rec.Count, Is.EqualTo(8)); Assert.That(rec.Id, Is.EqualTo("R1")); Assert.That(rec.Limit.Offset, Is.EqualTo(0)); Assert.That(rec.Limit.Max, Is.EqualTo(0)); Assert.That(rec.ColHeaders, Is.True); //intfld Assert.That(rec[0].Name, Is.EqualTo("intfld")); Assert.That(rec[0].AddQuotes, Is.False); Assert.That(rec[0].FldType, Is.EqualTo(SchemaFieldType.Int)); Assert.That(rec[0].Filled, Is.EqualTo(true)); Assert.That(rec[0].FillChar, Is.EqualTo('0')); Assert.That(rec[0].Comment, Is.EqualTo("Comment for intfld")); Assert.That(rec[0].ColHdr, Is.StringMatching("int1")); //strfld Assert.That(rec[1].Name, Is.EqualTo("strfld")); Assert.That(rec[1].AddQuotes, Is.True); Assert.That(rec[1].FldType, Is.EqualTo(SchemaFieldType.String)); Assert.That(rec[1].Comment, Is.EqualTo(string.Empty)); Assert.That(rec[1].ColHdr, Is.StringMatching("str1")); //doublefld Assert.That(rec[2].Name, Is.EqualTo("doublefld")); Assert.That(rec[2].FldType, Is.EqualTo(SchemaFieldType.Double)); Assert.That(rec[2].ColHdr, Is.StringMatching("dbl1")); //decimalfld Assert.That(rec[3].Name, Is.EqualTo("decimalfld")); Assert.That(rec[3].FldType, Is.EqualTo(SchemaFieldType.Decimal)); Assert.That(rec[3].CustFmt, Is.TypeOf(typeof(NCsvLib.Formatters.NumberDigitsFormatter))); Assert.That(rec[3].ColHdr, Is.StringMatching("dec1")); //dtfld Assert.That(rec[4].Name, Is.EqualTo("dtfld")); Assert.That(rec[4].FldType, Is.EqualTo(SchemaFieldType.DateTime)); Assert.That(rec[4].ColHdr, Is.StringMatching("dt1")); //fixedfld Assert.That(rec[5].Name, Is.EqualTo("fixedfld")); Assert.That(rec[5].HasFixedValue, Is.True); Assert.That(rec[5].FixedValue, Is.EqualTo("AAA")); Assert.That(rec[5].ColHdr, Is.StringMatching("fix1")); //strfld2 Assert.That(rec[6].Name, Is.EqualTo("strfld2")); Assert.That(rec[6].FldType, Is.EqualTo(SchemaFieldType.String)); Assert.That(rec[6].CustFmt.GetType().Name, Is.StringMatching("DummyFormatter")); Assert.That(rec[6].ColHdr, Is.StringMatching("str1_2")); //boolfld Assert.That(rec[7].Name, Is.EqualTo("boolfld")); Assert.That(rec[7].FldType, Is.EqualTo(SchemaFieldType.Bool)); Assert.That(rec[7].BoolSettings.TrueValue, Is.StringMatching("true")); Assert.That(rec[7].BoolSettings.FalseValue, Is.StringMatching("false")); Assert.That(rec[7].BoolSettings.TrueIoValue, Is.EqualTo((int)1)); Assert.That(rec[7].BoolSettings.FalseIoValue, Is.EqualTo((int)0)); Assert.That(rec[7].BoolSettings.BoolIoType, Is.EqualTo(SchemaFieldBoolIoType.Int)); Assert.That(rec[7].ColHdr, Is.StringMatching("bool1")); //*** Second record (group RG1) Assert.That(sch[1], Is.TypeOf(typeof(SchemaRecordComposite))); comp = (SchemaRecordComposite)sch[1]; Assert.That(comp.Count, Is.EqualTo(2)); Assert.That(comp.Limit.Offset, Is.EqualTo(0)); Assert.That(comp.Limit.Max, Is.EqualTo(2)); Assert.That(comp[0], Is.TypeOf(typeof(SchemaRecord))); //record R2 rec = (SchemaRecord)comp[0]; Assert.That(rec.Count, Is.EqualTo(5)); Assert.That(rec.Limit.Offset, Is.EqualTo(0)); Assert.That(rec.Limit.Max, Is.EqualTo(4)); Assert.That(rec.ColHeaders, Is.False); //fixedr2 Assert.That(rec[0].Name, Is.EqualTo("fixedr2")); Assert.That(rec[0].HasFixedValue, Is.True); Assert.That(rec[0].FixedValue, Is.EqualTo("FLDR2")); Assert.That(rec[0].ColHdr, Is.StringMatching(string.Empty)); //intr2 Assert.That(rec[1].Name, Is.EqualTo("intr2")); Assert.That(rec[1].AddQuotes, Is.False); Assert.That(rec[1].FldType, Is.EqualTo(SchemaFieldType.Int)); Assert.That(rec[1].Filled, Is.True); Assert.That(rec[1].FillChar, Is.EqualTo('0')); //intr2left Assert.That(rec[2].Name, Is.EqualTo("intr2left")); Assert.That(rec[2].AddQuotes, Is.False); Assert.That(rec[2].FldType, Is.EqualTo(SchemaFieldType.Int)); Assert.That(rec[2].Alignment, Is.EqualTo(SchemaValueAlignment.Left)); Assert.That(rec[2].Filled, Is.True); Assert.That(rec[2].FillChar, Is.EqualTo('0')); //strr2 Assert.That(rec[3].Name, Is.EqualTo("strr2")); Assert.That(rec[3].AddQuotes, Is.True); Assert.That(rec[3].FldType, Is.EqualTo(SchemaFieldType.String)); Assert.That(rec[3].NullValueWrt, Is.EqualTo("ABCD")); //bool2 Assert.That(rec[4].Name, Is.EqualTo("bool2")); Assert.That(rec[4].FldType, Is.EqualTo(SchemaFieldType.Bool)); Assert.That(rec[4].BoolSettings.TrueValue, Is.StringMatching("TTT")); Assert.That(rec[4].BoolSettings.FalseValue, Is.StringMatching("FFF")); Assert.That(rec[4].BoolSettings.TrueIoValue, Is.StringMatching("T")); Assert.That(rec[4].BoolSettings.FalseIoValue, Is.StringMatching("F")); Assert.That(rec[4].BoolSettings.BoolIoType, Is.EqualTo(SchemaFieldBoolIoType.String)); //record R3 rec = (SchemaRecord)comp[1]; Assert.That(rec.Count, Is.EqualTo(3)); Assert.That(rec.Limit.Offset, Is.EqualTo(0)); Assert.That(rec.Limit.Max, Is.EqualTo(4)); Assert.That(rec.ColHeaders, Is.False); //fixedr3 Assert.That(rec[0].Name, Is.EqualTo("fixedr3")); Assert.That(rec[0].HasFixedValue, Is.True); Assert.That(rec[0].FixedValue, Is.EqualTo("FLDR3")); //intr3 Assert.That(rec[1].Name, Is.EqualTo("intr3")); Assert.That(rec[1].AddQuotes, Is.True); Assert.That(rec[1].Quotes, Is.StringMatching("'")); Assert.That(rec[1].FldType, Is.EqualTo(SchemaFieldType.Int)); //strr3 Assert.That(rec[2].Name, Is.EqualTo("strr3")); Assert.That(rec[2].AddQuotes, Is.True); Assert.That(rec[2].FldType, Is.EqualTo(SchemaFieldType.String)); //*** Third record (R4) Assert.That(sch[2], Is.TypeOf(typeof(SchemaRecord))); rec = (SchemaRecord)sch[2]; Assert.That(rec.Limit.Offset, Is.EqualTo(3)); Assert.That(rec.Limit.Max, Is.EqualTo(5)); Assert.That(rec.ColHeaders, Is.False); //fixedr4 Assert.That(rec[0].Name, Is.EqualTo("fixedr4")); Assert.That(rec[0].HasFixedValue, Is.True); Assert.That(rec[0].FixedValue, Is.EqualTo("FLDR4")); //intr4 Assert.That(rec[1].Name, Is.EqualTo("intr4")); Assert.That(rec[1].AddQuotes, Is.False); Assert.That(rec[1].FldType, Is.EqualTo(SchemaFieldType.Int)); Assert.That(rec[1].Size, Is.EqualTo(5)); //doublefld Assert.That(rec[2].Name, Is.EqualTo("doubler4")); Assert.That(rec[2].FldType, Is.EqualTo(SchemaFieldType.Double)); //decimalfld Assert.That(rec[3].Name, Is.EqualTo("decimalr4")); Assert.That(rec[3].FldType, Is.EqualTo(SchemaFieldType.Decimal)); //*** Second group (group RG2) Assert.That(sch[3], Is.TypeOf(typeof(SchemaRecordComposite))); comp = (SchemaRecordComposite)sch[3]; Assert.That(comp.Count, Is.EqualTo(2)); Assert.That(comp.Limit.Offset, Is.EqualTo(0)); Assert.That(comp.Limit.Max, Is.EqualTo(0)); Assert.That(comp[0], Is.TypeOf(typeof(SchemaRecord))); //record R5 rec = (SchemaRecord)comp[0]; Assert.That(rec.Count, Is.EqualTo(2)); Assert.That(rec.Limit.Offset, Is.EqualTo(0)); Assert.That(rec.Limit.Max, Is.EqualTo(2)); Assert.That(rec.ColHeaders, Is.False); //intr5 Assert.That(rec[0].Name, Is.EqualTo("intr5")); Assert.That(rec[0].AddQuotes, Is.False); Assert.That(rec[0].FldType, Is.EqualTo(SchemaFieldType.Int)); Assert.That(rec[0].Filled, Is.False); //strr5 Assert.That(rec[1].Name, Is.EqualTo("strr5")); Assert.That(rec[1].AddQuotes, Is.False); Assert.That(rec[1].FldType, Is.EqualTo(SchemaFieldType.String)); //record R6 rec = (SchemaRecord)comp[1]; Assert.That(rec.Count, Is.EqualTo(2)); Assert.That(rec.Limit.Offset, Is.EqualTo(0)); Assert.That(rec.Limit.Max, Is.EqualTo(2)); Assert.That(rec.ColHeaders, Is.False); //intr6 Assert.That(rec[0].Name, Is.EqualTo("intr6")); Assert.That(rec[0].AddQuotes, Is.False); Assert.That(rec[0].FldType, Is.EqualTo(SchemaFieldType.Int)); Assert.That(rec[0].Filled, Is.False); //strr6 Assert.That(rec[1].Name, Is.EqualTo("strr6")); Assert.That(rec[1].AddQuotes, Is.False); Assert.That(rec[1].FldType, Is.EqualTo(SchemaFieldType.String)); } } }
// Copyright 2016 Applied Geographics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web.Script.Serialization; using System.Web.SessionState; using System.Web.UI; using GeoAPI.Geometries; using NetTopologySuite.Geometries; using ICSharpCode.SharpZipLib.GZip; public class AppState { private const char Separator = '\u0001'; private const char Separator2 = '\u0002'; private const char Separator3 = '\u0004'; private const string Key = "AppState"; private const char VersionMarker = '\u0003'; private const string CurrentVersion = "5.0"; public static AppState FromJson(string json) { return GetJsonSerializer().Deserialize<AppState>(json); } public static bool IsIn(HttpSessionState session) { return session[Key] != null; } public static bool IsIn(StateBag viewState) { return viewState[Key] != null; } public static void RemoveFrom(HttpSessionState session) { if (IsIn(session)) { session.Remove(Key); } } public static void RemoveFrom(StateBag viewState) { if (IsIn(viewState)) { viewState.Remove(Key); } } public static AppState RestoreFrom(HttpSessionState session) { return RestoreFrom(session, true); } public static AppState RestoreFrom(HttpSessionState session, bool remove) { if (IsIn(session)) { AppState appState = FromString((string)session[Key]); if (remove) { RemoveFrom(session); } return appState; } else { return new AppState(); } } public static AppState RestoreFrom(StateBag viewState) { return RestoreFrom(viewState, true); } public static AppState RestoreFrom(StateBag viewState, bool remove) { if (IsIn(viewState)) { AppState appState = FromString((string)viewState[Key]); if (remove) { RemoveFrom(viewState); } return appState; } else { return new AppState(); } } private static List<Markup> CoordinateMarkupFromString(string value) { List<Markup> markup = new List<Markup>(); if (value.Length > 0) { string[] values = value.Split(Separator2); for (int i = 0; i < values.Length; ++i) { string[] coords = values[i].Split(','); string point = String.Format("POINT({0} {1})", coords[0], coords[1]); markup.Add(new Markup(point, "#000000", 1)); } } return markup; } private static T FromJson<T>(string json) { return GetJsonSerializer().Deserialize<T>(json); } public static AppState FromString(string stateString) { Queue values = new Queue(stateString.Split(Separator)); AppState appState = new AppState(); string version = ((string)values.Peek())[0] != VersionMarker ? "2.0" : ((string)values.Dequeue()).Substring(1); int tab; FunctionTab functionTabs; switch (version) { case "2.0": appState.Application = (string)values.Dequeue(); appState.MapTab = (string)values.Dequeue(); appState.TargetLayer = (string)values.Dequeue(); appState.SelectionLayer = (string)values.Dequeue(); values.Dequeue(); // skip SelectionDistance appState.ActiveMapId = (string)values.Dequeue(); appState.ActiveDataId = (string)values.Dequeue(); appState.TargetIds = StringCollection.FromString((string)values.Dequeue()); appState.SelectionIds = StringCollection.FromString((string)values.Dequeue()); appState.Query = (string)values.Dequeue(); appState.DataTab = (string)values.Dequeue(); appState.MarkupCategory = (string)values.Dequeue(); appState.MarkupGroups = StringCollection.FromString((string)values.Dequeue()); tab = Convert.ToInt32((string)values.Dequeue()); functionTabs = FunctionTab.All; switch (tab) { case 1: functionTabs = FunctionTab.Selection; break; case 2: functionTabs = FunctionTab.Markup; break; case 3: functionTabs = FunctionTab.None; break; } appState.FunctionTabs = functionTabs; appState.ActiveFunctionTab = functionTabs == FunctionTab.All ? FunctionTab.Selection : functionTabs; appState.Extent = ProjectExtent(EnvelopeExtensions.FromDelimitedString((string)values.Dequeue(), Separator2)); break; case "2.1": appState.Application = (string)values.Dequeue(); appState.MapTab = (string)values.Dequeue(); appState.Action = (Action)(Convert.ToInt32((string)values.Dequeue())); appState.TargetLayer = (string)values.Dequeue(); appState.TargetIds = StringCollection.FromString((string)values.Dequeue()); appState.ActiveMapId = (string)values.Dequeue(); appState.ActiveDataId = (string)values.Dequeue(); appState.Proximity = (string)values.Dequeue(); appState.SelectionLayer = (string)values.Dequeue(); appState.SelectionIds = StringCollection.FromString((string)values.Dequeue()); appState.Query = (string)values.Dequeue(); appState.DataTab = (string)values.Dequeue(); appState.MarkupCategory = (string)values.Dequeue(); appState.MarkupGroups = StringCollection.FromString((string)values.Dequeue()); tab = Convert.ToInt32((string)values.Dequeue()); functionTabs = FunctionTab.All; switch (tab) { case 0: functionTabs = FunctionTab.None; break; case 1: functionTabs = FunctionTab.Selection; break; case 2: functionTabs = FunctionTab.Markup; break; } appState.FunctionTabs = functionTabs; appState.ActiveFunctionTab = functionTabs == FunctionTab.All ? FunctionTab.Selection : functionTabs; appState.Extent = ProjectExtent(EnvelopeExtensions.FromDelimitedString((string)values.Dequeue(), Separator2)); appState.Markup = CoordinateMarkupFromString((string)values.Dequeue()); break; case "2.4": appState.Application = (string)values.Dequeue(); appState.MapTab = (string)values.Dequeue(); appState.Action = (Action)(Convert.ToInt32((string)values.Dequeue())); appState.TargetLayer = (string)values.Dequeue(); appState.TargetIds = StringCollection.FromString((string)values.Dequeue()); appState.ActiveMapId = (string)values.Dequeue(); appState.ActiveDataId = (string)values.Dequeue(); appState.Proximity = (string)values.Dequeue(); appState.SelectionLayer = (string)values.Dequeue(); appState.SelectionIds = StringCollection.FromString((string)values.Dequeue()); appState.Query = (string)values.Dequeue(); appState.DataTab = (string)values.Dequeue(); appState.MarkupCategory = (string)values.Dequeue(); appState.MarkupGroups = StringCollection.FromString((string)values.Dequeue()); appState.FunctionTabs = (FunctionTab)(Convert.ToInt32((string)values.Dequeue())); appState.ActiveFunctionTab = (FunctionTab)(Convert.ToInt32((string)values.Dequeue())); appState.Extent = ProjectExtent(EnvelopeExtensions.FromDelimitedString((string)values.Dequeue(), Separator2)); appState.Markup = CoordinateMarkupFromString((string)values.Dequeue()); break; case "2.5": appState.Application = (string)values.Dequeue(); appState.MapTab = (string)values.Dequeue(); appState.Action = (Action)(Convert.ToInt32((string)values.Dequeue())); appState.TargetLayer = (string)values.Dequeue(); appState.TargetIds = StringCollection.FromString((string)values.Dequeue()); appState.ActiveMapId = (string)values.Dequeue(); appState.ActiveDataId = (string)values.Dequeue(); appState.Proximity = (string)values.Dequeue(); appState.SelectionLayer = (string)values.Dequeue(); appState.SelectionIds = StringCollection.FromString((string)values.Dequeue()); appState.Query = (string)values.Dequeue(); appState.DataTab = (string)values.Dequeue(); appState.MarkupCategory = (string)values.Dequeue(); appState.MarkupGroups = StringCollection.FromString((string)values.Dequeue()); appState.FunctionTabs = (FunctionTab)(Convert.ToInt32((string)values.Dequeue())); appState.ActiveFunctionTab = (FunctionTab)(Convert.ToInt32((string)values.Dequeue())); appState.Extent = ProjectExtent(EnvelopeExtensions.FromDelimitedString((string)values.Dequeue(), Separator2)); appState.Markup = CoordinateMarkupFromString((string)values.Dequeue()); appState.VisibleLayers = LayersFromString((string)values.Dequeue()); break; case "3.1": appState.Application = (string)values.Dequeue(); appState.MapTab = (string)values.Dequeue(); appState.Action = (Action)(Convert.ToInt32((string)values.Dequeue())); appState.TargetLayer = (string)values.Dequeue(); appState.TargetIds = StringCollection.FromString((string)values.Dequeue()); appState.ActiveMapId = (string)values.Dequeue(); appState.ActiveDataId = (string)values.Dequeue(); appState.Proximity = (string)values.Dequeue(); appState.SelectionLayer = (string)values.Dequeue(); appState.SelectionIds = StringCollection.FromString((string)values.Dequeue()); appState.Query = (string)values.Dequeue(); appState.DataTab = (string)values.Dequeue(); appState.MarkupCategory = (string)values.Dequeue(); appState.MarkupGroups = StringCollection.FromString((string)values.Dequeue()); appState.FunctionTabs = (FunctionTab)(Convert.ToInt32((string)values.Dequeue())); appState.ActiveFunctionTab = (FunctionTab)(Convert.ToInt32((string)values.Dequeue())); appState.Extent = ProjectExtent(EnvelopeExtensions.FromDelimitedString((string)values.Dequeue(), Separator2)); appState.Markup = CoordinateMarkupFromString((string)values.Dequeue()); appState.VisibleLayers = LayersFromString((string)values.Dequeue()); appState.Level = (string)values.Dequeue(); if (values.Count > 0) { var text = (string)values.Dequeue(); if (!String.IsNullOrEmpty(text) && text != "1") { appState.Markup[0].Text = text; } } break; case "4.2": appState.Application = (string)values.Dequeue(); appState.MapTab = (string)values.Dequeue(); appState.Action = (Action)(Convert.ToInt32((string)values.Dequeue())); appState.TargetLayer = (string)values.Dequeue(); appState.TargetIds = StringCollection.FromString((string)values.Dequeue()); appState.ActiveMapId = (string)values.Dequeue(); appState.ActiveDataId = (string)values.Dequeue(); appState.Proximity = (string)values.Dequeue(); appState.SelectionLayer = (string)values.Dequeue(); appState.SelectionIds = StringCollection.FromString((string)values.Dequeue()); appState.Query = (string)values.Dequeue(); appState.DataTab = (string)values.Dequeue(); appState.MarkupCategory = (string)values.Dequeue(); appState.MarkupGroups = StringCollection.FromString((string)values.Dequeue()); appState.Markup = FromJson<List<Markup>>((string)values.Dequeue()); appState.FunctionTabs = (FunctionTab)(Convert.ToInt32((string)values.Dequeue())); appState.ActiveFunctionTab = (FunctionTab)(Convert.ToInt32((string)values.Dequeue())); appState.Extent = ProjectExtent(EnvelopeExtensions.FromDelimitedString((string)values.Dequeue(), Separator2)); appState.VisibleLayers = LayersFromString((string)values.Dequeue()); appState.Level = (string)values.Dequeue(); break; case "5.0": appState.Application = (string)values.Dequeue(); appState.MapTab = (string)values.Dequeue(); appState.Search = (string)values.Dequeue(); appState.SearchCriteria = FromJson<Dictionary<String, Object>>((string)values.Dequeue()); appState.Action = (Action)(Convert.ToInt32((string)values.Dequeue())); appState.TargetLayer = (string)values.Dequeue(); appState.TargetIds = StringCollection.FromString((string)values.Dequeue()); appState.ActiveMapId = (string)values.Dequeue(); appState.ActiveDataId = (string)values.Dequeue(); appState.Proximity = (string)values.Dequeue(); appState.SelectionLayer = (string)values.Dequeue(); appState.SelectionIds = StringCollection.FromString((string)values.Dequeue()); appState.Query = (string)values.Dequeue(); appState.DataTab = (string)values.Dequeue(); appState.MarkupCategory = (string)values.Dequeue(); appState.MarkupGroups = StringCollection.FromString((string)values.Dequeue()); appState.Markup = FromJson<List<Markup>>((string)values.Dequeue()); appState.FunctionTabs = (FunctionTab)(Convert.ToInt32((string)values.Dequeue())); appState.ActiveFunctionTab = (FunctionTab)(Convert.ToInt32((string)values.Dequeue())); appState.Extent = EnvelopeExtensions.FromDelimitedString((string)values.Dequeue(), Separator2); appState.VisibleLayers = LayersFromString((string)values.Dequeue()); appState.VisibleTiles = LayersFromString((string)values.Dequeue()); appState.Level = (string)values.Dequeue(); break; } return appState; } public static AppState FromCompressedString(string stateString) { byte[] compressedData = Convert.FromBase64String(stateString.Replace("!", "/").Replace("*", "+").Replace("$", "=")); GZipInputStream zipStream = new GZipInputStream(new MemoryStream(compressedData)); int size; byte[] data = new byte[1024]; StringBuilder builder = new StringBuilder(); try { while ((size = zipStream.Read(data, 0, data.Length)) > 0) { builder.Append(Encoding.UTF8.GetString(data, 0, size)); } } catch (Exception ex) { throw new AppException("Could not uncompress the provided application state string", ex); } finally { zipStream.Close(); } return FromString(builder.ToString()); } private static JavaScriptSerializer GetJsonSerializer() { JavaScriptSerializer serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new GeometryConverter() }); return serializer; } private static Dictionary<String, StringCollection> LayersFromString(string value) { Dictionary<String, StringCollection> dict = new Dictionary<String, StringCollection>(); if (value.Length > 0) { string[] layers = value.Split(Separator2); for (int i = 0; i < layers.Length; ++i) { StringCollection values = new StringCollection(); values.AddRange(layers[i].Split(Separator3)); string key = values[0]; values.RemoveAt(0); dict.Add(key, values); } } return dict; } private static Envelope ProjectExtent(Envelope originalExtent) { AppSettings appSettings = AppContext.AppSettings; Envelope projectedExtent = originalExtent; if (appSettings.MapCoordinateSystem != null && appSettings.MeasureCoordinateSystem != null && !appSettings.MapCoordinateSystem.Equals(appSettings.MeasureCoordinateSystem)) { projectedExtent = appSettings.MapCoordinateSystem.ToProjected(appSettings.MeasureCoordinateSystem.ToGeodetic(originalExtent)); } return projectedExtent; } private SelectionManager _selectionManager = null; public string Application = ""; public string MapTab = ""; public string Level = ""; public string Search = ""; public Dictionary<String, Object> SearchCriteria = new Dictionary<String, Object>(); public Action Action = Action.Select; public string TargetLayer = ""; public StringCollection TargetIds = new StringCollection(); public string ActiveMapId = ""; public string ActiveDataId = ""; public string Proximity = ""; public string SelectionLayer = ""; public StringCollection SelectionIds = new StringCollection(); public string Query = ""; public string DataTab = ""; public string MarkupCategory = ""; public StringCollection MarkupGroups = new StringCollection(); public List<Markup> Markup = new List<Markup>(); public FunctionTab FunctionTabs = FunctionTab.None; public FunctionTab ActiveFunctionTab = FunctionTab.None; public Envelope Extent = null; public Dictionary<String, StringCollection> VisibleLayers = new Dictionary<String, StringCollection>(); public Dictionary<String, StringCollection> VisibleTiles = new Dictionary<String, StringCollection>(); public AppState() { _selectionManager = new SelectionManager(this); } [ScriptIgnore] public SelectionManager SelectionManager { get { return _selectionManager; } } private string MarkupToJson(List<Markup> markup) { return GetJsonSerializer().Serialize(markup); } public void SaveTo(HttpSessionState session) { session[Key] = ToString(); } public void SaveTo(StateBag viewState) { viewState[Key] = ToString(); } private String ToJson(object obj) { return GetJsonSerializer().Serialize(obj); } private string CoordinatesToString(List<Coordinate> points) { StringCollection coords = new StringCollection(); for (int i = 0; i < points.Count; ++i) { coords.Add(points[i].X.ToString() + "," + points[i].Y.ToString()); } return coords.Join(Separator2.ToString()); } private string LayersToString(Dictionary<String, StringCollection> dict) { StringCollection layers = new StringCollection(); foreach (string key in dict.Keys) { string s = key; if (dict[key].Count > 0) { s += Separator3.ToString() + dict[key].Join(Separator3.ToString()); } layers.Add(s); } return layers.Join(Separator2.ToString()); } public string ToCompressedString() { byte[] data = Encoding.UTF8.GetBytes(ToString()); MemoryStream memoryStream = new MemoryStream(); GZipOutputStream zipStream = new GZipOutputStream(memoryStream); zipStream.Write(data, 0, data.Length); zipStream.Close(); string s = Convert.ToBase64String(memoryStream.ToArray()); return s.Replace("/", "!").Replace("+", "*").Replace("=", "$"); } public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append(VersionMarker + CurrentVersion + Separator); builder.Append(Application + Separator); builder.Append(MapTab + Separator); builder.Append(Search + Separator); builder.Append(ToJson(SearchCriteria) + Separator); builder.Append(Action.ToString("d") + Separator); builder.Append(TargetLayer + Separator); builder.Append(TargetIds.ToString() + Separator); builder.Append(ActiveMapId + Separator); builder.Append(ActiveDataId + Separator); builder.Append(Proximity + Separator); builder.Append(SelectionLayer + Separator); builder.Append(SelectionIds.ToString() + Separator); builder.Append(Query + Separator); builder.Append(DataTab + Separator); builder.Append(MarkupCategory + Separator); builder.Append(MarkupGroups.ToString() + Separator); builder.Append(ToJson(Markup) + Separator); builder.Append(FunctionTabs.ToString("d") + Separator); builder.Append(ActiveFunctionTab.ToString("d") + Separator); builder.Append(Extent.ToDelimitedString(Separator2) + Separator); builder.Append(LayersToString(VisibleLayers) + Separator); builder.Append(LayersToString(VisibleTiles) + Separator); builder.Append(Level + Separator); return builder.ToString(); } public string ToJson() { return GetJsonSerializer().Serialize(this); } private class GeometryConverter : JavaScriptConverter { public override object Deserialize(IDictionary<String, object> dictionary, Type type, JavaScriptSerializer serializer) { if (type == typeof(Coordinate)) { double[] coordinates = ((ArrayList)dictionary["coordinates"]).OfType<object>().Select(o => Convert.ToDouble(o)).ToArray(); return new Coordinate(coordinates[0], coordinates[1]); } if (type == typeof(Envelope)) { double[] bbox = ((ArrayList)dictionary["bbox"]).OfType<object>().Select(o => Convert.ToDouble(o)).ToArray(); return new Envelope(new Coordinate(bbox[0], bbox[1]), new Coordinate(bbox[2], bbox[3])); } return null; } public override IDictionary<String, object> Serialize(object obj, JavaScriptSerializer serializer) { Dictionary<String, object> dictionary = new Dictionary<String, object>(); Envelope envelope = obj as Envelope; if (envelope != null) { dictionary.Add("bbox", new double[] { envelope.MinX, envelope.MinY, envelope.MaxX, envelope.MaxY }); return dictionary; } return null; } public override IEnumerable<Type> SupportedTypes { get { return new Type[] { typeof(Envelope) }; } } } }
// 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.Text; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Encoding.Tests { public class DerEncoderTests { [Theory] [InlineData("00", 0x02, "01", "00")] [InlineData("01", 0x02, "01", "01")] [InlineData("7F", 0x02, "01", "7F")] [InlineData("80", 0x02, "02", "0080")] [InlineData("FF", 0x02, "02", "00FF")] [InlineData("00FF", 0x02, "02", "00FF")] [InlineData("01FF", 0x02, "02", "01FF")] [InlineData("7FFF", 0x02, "02", "7FFF")] [InlineData("8000", 0x02, "03", "008000")] [InlineData("FFFF", 0x02, "03", "00FFFF")] [InlineData("00FFFF", 0x02, "03", "00FFFF")] [InlineData("7FFFFF", 0x02, "03", "7FFFFF")] [InlineData("800000", 0x02, "04", "00800000")] [InlineData("FFFFFF", 0x02, "04", "00FFFFFF")] [InlineData("00FFFFFF", 0x02, "04", "00FFFFFF")] [InlineData("7FFFFFFF", 0x02, "04", "7FFFFFFF")] [InlineData("80000000", 0x02, "05", "0080000000")] [InlineData("FFFFFFFF", 0x02, "05", "00FFFFFFFF")] [InlineData("0123456789ABCDEF", 0x02, "08", "0123456789ABCDEF")] [InlineData("FEDCBA9876543210", 0x02, "09", "00FEDCBA9876543210")] public static void ValidateUintEncodings(string hexRaw, byte tag, string hexLength, string hexValue) { byte[] raw = hexRaw.HexToByteArray(); byte[] length = hexLength.HexToByteArray(); byte[] value = hexValue.HexToByteArray(); byte[][] segments = DerEncoder.SegmentedEncodeUnsignedInteger(raw); Assert.Equal(3, segments.Length); Assert.Equal(new[] { tag }, segments[0]); Assert.Equal(length, segments[1]); Assert.Equal(value, segments[2]); } [Theory] [InlineData("", 0, "01", "00")] [InlineData("00", 0, "02", "0000")] [InlineData("00", 7, "02", "0700")] [InlineData("0000", 0, "03", "000000")] [InlineData("007F", 7, "03", "070000")] [InlineData("007F", 6, "03", "060040")] [InlineData("007F", 5, "03", "050060")] [InlineData("007F", 4, "03", "040070")] [InlineData("007F", 3, "03", "030078")] [InlineData("007F", 2, "03", "02007C")] [InlineData("007F", 1, "03", "01007E")] [InlineData("007F", 0, "03", "00007F")] public static void ValidateBitStringEncodings(string hexRaw, int unusedBits, string hexLength, string encodedData) { byte[] input = hexRaw.HexToByteArray(); const byte tag = 0x03; byte[] length = hexLength.HexToByteArray(); byte[] expectedOutput = encodedData.HexToByteArray(); byte[][] segments = DerEncoder.SegmentedEncodeBitString(unusedBits, input); Assert.Equal(3, segments.Length); Assert.Equal(new[] { tag }, segments[0]); Assert.Equal(length, segments[1]); Assert.Equal(expectedOutput, segments[2]); } [Theory] [InlineData("", 9, "01", "00")] [InlineData("00", 9, "01", "00")] [InlineData("0000", 9, "01", "00")] [InlineData("007F", 9, "01", "00")] [InlineData("8000", 3, "02", "0780")] [InlineData("8FF0", 3, "02", "0780")] [InlineData("8FF0", 7, "02", "018E")] [InlineData("8FF0", 8, "02", "008F")] [InlineData("8FF0", 9, "03", "078F80")] public static void ValidateNamedBitEncodings(string hexRaw, int namedBits, string hexLength, string encodedData) { byte[] input = hexRaw.HexToByteArray(); const byte tag = 0x03; byte[] length = hexLength.HexToByteArray(); byte[] expectedOutput = encodedData.HexToByteArray(); byte[][] segments = DerEncoder.SegmentedEncodeNamedBitList(input, namedBits); Assert.Equal(3, segments.Length); Assert.Equal(new[] { tag }, segments[0]); Assert.Equal(length, segments[1]); Assert.Equal(expectedOutput, segments[2]); } [Theory] [InlineData("010203040506070809", "09")] [InlineData("", "00")] public static void ValidateOctetStringEncodings(string hexData, string hexLength) { byte[] input = hexData.HexToByteArray(); const byte tag = 0x04; byte[] length = hexLength.HexToByteArray(); byte[][] segments = DerEncoder.SegmentedEncodeOctetString(input); Assert.Equal(3, segments.Length); Assert.Equal(new[] { tag }, segments[0]); Assert.Equal(length, segments[1]); Assert.Equal(input, segments[2]); } [Theory] [InlineData("1.3.6.1.5.5.7.3.1", "08", "2B06010505070301")] [InlineData("1.3.6.1.5.5.7.3.2", "08", "2B06010505070302")] [InlineData("2.999.3", "03", "883703")] [InlineData("2.999.19427512891.25", "08", "8837C8AFE1A43B19")] public static void ValidateOidEncodings(string oidValue, string hexLength, string encodedData) { Oid oid = new Oid(oidValue, oidValue); const byte tag = 0x06; byte[] length = hexLength.HexToByteArray(); byte[] expectedOutput = encodedData.HexToByteArray(); byte[][] segments = DerEncoder.SegmentedEncodeOid(oid); Assert.Equal(3, segments.Length); Assert.Equal(new[] { tag }, segments[0]); Assert.Equal(length, segments[1]); Assert.Equal(expectedOutput, segments[2]); } [Fact] public static void ConstructSequence() { byte[] expected = { /* SEQUENCE */ 0x30, 0x07, /* INTEGER(0) */ 0x02, 0x01, 0x00, /* INTEGER(256) */ 0x02, 0x02, 0x01, 0x00, }; byte[] encoded = DerEncoder.ConstructSequence( DerEncoder.SegmentedEncodeUnsignedInteger(new byte[] { 0x00 }), DerEncoder.SegmentedEncodeUnsignedInteger(new byte[] { 0x01, 0x00 })); Assert.Equal(expected, encoded); } [Theory] [InlineData("", true)] [InlineData("This is a PrintableString.", true)] [InlineData("This is not @ PrintableString.", false)] [InlineData("\u65E5\u672C\u8A9E is not a PrintableString", false)] public static void CheckPrintableString(string candidate, bool expected) { Assert.Equal(expected, DerEncoder.IsValidPrintableString(candidate.ToCharArray())); } // No bounds check tests are done here, because the method is currently assert-based, // not exception-based. [Theory] [InlineData("", 0, 0, true)] [InlineData("This is a PrintableString.", 0, 26, true)] [InlineData("This is not @ PrintableString.", 0, 30, false)] [InlineData("This is not @ PrintableString.", 0, 12, true)] [InlineData("This is not @ PrintableString.", 12, 0, true)] [InlineData("This is not @ PrintableString.", 12, 1, false)] [InlineData("This is not @ PrintableString.", 13, 17, true)] [InlineData("\u65E5\u672C\u8A9E is not a PrintableString", 0, 27, false)] [InlineData("\u65E5\u672C\u8A9E is not a PrintableString", 0, 0, true)] [InlineData("\u65E5\u672C\u8A9E is not a PrintableString", 3, 24, true)] public static void CheckPrintableSubstring(string candidate, int offset, int length, bool expected) { Assert.Equal(expected, DerEncoder.IsValidPrintableString(candidate.ToCharArray(), offset, length)); } [Theory] [InlineData("", "")] [InlineData("Hello", "48656C6C6F")] [InlineData("banana", "62616E616E61")] public static void CheckIA5StringEncoding(string input, string expectedHex) { byte[][] encodedString = DerEncoder.SegmentedEncodeIA5String(input.ToCharArray()); Assert.NotNull(encodedString); Assert.Equal(3, encodedString.Length); // Check the tag Assert.NotNull(encodedString[0]); Assert.Equal(1, encodedString[0].Length); Assert.Equal(0x16, encodedString[0][0]); // Check the length. Since the input cases are all less than 0x7F bytes // the length is only one byte. Assert.NotNull(encodedString[1]); Assert.Equal(1, encodedString[1].Length); Assert.Equal(expectedHex.Length / 2, encodedString[1][0]); // Check the value Assert.Equal(expectedHex.HexToByteArray(), encodedString[2]); // And, full roundtrip Assert.Equal(input, Text.Encoding.ASCII.GetString(encodedString[2])); } [Theory] [InlineData("Hello", 3, 2, "6C6F")] [InlineData("banana", 1, 4, "616E616E")] public static void CheckIA5SubstringEncoding(string input, int offset, int length, string expectedHex) { byte[][] encodedString = DerEncoder.SegmentedEncodeIA5String(input.ToCharArray(), offset, length); Assert.NotNull(encodedString); Assert.Equal(3, encodedString.Length); // Check the tag Assert.NotNull(encodedString[0]); Assert.Equal(1, encodedString[0].Length); Assert.Equal(0x16, encodedString[0][0]); // Check the length. Since the input cases are all less than 0x7F bytes // the length is only one byte. Assert.NotNull(encodedString[1]); Assert.Equal(1, encodedString[1].Length); Assert.Equal(expectedHex.Length / 2, encodedString[1][0]); // Check the value Assert.Equal(expectedHex.HexToByteArray(), encodedString[2]); // And, full roundtrip Assert.Equal(input.Substring(offset, length), Text.Encoding.ASCII.GetString(encodedString[2])); } [Theory] [InlineData("", "")] [InlineData("Hello", "48656C6C6F")] [InlineData("banana", "62616E616E61")] public static void CheckPrintableStringEncoding(string input, string expectedHex) { byte[][] encodedString = DerEncoder.SegmentedEncodePrintableString(input.ToCharArray()); Assert.NotNull(encodedString); Assert.Equal(3, encodedString.Length); // Check the tag Assert.NotNull(encodedString[0]); Assert.Equal(1, encodedString[0].Length); Assert.Equal(0x13, encodedString[0][0]); // Check the length. Since the input cases are all less than 0x7F bytes // the length is only one byte. Assert.NotNull(encodedString[1]); Assert.Equal(1, encodedString[1].Length); Assert.Equal(expectedHex.Length / 2, encodedString[1][0]); // Check the value Assert.Equal(expectedHex.HexToByteArray(), encodedString[2]); // And, full roundtrip Assert.Equal(input, Text.Encoding.ASCII.GetString(encodedString[2])); } [Theory] [InlineData("Hello", 3, 2, "6C6F")] [InlineData("banana", 1, 4, "616E616E")] public static void CheckPrintableSubstringEncoding(string input, int offset, int length, string expectedHex) { byte[][] encodedString = DerEncoder.SegmentedEncodePrintableString(input.ToCharArray(), offset, length); Assert.NotNull(encodedString); Assert.Equal(3, encodedString.Length); // Check the tag Assert.NotNull(encodedString[0]); Assert.Equal(1, encodedString[0].Length); Assert.Equal(0x13, encodedString[0][0]); // Check the length. Since the input cases are all less than 0x7F bytes // the length is only one byte. Assert.NotNull(encodedString[1]); Assert.Equal(1, encodedString[1].Length); Assert.Equal(expectedHex.Length / 2, encodedString[1][0]); // Check the value Assert.Equal(expectedHex.HexToByteArray(), encodedString[2]); // And, full roundtrip Assert.Equal(input.Substring(offset, length), Text.Encoding.ASCII.GetString(encodedString[2])); } [Theory] [InlineData("", "")] [InlineData("Hello", "48656C6C6F")] [InlineData("banana", "62616E616E61")] [InlineData("\u65E5\u672C\u8A9E", "E697A5E69CACE8AA9E")] public static void CheckUTF8StringEncoding(string input, string expectedHex) { byte[][] encodedString = DerEncoder.SegmentedEncodeUtf8String(input.ToCharArray()); Assert.NotNull(encodedString); Assert.Equal(3, encodedString.Length); // Check the tag Assert.NotNull(encodedString[0]); Assert.Equal(1, encodedString[0].Length); Assert.Equal(0x0C, encodedString[0][0]); // Check the length. Since the input cases are all less than 0x7F bytes // the length is only one byte. Assert.NotNull(encodedString[1]); Assert.Equal(1, encodedString[1].Length); Assert.Equal(expectedHex.Length / 2, encodedString[1][0]); // Check the value Assert.Equal(expectedHex.HexToByteArray(), encodedString[2]); // And, full roundtrip Assert.Equal(input, Text.Encoding.UTF8.GetString(encodedString[2])); } [Theory] [InlineData("Hello", 3, 2, "6C6F")] [InlineData("banana", 1, 4, "616E616E")] [InlineData("\u65E5\u672C\u8A9E", 1, 1, "E69CAC")] public static void CheckUTF8SubstringEncoding(string input, int offset, int length, string expectedHex) { byte[][] encodedString = DerEncoder.SegmentedEncodeUtf8String(input.ToCharArray(), offset, length); Assert.NotNull(encodedString); Assert.Equal(3, encodedString.Length); // Check the tag Assert.NotNull(encodedString[0]); Assert.Equal(1, encodedString[0].Length); Assert.Equal(0x0C, encodedString[0][0]); // Check the length. Since the input cases are all less than 0x7F bytes // the length is only one byte. Assert.NotNull(encodedString[1]); Assert.Equal(1, encodedString[1].Length); Assert.Equal(expectedHex.Length / 2, encodedString[1][0]); // Check the value Assert.Equal(expectedHex.HexToByteArray(), encodedString[2]); // And, full roundtrip Assert.Equal(input.Substring(offset, length), Text.Encoding.UTF8.GetString(encodedString[2])); } } }
// 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.Diagnostics; using System.IO; using System.Reflection; using System.Xml.Xsl.IlGen; using System.Xml.Xsl.Qil; namespace System.Xml.Xsl.Runtime { /// <summary> /// Contains all static data that is used by the runtime. /// </summary> internal class XmlQueryStaticData { // Name of the field to serialize to public const string DataFieldName = "staticData"; public const string TypesFieldName = "ebTypes"; // Format version marker to support versioning: (major << 8) | minor private const int CurrentFormatVersion = (0 << 8) | 0; private XmlWriterSettings _defaultWriterSettings; private IList<WhitespaceRule> _whitespaceRules; private string[] _names; private StringPair[][] _prefixMappingsList; private Int32Pair[] _filters; private XmlQueryType[] _types; private XmlCollation[] _collations; private string[] _globalNames; private EarlyBoundInfo[] _earlyBound; /// <summary> /// Constructor. /// </summary> public XmlQueryStaticData(XmlWriterSettings defaultWriterSettings, IList<WhitespaceRule> whitespaceRules, StaticDataManager staticData) { Debug.Assert(defaultWriterSettings != null && staticData != null); _defaultWriterSettings = defaultWriterSettings; _whitespaceRules = whitespaceRules; _names = staticData.Names; _prefixMappingsList = staticData.PrefixMappingsList; _filters = staticData.NameFilters; _types = staticData.XmlTypes; _collations = staticData.Collations; _globalNames = staticData.GlobalNames; _earlyBound = staticData.EarlyBound; #if DEBUG // Round-trip check byte[] data; Type[] ebTypes; this.GetObjectData(out data, out ebTypes); XmlQueryStaticData copy = new XmlQueryStaticData(data, ebTypes); _defaultWriterSettings = copy._defaultWriterSettings; _whitespaceRules = copy._whitespaceRules; _names = copy._names; _prefixMappingsList = copy._prefixMappingsList; _filters = copy._filters; _types = copy._types; _collations = copy._collations; _globalNames = copy._globalNames; _earlyBound = copy._earlyBound; #endif } /// <summary> /// Deserialize XmlQueryStaticData object from a byte array. /// </summary> public XmlQueryStaticData(byte[] data, Type[] ebTypes) { MemoryStream dataStream = new MemoryStream(data, /*writable:*/false); XmlQueryDataReader dataReader = new XmlQueryDataReader(dataStream); int length; // Read a format version int formatVersion = dataReader.ReadInt32Encoded(); // Changes in the major part of version are not supported if ((formatVersion & ~0xff) > CurrentFormatVersion) throw new NotSupportedException(); // XmlWriterSettings defaultWriterSettings; _defaultWriterSettings = new XmlWriterSettings(dataReader); // IList<WhitespaceRule> whitespaceRules; length = dataReader.ReadInt32(); if (length != 0) { _whitespaceRules = new WhitespaceRule[length]; for (int idx = 0; idx < length; idx++) { _whitespaceRules[idx] = new WhitespaceRule(dataReader); } } // string[] names; length = dataReader.ReadInt32(); if (length != 0) { _names = new string[length]; for (int idx = 0; idx < length; idx++) { _names[idx] = dataReader.ReadString(); } } // StringPair[][] prefixMappingsList; length = dataReader.ReadInt32(); if (length != 0) { _prefixMappingsList = new StringPair[length][]; for (int idx = 0; idx < length; idx++) { int length2 = dataReader.ReadInt32(); _prefixMappingsList[idx] = new StringPair[length2]; for (int idx2 = 0; idx2 < length2; idx2++) { _prefixMappingsList[idx][idx2] = new StringPair(dataReader.ReadString(), dataReader.ReadString()); } } } // Int32Pair[] filters; length = dataReader.ReadInt32(); if (length != 0) { _filters = new Int32Pair[length]; for (int idx = 0; idx < length; idx++) { _filters[idx] = new Int32Pair(dataReader.ReadInt32Encoded(), dataReader.ReadInt32Encoded()); } } // XmlQueryType[] types; length = dataReader.ReadInt32(); if (length != 0) { _types = new XmlQueryType[length]; for (int idx = 0; idx < length; idx++) { _types[idx] = XmlQueryTypeFactory.Deserialize(dataReader); } } // XmlCollation[] collations; length = dataReader.ReadInt32(); if (length != 0) { _collations = new XmlCollation[length]; for (int idx = 0; idx < length; idx++) { _collations[idx] = new XmlCollation(dataReader); } } // string[] globalNames; length = dataReader.ReadInt32(); if (length != 0) { _globalNames = new string[length]; for (int idx = 0; idx < length; idx++) { _globalNames[idx] = dataReader.ReadString(); } } // EarlyBoundInfo[] earlyBound; length = dataReader.ReadInt32(); if (length != 0) { _earlyBound = new EarlyBoundInfo[length]; for (int idx = 0; idx < length; idx++) { _earlyBound[idx] = new EarlyBoundInfo(dataReader.ReadString(), ebTypes[idx]); } } Debug.Assert(formatVersion != CurrentFormatVersion || dataReader.Read() == -1, "Extra data at the end of the stream"); dataReader.Dispose(); } /// <summary> /// Serialize XmlQueryStaticData object into a byte array. /// </summary> public void GetObjectData(out byte[] data, out Type[] ebTypes) { MemoryStream dataStream = new MemoryStream(4096); XmlQueryDataWriter dataWriter = new XmlQueryDataWriter(dataStream); // First put the format version dataWriter.WriteInt32Encoded(CurrentFormatVersion); // XmlWriterSettings defaultWriterSettings; _defaultWriterSettings.GetObjectData(dataWriter); // IList<WhitespaceRule> whitespaceRules; if (_whitespaceRules == null) { dataWriter.Write(0); } else { dataWriter.Write(_whitespaceRules.Count); foreach (WhitespaceRule rule in _whitespaceRules) { rule.GetObjectData(dataWriter); } } // string[] names; if (_names == null) { dataWriter.Write(0); } else { dataWriter.Write(_names.Length); foreach (string name in _names) { dataWriter.Write(name); } } // StringPair[][] prefixMappingsList; if (_prefixMappingsList == null) { dataWriter.Write(0); } else { dataWriter.Write(_prefixMappingsList.Length); foreach (StringPair[] mappings in _prefixMappingsList) { dataWriter.Write(mappings.Length); foreach (StringPair mapping in mappings) { dataWriter.Write(mapping.Left); dataWriter.Write(mapping.Right); } } } // Int32Pair[] filters; if (_filters == null) { dataWriter.Write(0); } else { dataWriter.Write(_filters.Length); foreach (Int32Pair filter in _filters) { dataWriter.WriteInt32Encoded(filter.Left); dataWriter.WriteInt32Encoded(filter.Right); } } // XmlQueryType[] types; if (_types == null) { dataWriter.Write(0); } else { dataWriter.Write(_types.Length); foreach (XmlQueryType type in _types) { XmlQueryTypeFactory.Serialize(dataWriter, type); } } // XmlCollation[] collations; if (_collations == null) { dataWriter.Write(0); } else { dataWriter.Write(_collations.Length); foreach (XmlCollation collation in _collations) { collation.GetObjectData(dataWriter); } } // string[] globalNames; if (_globalNames == null) { dataWriter.Write(0); } else { dataWriter.Write(_globalNames.Length); foreach (string name in _globalNames) { dataWriter.Write(name); } } // EarlyBoundInfo[] earlyBound; if (_earlyBound == null) { dataWriter.Write(0); ebTypes = null; } else { dataWriter.Write(_earlyBound.Length); ebTypes = new Type[_earlyBound.Length]; int idx = 0; foreach (EarlyBoundInfo info in _earlyBound) { dataWriter.Write(info.NamespaceUri); ebTypes[idx++] = info.EarlyBoundType; } } dataWriter.Dispose(); data = dataStream.ToArray(); } /// <summary> /// Return the default writer settings. /// </summary> public XmlWriterSettings DefaultWriterSettings { get { return _defaultWriterSettings; } } /// <summary> /// Return the rules used for whitespace stripping/preservation. /// </summary> public IList<WhitespaceRule> WhitespaceRules { get { return _whitespaceRules; } } /// <summary> /// Return array of names used by this query. /// </summary> public string[] Names { get { return _names; } } /// <summary> /// Return array of prefix mappings used by this query. /// </summary> public StringPair[][] PrefixMappingsList { get { return _prefixMappingsList; } } /// <summary> /// Return array of name filter specifications used by this query. /// </summary> public Int32Pair[] Filters { get { return _filters; } } /// <summary> /// Return array of types used by this query. /// </summary> public XmlQueryType[] Types { get { return _types; } } /// <summary> /// Return array of collations used by this query. /// </summary> public XmlCollation[] Collations { get { return _collations; } } /// <summary> /// Return names of all global variables and parameters used by this query. /// </summary> public string[] GlobalNames { get { return _globalNames; } } /// <summary> /// Return array of early bound object information related to this query. /// </summary> public EarlyBoundInfo[] EarlyBound { get { return _earlyBound; } } } /// <summary> /// Subclass of BinaryReader used to serialize query static data. /// </summary> internal class XmlQueryDataReader : BinaryReader { public XmlQueryDataReader(Stream input) : base(input) { } /// <summary> /// Read in a 32-bit integer in compressed format. /// </summary> public int ReadInt32Encoded() { return Read7BitEncodedInt(); } /// <summary> /// Read a string value from the stream. Value can be null. /// </summary> public string ReadStringQ() { return ReadBoolean() ? ReadString() : null; } /// <summary> /// Read a signed byte value from the stream and check if it belongs to the given diapason. /// </summary> public sbyte ReadSByte(sbyte minValue, sbyte maxValue) { sbyte value = ReadSByte(); if (value < minValue) throw new ArgumentOutOfRangeException(nameof(minValue)); if (maxValue < value) throw new ArgumentOutOfRangeException(nameof(maxValue)); return value; } } /// <summary> /// Subclass of BinaryWriter used to deserialize query static data. /// </summary> internal class XmlQueryDataWriter : BinaryWriter { public XmlQueryDataWriter(Stream output) : base(output) { } /// <summary> /// Write a 32-bit integer in a compressed format. /// </summary> public void WriteInt32Encoded(int value) { Write7BitEncodedInt(value); } /// <summary> /// Write a string value to the stream. Value can be null. /// </summary> public void WriteStringQ(string value) { Write(value != null); if (value != null) { Write(value); } } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2016 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System; using System.Collections.Generic; static partial class MoreEnumerable { /// <summary> /// Creates an array from an <see cref="IEnumerable{T}"/> where a /// function is used to determine the index at which an element will /// be placed in the array. /// </summary> /// <param name="source">The source sequence for the array.</param> /// <param name="indexSelector"> /// A function that maps an element to its index.</param> /// <typeparam name="T"> /// The type of the element in <paramref name="source"/>.</typeparam> /// <returns> /// An array that contains the elements from the input sequence. The /// size of the array will be as large as the highest index returned /// by the <paramref name="indexSelector"/> plus 1. /// </returns> /// <remarks> /// This method forces immediate query evaluation. It should not be /// used on infinite sequences. If more than one element maps to the /// same index then the latter element overwrites the former in the /// resulting array. /// </remarks> public static T[] ToArrayByIndex<T>(this IEnumerable<T> source, Func<T, int> indexSelector) { return source.ToArrayByIndex(indexSelector, (e, _) => e); } /// <summary> /// Creates an array from an <see cref="IEnumerable{T}"/> where a /// function is used to determine the index at which an element will /// be placed in the array. The elements are projected into the array /// via an additional function. /// </summary> /// <param name="source">The source sequence for the array.</param> /// <param name="indexSelector"> /// A function that maps an element to its index.</param> /// <param name="resultSelector"> /// A function to project a source element into an element of the /// resulting array.</param> /// <typeparam name="T"> /// The type of the element in <paramref name="source"/>.</typeparam> /// <typeparam name="TResult"> /// The type of the element in the resulting array.</typeparam> /// <returns> /// An array that contains the projected elements from the input /// sequence. The size of the array will be as large as the highest /// index returned by the <paramref name="indexSelector"/> plus 1. /// </returns> /// <remarks> /// This method forces immediate query evaluation. It should not be /// used on infinite sequences. If more than one element maps to the /// same index then the latter element overwrites the former in the /// resulting array. /// </remarks> public static TResult[] ToArrayByIndex<T, TResult>(this IEnumerable<T> source, Func<T, int> indexSelector, Func<T, TResult> resultSelector) { if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return source.ToArrayByIndex(indexSelector, (e, _) => resultSelector(e)); } /// <summary> /// Creates an array from an <see cref="IEnumerable{T}"/> where a /// function is used to determine the index at which an element will /// be placed in the array. The elements are projected into the array /// via an additional function. /// </summary> /// <param name="source">The source sequence for the array.</param> /// <param name="indexSelector"> /// A function that maps an element to its index.</param> /// <param name="resultSelector"> /// A function to project a source element into an element of the /// resulting array.</param> /// <typeparam name="T"> /// The type of the element in <paramref name="source"/>.</typeparam> /// <typeparam name="TResult"> /// The type of the element in the resulting array.</typeparam> /// <returns> /// An array that contains the projected elements from the input /// sequence. The size of the array will be as large as the highest /// index returned by the <paramref name="indexSelector"/> plus 1. /// </returns> /// <remarks> /// This method forces immediate query evaluation. It should not be /// used on infinite sequences. If more than one element maps to the /// same index then the latter element overwrites the former in the /// resulting array. /// </remarks> public static TResult[] ToArrayByIndex<T, TResult>(this IEnumerable<T> source, Func<T, int> indexSelector, Func<T, int, TResult> resultSelector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (indexSelector == null) throw new ArgumentNullException(nameof(indexSelector)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); var lastIndex = -1; var indexed = (List<KeyValuePair<int, T>>?) null; List<KeyValuePair<int, T>> Indexed() => indexed ??= new List<KeyValuePair<int, T>>(); foreach (var e in source) { var i = indexSelector(e); if (i < 0) throw new IndexOutOfRangeException(); lastIndex = Math.Max(i, lastIndex); Indexed().Add(new KeyValuePair<int, T>(i, e)); } var length = lastIndex + 1; return length == 0 ? new TResult[0] : Indexed().ToArrayByIndex(length, e => e.Key, e => resultSelector(e.Value, e.Key)); } /// <summary> /// Creates an array of user-specified length from an /// <see cref="IEnumerable{T}"/> where a function is used to determine /// the index at which an element will be placed in the array. /// </summary> /// <param name="source">The source sequence for the array.</param> /// <param name="length">The (non-negative) length of the resulting array.</param> /// <param name="indexSelector"> /// A function that maps an element to its index.</param> /// <typeparam name="T"> /// The type of the element in <paramref name="source"/>.</typeparam> /// <returns> /// An array of size <paramref name="length"/> that contains the /// elements from the input sequence. /// </returns> /// <remarks> /// This method forces immediate query evaluation. It should not be /// used on infinite sequences. If more than one element maps to the /// same index then the latter element overwrites the former in the /// resulting array. /// </remarks> public static T[] ToArrayByIndex<T>(this IEnumerable<T> source, int length, Func<T, int> indexSelector) { return source.ToArrayByIndex(length, indexSelector, (e, _) => e); } /// <summary> /// Creates an array of user-specified length from an /// <see cref="IEnumerable{T}"/> where a function is used to determine /// the index at which an element will be placed in the array. The /// elements are projected into the array via an additional function. /// </summary> /// <param name="source">The source sequence for the array.</param> /// <param name="length">The (non-negative) length of the resulting array.</param> /// <param name="indexSelector"> /// A function that maps an element to its index.</param> /// <param name="resultSelector"> /// A function to project a source element into an element of the /// resulting array.</param> /// <typeparam name="T"> /// The type of the element in <paramref name="source"/>.</typeparam> /// <typeparam name="TResult"> /// The type of the element in the resulting array.</typeparam> /// <returns> /// An array of size <paramref name="length"/> that contains the /// projected elements from the input sequence. /// </returns> /// <remarks> /// This method forces immediate query evaluation. It should not be /// used on infinite sequences. If more than one element maps to the /// same index then the latter element overwrites the former in the /// resulting array. /// </remarks> public static TResult[] ToArrayByIndex<T, TResult>(this IEnumerable<T> source, int length, Func<T, int> indexSelector, Func<T, TResult> resultSelector) { if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return source.ToArrayByIndex(length, indexSelector, (e, _) => resultSelector(e)); } /// <summary> /// Creates an array of user-specified length from an /// <see cref="IEnumerable{T}"/> where a function is used to determine /// the index at which an element will be placed in the array. The /// elements are projected into the array via an additional function. /// </summary> /// <param name="source">The source sequence for the array.</param> /// <param name="length">The (non-negative) length of the resulting array.</param> /// <param name="indexSelector"> /// A function that maps an element to its index.</param> /// <param name="resultSelector"> /// A function to project a source element into an element of the /// resulting array.</param> /// <typeparam name="T"> /// The type of the element in <paramref name="source"/>.</typeparam> /// <typeparam name="TResult"> /// The type of the element in the resulting array.</typeparam> /// <returns> /// An array of size <paramref name="length"/> that contains the /// projected elements from the input sequence. /// </returns> /// <remarks> /// This method forces immediate query evaluation. It should not be /// used on infinite sequences. If more than one element maps to the /// same index then the latter element overwrites the former in the /// resulting array. /// </remarks> public static TResult[] ToArrayByIndex<T, TResult>(this IEnumerable<T> source, int length, Func<T, int> indexSelector, Func<T, int, TResult> resultSelector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); if (indexSelector == null) throw new ArgumentNullException(nameof(indexSelector)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); var array = new TResult[length]; foreach (var e in source) { var i = indexSelector(e); if (i < 0 || i > array.Length) throw new IndexOutOfRangeException(); array[i] = resultSelector(e, i); } return array; } } }
namespace CSharpChartExplorer { partial class FrmZoomScrollTrack2 { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmZoomScrollTrack2)); this.winChartViewer1 = new ChartDirector.WinChartViewer(); this.hScrollBar1 = new System.Windows.Forms.HScrollBar(); this.leftPanel = new System.Windows.Forms.Panel(); this.endDateCtrl = new System.Windows.Forms.DateTimePicker(); this.endDateLabel = new System.Windows.Forms.Label(); this.separatorLine = new System.Windows.Forms.Label(); this.pointerPB = new System.Windows.Forms.RadioButton(); this.zoomInPB = new System.Windows.Forms.RadioButton(); this.zoomOutPB = new System.Windows.Forms.RadioButton(); this.startDateCtrl = new System.Windows.Forms.DateTimePicker(); this.startDateLabel = new System.Windows.Forms.Label(); this.topLabel = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.winChartViewer1)).BeginInit(); this.leftPanel.SuspendLayout(); this.SuspendLayout(); // // winChartViewer1 // this.winChartViewer1.HotSpotCursor = System.Windows.Forms.Cursors.Hand; this.winChartViewer1.Location = new System.Drawing.Point(128, 32); this.winChartViewer1.Name = "winChartViewer1"; this.winChartViewer1.Size = new System.Drawing.Size(640, 350); this.winChartViewer1.TabIndex = 23; this.winChartViewer1.TabStop = false; this.winChartViewer1.ViewPortChanged += new ChartDirector.WinViewPortEventHandler(this.winChartViewer1_ViewPortChanged); this.winChartViewer1.MouseMovePlotArea += new System.Windows.Forms.MouseEventHandler(this.winChartViewer1_MouseMovePlotArea); // // hScrollBar1 // this.hScrollBar1.BackColor = System.Drawing.Color.White; this.hScrollBar1.Cursor = System.Windows.Forms.Cursors.Default; this.hScrollBar1.Dock = System.Windows.Forms.DockStyle.Bottom; this.hScrollBar1.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.hScrollBar1.Location = new System.Drawing.Point(120, 387); this.hScrollBar1.Maximum = 1000000000; this.hScrollBar1.Name = "hScrollBar1"; this.hScrollBar1.Size = new System.Drawing.Size(656, 16); this.hScrollBar1.TabIndex = 5; this.hScrollBar1.ValueChanged += new System.EventHandler(this.hScrollBar1_ValueChanged); // // leftPanel // this.leftPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255))))); this.leftPanel.Controls.Add(this.endDateCtrl); this.leftPanel.Controls.Add(this.endDateLabel); this.leftPanel.Controls.Add(this.separatorLine); this.leftPanel.Controls.Add(this.pointerPB); this.leftPanel.Controls.Add(this.zoomInPB); this.leftPanel.Controls.Add(this.zoomOutPB); this.leftPanel.Controls.Add(this.startDateCtrl); this.leftPanel.Controls.Add(this.startDateLabel); this.leftPanel.Dock = System.Windows.Forms.DockStyle.Left; this.leftPanel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.leftPanel.Location = new System.Drawing.Point(0, 24); this.leftPanel.Name = "leftPanel"; this.leftPanel.Size = new System.Drawing.Size(120, 379); this.leftPanel.TabIndex = 22; // // endDateCtrl // this.endDateCtrl.CustomFormat = ""; this.endDateCtrl.Format = System.Windows.Forms.DateTimePickerFormat.Short; this.endDateCtrl.Location = new System.Drawing.Point(4, 281); this.endDateCtrl.Name = "endDateCtrl"; this.endDateCtrl.Size = new System.Drawing.Size(112, 20); this.endDateCtrl.TabIndex = 4; this.endDateCtrl.Value = new System.DateTime(2000, 1, 1, 0, 0, 0, 0); this.endDateCtrl.ValueChanged += new System.EventHandler(this.endDateCtrl_ValueChanged); // // endDateLabel // this.endDateLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.endDateLabel.Location = new System.Drawing.Point(4, 265); this.endDateLabel.Name = "endDateLabel"; this.endDateLabel.Size = new System.Drawing.Size(72, 16); this.endDateLabel.TabIndex = 32; this.endDateLabel.Text = "End Date"; // // separatorLine // this.separatorLine.BackColor = System.Drawing.Color.Black; this.separatorLine.Dock = System.Windows.Forms.DockStyle.Right; this.separatorLine.Location = new System.Drawing.Point(119, 0); this.separatorLine.Name = "separatorLine"; this.separatorLine.Size = new System.Drawing.Size(1, 379); this.separatorLine.TabIndex = 31; // // pointerPB // this.pointerPB.Appearance = System.Windows.Forms.Appearance.Button; this.pointerPB.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.pointerPB.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.pointerPB.Image = ((System.Drawing.Image)(resources.GetObject("pointerPB.Image"))); this.pointerPB.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.pointerPB.Location = new System.Drawing.Point(0, 0); this.pointerPB.Name = "pointerPB"; this.pointerPB.Size = new System.Drawing.Size(120, 28); this.pointerPB.TabIndex = 0; this.pointerPB.Text = " Pointer"; this.pointerPB.CheckedChanged += new System.EventHandler(this.pointerPB_CheckedChanged); // // zoomInPB // this.zoomInPB.Appearance = System.Windows.Forms.Appearance.Button; this.zoomInPB.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.zoomInPB.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.zoomInPB.Image = ((System.Drawing.Image)(resources.GetObject("zoomInPB.Image"))); this.zoomInPB.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.zoomInPB.Location = new System.Drawing.Point(0, 27); this.zoomInPB.Name = "zoomInPB"; this.zoomInPB.Size = new System.Drawing.Size(120, 28); this.zoomInPB.TabIndex = 1; this.zoomInPB.Text = " Zoom In"; this.zoomInPB.CheckedChanged += new System.EventHandler(this.zoomInPB_CheckedChanged); // // zoomOutPB // this.zoomOutPB.Appearance = System.Windows.Forms.Appearance.Button; this.zoomOutPB.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.zoomOutPB.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.zoomOutPB.Image = ((System.Drawing.Image)(resources.GetObject("zoomOutPB.Image"))); this.zoomOutPB.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.zoomOutPB.Location = new System.Drawing.Point(0, 54); this.zoomOutPB.Name = "zoomOutPB"; this.zoomOutPB.Size = new System.Drawing.Size(120, 28); this.zoomOutPB.TabIndex = 2; this.zoomOutPB.Text = " Zoom Out"; this.zoomOutPB.CheckedChanged += new System.EventHandler(this.zoomOutPB_CheckedChanged); // // startDateCtrl // this.startDateCtrl.CustomFormat = ""; this.startDateCtrl.Format = System.Windows.Forms.DateTimePickerFormat.Short; this.startDateCtrl.Location = new System.Drawing.Point(4, 227); this.startDateCtrl.Name = "startDateCtrl"; this.startDateCtrl.Size = new System.Drawing.Size(112, 20); this.startDateCtrl.TabIndex = 3; this.startDateCtrl.Value = new System.DateTime(2000, 1, 1, 0, 0, 0, 0); this.startDateCtrl.ValueChanged += new System.EventHandler(this.startDateCtrl_ValueChanged); // // startDateLabel // this.startDateLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.startDateLabel.Location = new System.Drawing.Point(4, 211); this.startDateLabel.Name = "startDateLabel"; this.startDateLabel.Size = new System.Drawing.Size(72, 16); this.startDateLabel.TabIndex = 1; this.startDateLabel.Text = "Start Date"; // // topLabel // this.topLabel.BackColor = System.Drawing.Color.Navy; this.topLabel.Dock = System.Windows.Forms.DockStyle.Top; this.topLabel.Font = new System.Drawing.Font("Arial", 9.75F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.topLabel.ForeColor = System.Drawing.Color.Yellow; this.topLabel.Location = new System.Drawing.Point(0, 0); this.topLabel.Name = "topLabel"; this.topLabel.Size = new System.Drawing.Size(776, 24); this.topLabel.TabIndex = 21; this.topLabel.Text = "Advanced Software Engineering"; this.topLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // FrmZoomScrollTrack2 // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(776, 403); this.Controls.Add(this.winChartViewer1); this.Controls.Add(this.hScrollBar1); this.Controls.Add(this.leftPanel); this.Controls.Add(this.topLabel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.Name = "FrmZoomScrollTrack2"; this.Text = "Zooming and Scrolling with Track Line (2)"; this.Load += new System.EventHandler(this.FrmZoomScrollTrack2_Load); ((System.ComponentModel.ISupportInitialize)(this.winChartViewer1)).EndInit(); this.leftPanel.ResumeLayout(false); this.ResumeLayout(false); } #endregion private ChartDirector.WinChartViewer winChartViewer1; private System.Windows.Forms.HScrollBar hScrollBar1; private System.Windows.Forms.Panel leftPanel; private System.Windows.Forms.Label separatorLine; private System.Windows.Forms.RadioButton pointerPB; private System.Windows.Forms.RadioButton zoomInPB; private System.Windows.Forms.RadioButton zoomOutPB; private System.Windows.Forms.DateTimePicker startDateCtrl; private System.Windows.Forms.Label startDateLabel; private System.Windows.Forms.Label topLabel; private System.Windows.Forms.DateTimePicker endDateCtrl; private System.Windows.Forms.Label endDateLabel; } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime.Versioning; using NuGet.Resources; namespace NuGet { public class InstallWalker : PackageWalker, IPackageOperationResolver { private readonly bool _ignoreDependencies; private readonly bool _allowPrereleaseVersions; private readonly OperationLookup _operations; // This acts as a "retainment" queue. It contains packages that are already installed but need to be kept during // a package walk. This is to prevent those from being uninstalled in subsequent encounters. private readonly HashSet<IPackage> _packagesToKeep = new HashSet<IPackage>(PackageEqualityComparer.IdAndVersion); // this ctor is used for unit tests internal InstallWalker(IPackageRepository localRepository, IPackageRepository sourceRepository, ILogger logger, bool ignoreDependencies, bool allowPrereleaseVersions) : this(localRepository, sourceRepository, null, logger, ignoreDependencies, allowPrereleaseVersions) { } public InstallWalker(IPackageRepository localRepository, IPackageRepository sourceRepository, FrameworkName targetFramework, ILogger logger, bool ignoreDependencies, bool allowPrereleaseVersions) : this(localRepository, sourceRepository, constraintProvider: NullConstraintProvider.Instance, targetFramework: targetFramework, logger: logger, ignoreDependencies: ignoreDependencies, allowPrereleaseVersions: allowPrereleaseVersions) { } public InstallWalker(IPackageRepository localRepository, IPackageRepository sourceRepository, IPackageConstraintProvider constraintProvider, FrameworkName targetFramework, ILogger logger, bool ignoreDependencies, bool allowPrereleaseVersions) : base(targetFramework) { if (sourceRepository == null) { throw new ArgumentNullException("sourceRepository"); } if (localRepository == null) { throw new ArgumentNullException("localRepository"); } if (logger == null) { throw new ArgumentNullException("logger"); } Repository = localRepository; Logger = logger; SourceRepository = sourceRepository; _ignoreDependencies = ignoreDependencies; ConstraintProvider = constraintProvider; _operations = new OperationLookup(); _allowPrereleaseVersions = allowPrereleaseVersions; } internal bool DisableWalkInfo { get; set; } protected override bool IgnoreWalkInfo { get { return DisableWalkInfo ? true : base.IgnoreWalkInfo; } } protected ILogger Logger { get; private set; } protected IPackageRepository Repository { get; private set; } protected override bool IgnoreDependencies { get { return _ignoreDependencies; } } protected override bool AllowPrereleaseVersions { get { return _allowPrereleaseVersions; } } protected IPackageRepository SourceRepository { get; private set; } private IPackageConstraintProvider ConstraintProvider { get; set; } protected IList<PackageOperation> Operations { get { return _operations.ToList(); } } protected virtual ConflictResult GetConflict(IPackage package) { var conflictingPackage = Marker.FindPackage(package.Id); if (conflictingPackage != null) { return new ConflictResult(conflictingPackage, Marker, Marker); } return null; } protected override void OnBeforePackageWalk(IPackage package) { ConflictResult conflictResult = GetConflict(package); if (conflictResult == null) { return; } // If the conflicting package is the same as the package being installed // then no-op if (PackageEqualityComparer.IdAndVersion.Equals(package, conflictResult.Package)) { return; } // First we get a list of dependents for the installed package. // Then we find the dependency in the foreach dependent that this installed package used to satisfy. // We then check if the resolved package also meets that dependency and if it doesn't it's added to the list // i.e. A1 -> C >= 1 // B1 -> C >= 1 // C2 -> [] // Given the above graph, if we upgrade from C1 to C2, we need to see if A and B can work with the new C var incompatiblePackages = from dependentPackage in GetDependents(conflictResult) let dependency = dependentPackage.FindDependency(package.Id, TargetFramework) where dependency != null && !dependency.VersionSpec.Satisfies(package.Version) select dependentPackage; // If there were incompatible packages that we failed to update then we throw an exception if (incompatiblePackages.Any() && !TryUpdate(incompatiblePackages, conflictResult, package, out incompatiblePackages)) { throw CreatePackageConflictException(package, conflictResult.Package, incompatiblePackages); } else if (package.Version < conflictResult.Package.Version) { // REVIEW: Should we have a flag to allow downgrading? throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.NewerVersionAlreadyReferenced, package.Id)); } else if (package.Version > conflictResult.Package.Version) { Uninstall(conflictResult.Package, conflictResult.DependentsResolver, conflictResult.Repository); } } private void Uninstall(IPackage package, IDependentsResolver dependentsResolver, IPackageRepository repository) { // If we explicitly want to uninstall this package, then remove it from the retainment queue. _packagesToKeep.Remove(package); // If this package isn't part of the current graph (i.e. hasn't been visited yet) and // is marked for removal, then do nothing. This is so we don't get unnecessary duplicates. if (!Marker.Contains(package) && _operations.Contains(package, PackageAction.Uninstall)) { return; } // Uninstall the conflicting package. We set throw on conflicts to false since we've // already decided that there were no conflicts based on the above code. var resolver = new UninstallWalker(repository, dependentsResolver, TargetFramework, NullLogger.Instance, removeDependencies: !IgnoreDependencies, forceRemove: false) { ThrowOnConflicts = false }; foreach (var operation in resolver.ResolveOperations(package)) { // If the operation is Uninstall, we don't want to uninstall the package if it is in the "retainment" queue. if (operation.Action == PackageAction.Install || !_packagesToKeep.Contains(operation.Package)) { _operations.AddOperation(operation); } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We re-throw a more specific exception later on")] private bool TryUpdate(IEnumerable<IPackage> dependents, ConflictResult conflictResult, IPackage package, out IEnumerable<IPackage> incompatiblePackages) { // Key dependents by id so we can look up the old package later var dependentsLookup = dependents.ToDictionary(d => d.Id, StringComparer.OrdinalIgnoreCase); var compatiblePackages = new Dictionary<IPackage, IPackage>(); // Initialize each compatible package to null foreach (var dependent in dependents) { compatiblePackages[dependent] = null; } // Get compatible packages in one batch so we don't have to make requests for each one var packages = from p in SourceRepository.FindCompatiblePackages(ConstraintProvider, dependentsLookup.Keys, package, TargetFramework, AllowPrereleaseVersions) group p by p.Id into g let oldPackage = dependentsLookup[g.Key] select new { OldPackage = oldPackage, NewPackage = g.Where(p => p.Version > oldPackage.Version) .OrderBy(p => p.Version) .FirstOrDefault() }; foreach (var p in packages) { compatiblePackages[p.OldPackage] = p.NewPackage; } // Get all packages that have an incompatibility with the specified package i.e. // We couldn't find a version in the repository that works with the specified package. incompatiblePackages = compatiblePackages.Where(p => p.Value == null) .Select(p => p.Key); if (incompatiblePackages.Any()) { return false; } IPackageConstraintProvider currentConstraintProvider = ConstraintProvider; try { // Add a constraint for the incoming package so we don't try to update it by mistake. // Scenario: // A 1.0 -> B [1.0] // B 1.0.1, B 1.5, B 2.0 // A 2.0 -> B (any version) // We have A 1.0 and B 1.0 installed. When trying to update to B 1.0.1, we'll end up trying // to find a version of A that works with B 1.0.1. The version in the above case is A 2.0. // When we go to install A 2.0 we need to make sure that when we resolve it's dependencies that we stay within bounds // i.e. when we resolve B for A 2.0 we want to keep the B 1.0.1 we've already chosen instead of trying to grab // B 1.5 or B 2.0. In order to achieve this, we add a constraint for version of B 1.0.1 so we stay within those bounds for B. // Respect all existing constraints plus an additional one that we specify based on the incoming package var constraintProvider = new DefaultConstraintProvider(); constraintProvider.AddConstraint(package.Id, new VersionSpec(package.Version)); ConstraintProvider = new AggregateConstraintProvider(ConstraintProvider, constraintProvider); // Mark the incoming package as visited so that we don't try walking the graph again Marker.MarkVisited(package); var failedPackages = new List<IPackage>(); // Update each of the existing packages to more compatible one foreach (var pair in compatiblePackages) { try { // Remove the old package Uninstall(pair.Key, conflictResult.DependentsResolver, conflictResult.Repository); // Install the new package Walk(pair.Value); } catch { // If we failed to update this package (most likely because of a conflict further up the dependency chain) // we keep track of it so we can report an error about the top level package. failedPackages.Add(pair.Key); } } incompatiblePackages = failedPackages; return !incompatiblePackages.Any(); } finally { // Restore the current constraint provider ConstraintProvider = currentConstraintProvider; // Mark the package as processing again Marker.MarkProcessing(package); } } protected override void OnAfterPackageWalk(IPackage package) { if (!Repository.Exists(package)) { // Don't add the package for installation if it already exists in the repository _operations.AddOperation(new PackageOperation(package, PackageAction.Install)); } else { // If we already added an entry for removing this package then remove it // (it's equivalent for doing +P since we're removing a -P from the list) _operations.RemoveOperation(package, PackageAction.Uninstall); // and mark the package as being "retained". _packagesToKeep.Add(package); } } protected override IPackage ResolveDependency(PackageDependency dependency) { Logger.Log(MessageLevel.Info, NuGetResources.Log_AttemptingToRetrievePackageFromSource, dependency); // First try to get a local copy of the package // Bug1638: Include prereleases when resolving locally installed dependencies. IPackage package = Repository.ResolveDependency(dependency, ConstraintProvider, allowPrereleaseVersions: true, preferListedPackages: false); if (package != null) { return package; } // Next, query the source repo for the same dependency IPackage sourcePackage = SourceRepository.ResolveDependency(dependency, ConstraintProvider, AllowPrereleaseVersions, preferListedPackages: true); return sourcePackage; } protected override void OnDependencyResolveError(PackageDependency dependency) { IVersionSpec spec = ConstraintProvider.GetConstraint(dependency.Id); string message = String.Empty; if (spec != null) { message = String.Format(CultureInfo.CurrentCulture, NuGetResources.AdditonalConstraintsDefined, dependency.Id, VersionUtility.PrettyPrint(spec), ConstraintProvider.Source); } throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.UnableToResolveDependency + message, dependency)); } public IEnumerable<PackageOperation> ResolveOperations(IPackage package) { _operations.Clear(); Marker.Clear(); _packagesToKeep.Clear(); Walk(package); return Operations.Reduce(); } private IEnumerable<IPackage> GetDependents(ConflictResult conflict) { // Skip all dependents that are marked for uninstall IEnumerable<IPackage> packages = _operations.GetPackages(PackageAction.Uninstall); return conflict.DependentsResolver.GetDependents(conflict.Package) .Except<IPackage>(packages, PackageEqualityComparer.IdAndVersion); } private static InvalidOperationException CreatePackageConflictException(IPackage resolvedPackage, IPackage package, IEnumerable<IPackage> dependents) { if (dependents.Count() == 1) { return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ConflictErrorWithDependent, package.GetFullName(), resolvedPackage.GetFullName(), dependents.Single().Id)); } return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ConflictErrorWithDependents, package.GetFullName(), resolvedPackage.GetFullName(), String.Join(", ", dependents.Select(d => d.Id)))); } /// <summary> /// Operation lookup encapsulates an operation list and another efficient data structure for finding package operations /// by package id, version and PackageAction. /// </summary> private class OperationLookup { private readonly List<PackageOperation> _operations = new List<PackageOperation>(); private readonly Dictionary<PackageAction, Dictionary<IPackage, PackageOperation>> _operationLookup = new Dictionary<PackageAction, Dictionary<IPackage, PackageOperation>>(); internal void Clear() { _operations.Clear(); _operationLookup.Clear(); } internal IList<PackageOperation> ToList() { return _operations; } internal IEnumerable<IPackage> GetPackages(PackageAction action) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action); if (dictionary != null) { return dictionary.Keys; } return Enumerable.Empty<IPackage>(); } internal void AddOperation(PackageOperation operation) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(operation.Action, createIfNotExists: true); if (!dictionary.ContainsKey(operation.Package)) { dictionary.Add(operation.Package, operation); _operations.Add(operation); } } internal void RemoveOperation(IPackage package, PackageAction action) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action); PackageOperation operation; if (dictionary != null && dictionary.TryGetValue(package, out operation)) { dictionary.Remove(package); _operations.Remove(operation); } } internal bool Contains(IPackage package, PackageAction action) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action); return dictionary != null && dictionary.ContainsKey(package); } private Dictionary<IPackage, PackageOperation> GetPackageLookup(PackageAction action, bool createIfNotExists = false) { Dictionary<IPackage, PackageOperation> packages; if (!_operationLookup.TryGetValue(action, out packages) && createIfNotExists) { packages = new Dictionary<IPackage, PackageOperation>(PackageEqualityComparer.IdAndVersion); _operationLookup.Add(action, packages); } return packages; } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type ContactFolderContactsCollectionRequest. /// </summary> public partial class ContactFolderContactsCollectionRequest : BaseRequest, IContactFolderContactsCollectionRequest { /// <summary> /// Constructs a new ContactFolderContactsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public ContactFolderContactsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Contact to the collection via POST. /// </summary> /// <param name="contact">The Contact to add.</param> /// <returns>The created Contact.</returns> public System.Threading.Tasks.Task<Contact> AddAsync(Contact contact) { return this.AddAsync(contact, CancellationToken.None); } /// <summary> /// Adds the specified Contact to the collection via POST. /// </summary> /// <param name="contact">The Contact to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Contact.</returns> public System.Threading.Tasks.Task<Contact> AddAsync(Contact contact, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Contact>(contact, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IContactFolderContactsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IContactFolderContactsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<ContactFolderContactsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Expand(Expression<Func<Contact, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Select(Expression<Func<Contact, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.38.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Accelerated Mobile Pages (AMP) URL API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/amp/cache/'>Accelerated Mobile Pages (AMP) URL API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20190205 (1496) * <tr><th>API Docs * <td><a href='https://developers.google.com/amp/cache/'> * https://developers.google.com/amp/cache/</a> * <tr><th>Discovery Name<td>acceleratedmobilepageurl * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Accelerated Mobile Pages (AMP) URL API can be found at * <a href='https://developers.google.com/amp/cache/'>https://developers.google.com/amp/cache/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Acceleratedmobilepageurl.v1 { /// <summary>The Acceleratedmobilepageurl Service.</summary> public class AcceleratedmobilepageurlService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public AcceleratedmobilepageurlService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public AcceleratedmobilepageurlService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { ampUrls = new AmpUrlsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "acceleratedmobilepageurl"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://acceleratedmobilepageurl.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://acceleratedmobilepageurl.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif private readonly AmpUrlsResource ampUrls; /// <summary>Gets the AmpUrls resource.</summary> public virtual AmpUrlsResource AmpUrls { get { return ampUrls; } } } ///<summary>A base abstract class for Acceleratedmobilepageurl requests.</summary> public abstract class AcceleratedmobilepageurlBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new AcceleratedmobilepageurlBaseServiceRequest instance.</summary> protected AcceleratedmobilepageurlBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Acceleratedmobilepageurl parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "ampUrls" collection of methods.</summary> public class AmpUrlsResource { private const string Resource = "ampUrls"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public AmpUrlsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Returns AMP URL(s) and equivalent [AMP Cache URL(s)](/amp/cache/overview#amp-cache-url- /// format).</summary> /// <param name="body">The body of the request.</param> public virtual BatchGetRequest BatchGet(Google.Apis.Acceleratedmobilepageurl.v1.Data.BatchGetAmpUrlsRequest body) { return new BatchGetRequest(service, body); } /// <summary>Returns AMP URL(s) and equivalent [AMP Cache URL(s)](/amp/cache/overview#amp-cache-url- /// format).</summary> public class BatchGetRequest : AcceleratedmobilepageurlBaseServiceRequest<Google.Apis.Acceleratedmobilepageurl.v1.Data.BatchGetAmpUrlsResponse> { /// <summary>Constructs a new BatchGet request.</summary> public BatchGetRequest(Google.Apis.Services.IClientService service, Google.Apis.Acceleratedmobilepageurl.v1.Data.BatchGetAmpUrlsRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Acceleratedmobilepageurl.v1.Data.BatchGetAmpUrlsRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "batchGet"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/ampUrls:batchGet"; } } /// <summary>Initializes BatchGet parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.Acceleratedmobilepageurl.v1.Data { /// <summary>AMP URL response for a requested URL.</summary> public class AmpUrl : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The AMP URL pointing to the publisher's web server.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ampUrl")] public virtual string AmpUrlValue { get; set; } /// <summary>The [AMP Cache URL](/amp/cache/overview#amp-cache-url-format) pointing to the cached document in /// the Google AMP Cache.</summary> [Newtonsoft.Json.JsonPropertyAttribute("cdnAmpUrl")] public virtual string CdnAmpUrl { get; set; } /// <summary>The original non-AMP URL.</summary> [Newtonsoft.Json.JsonPropertyAttribute("originalUrl")] public virtual string OriginalUrl { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>AMP URL Error resource for a requested URL that couldn't be found.</summary> public class AmpUrlError : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The error code of an API call.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorCode")] public virtual string ErrorCode { get; set; } /// <summary>An optional descriptive error message.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorMessage")] public virtual string ErrorMessage { get; set; } /// <summary>The original non-AMP URL.</summary> [Newtonsoft.Json.JsonPropertyAttribute("originalUrl")] public virtual string OriginalUrl { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>AMP URL request for a batch of URLs.</summary> public class BatchGetAmpUrlsRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The lookup_strategy being requested.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lookupStrategy")] public virtual string LookupStrategy { get; set; } /// <summary>List of URLs to look up for the paired AMP URLs. The URLs are case-sensitive. Up to 50 URLs per /// lookup (see [Usage Limits](/amp/cache/reference/limits)).</summary> [Newtonsoft.Json.JsonPropertyAttribute("urls")] public virtual System.Collections.Generic.IList<string> Urls { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Batch AMP URL response.</summary> public class BatchGetAmpUrlsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>For each URL in BatchAmpUrlsRequest, the URL response. The response might not be in the same order /// as URLs in the batch request. If BatchAmpUrlsRequest contains duplicate URLs, AmpUrl is generated only /// once.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ampUrls")] public virtual System.Collections.Generic.IList<AmpUrl> AmpUrls { get; set; } /// <summary>The errors for requested URLs that have no AMP URL.</summary> [Newtonsoft.Json.JsonPropertyAttribute("urlErrors")] public virtual System.Collections.Generic.IList<AmpUrlError> UrlErrors { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
/* 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache 2 License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Reflection; using MileageStats.Domain.Contracts.Data; using MileageStats.Domain.Models; namespace MileageStats.Data.InMemory { public class PopulateSampleData { private readonly int[] _distance = new[] {350, 310, 360, 220, 310, 360, 350, 340, 375, 410, 270, 330}; private readonly Double[] _fee = new[] {.45, 0, .50, 0, 0, 0, .30, .45, .50, 0, .45, 0}; private readonly Double[] _price = new[] {3.5, 3.75, 3.75, 3.65, 3.45, 3.75, 3.75, 3.70, 3.5, 3.65, 3.70, 3.35}; private readonly Double[] _units = new[] {17, 14, 16, 12, 17, 18, 16.5, 17, 17, 19, 14, 17}; private readonly IUserRepository _users; private readonly IReminderRepository _reminders; private readonly IFillupRepository _fillups; private readonly IVehicleRepository _vehicles; private readonly IVehiclePhotoRepository _photos; private readonly String[] _vendor = new[] { "Fabrikam", "Contoso", "Margie's Travel", "Adventure Works", "Fabrikam" , "Contoso", "Margie's Travel", "Adventure Works", "Fabrikam", "Contoso", "Margie's Travel", "Adventure Works" }; public PopulateSampleData(IVehicleRepository vehicles, IVehiclePhotoRepository photos, IUserRepository users, IReminderRepository reminders, IFillupRepository fillups) { _vehicles = vehicles; _photos = photos; _users = users; _reminders = reminders; _fillups = fillups; } public void Seed(int? userId) { if(!userId.HasValue) { var user = new User { AuthorizationId = "http://not/a/real/openid/url", DisplayName = "Sample User", Country = "United States" }; _users.Create(user); userId = user.UserId; } SeedVehicles(userId.Value); } private void SeedVehicles(int userId) { var cars = new[] { new Vehicle { UserId = userId, Name = "Hot Rod", SortOrder = 1, Year = 2003, MakeName = "BMW", ModelName = "330xi" }, new Vehicle { UserId = userId, Name = "Soccer Mom's Ride", SortOrder = 2, Year = 1997, MakeName = "Honda", ModelName = "Accord LX" }, new Vehicle { UserId = userId, Name = "Mud Lover", SortOrder = 3, Year = 2011, MakeName = "Jeep", ModelName = "Wrangler" } }; var now = DateTime.Now; var fillupdata = new[] { new FillupData {Mileage = 1000, Units = 1, Distance = 1, Date = now.AddDays(-365)}, new FillupData {Mileage = 500, Units = 0.9, Distance = 1.2, Date = now.AddDays(-370)}, new FillupData {Mileage = 750, Units = 1.2, Distance = 0.8, Date = now.AddDays(-373)}, }; cars .Select((car, index) => { CreateVehicle(userId, car); CreateFillups(car, fillupdata[index]); CreateReminders(car); return car; }) .ToList(); // ToList to force execution } private VehiclePhoto CreateVehiclePhoto(Image image, int vehicleId) { byte[] buffer; using (var memoryStream = new MemoryStream()) { image.Save(memoryStream, new ImageFormat(image.RawFormat.Guid)); buffer = memoryStream.ToArray(); } var vehiclePhoto = new VehiclePhoto {ImageMimeType = "image/jpeg", Image = buffer, VehicleId = vehicleId}; _photos.Create(vehicleId, vehiclePhoto); return vehiclePhoto; } private void CreateVehicle(int userId, Vehicle vehicle) { _vehicles.Create(userId, vehicle); string photoId = string.Format("MileageStats.Data.InMemory.Photos.{0}.jpg", vehicle.MakeName); var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(photoId); vehicle.Photo = CreateVehiclePhoto(Image.FromStream(stream), vehicle.VehicleId); vehicle.PhotoId = vehicle.Photo.VehiclePhotoId; } private void CreateReminders(Vehicle vehicle) { var lastFillup = _fillups.GetFillups(vehicle.VehicleId).OrderByDescending(f => f.Date).FirstOrDefault(); if (lastFillup == null) { return; } // create "overdue by mileage" reminder vehicle.Reminders.Add(new Reminder { DueDate = null, DueDistance = lastFillup.Odometer - 10, IsFulfilled = false, Remarks = "Check air filter when oil is changed", Title = "Oil Change", VehicleId = vehicle.VehicleId }); // create "overdue by date" reminder vehicle.Reminders.Add(new Reminder { DueDate = lastFillup.Date.AddDays(-10), DueDistance = null, IsFulfilled = false, Remarks = "Check condition of the wipers", Title = "Check Wiper Fluid", VehicleId = vehicle.VehicleId }); // create "to be done soon by mileage" reminder vehicle.Reminders.Add(new Reminder { DueDate = null, DueDistance = lastFillup.Odometer + 400, IsFulfilled = false, Remarks = "Check air pressure", Title = "Rotate Tires", VehicleId = vehicle.VehicleId }); // create "to be done soon by date" reminder vehicle.Reminders.Add(new Reminder { DueDate = DateTime.Now.AddDays(+10), DueDistance = null, IsFulfilled = false, Remarks = "Check air freshener", Title = "Vacuum Car", VehicleId = vehicle.VehicleId }); vehicle.Reminders.ToList() .ForEach(reminder => _reminders.Create(vehicle.VehicleId,reminder)); } private void CreateFillups(Vehicle vehicle, FillupData data) { int odometer = data.Mileage; DateTime date = data.Date; Double unitsModifier = data.Units; Double distanceModifier = data.Distance; int[] randomArray = RandomizeArray(new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}); int currentIndex = 0; var random = new Random(); bool isFirst = true; while (date < DateTime.Now) { int dataIndex = randomArray[currentIndex]; var distance = (int) (_distance[dataIndex]*distanceModifier); var fillup = new FillupEntry { Date = date, Odometer = odometer, PricePerUnit = _price[dataIndex], TotalUnits = _units[dataIndex]*unitsModifier, TransactionFee = _fee[dataIndex], VehicleId = vehicle.VehicleId, Vendor = _vendor[dataIndex] }; if (isFirst) { isFirst = false; fillup.Distance = null; } else { fillup.Distance = distance; } odometer += distance; currentIndex += 1; if (currentIndex > 11) { currentIndex = 0; } date = date.AddDays(random.Next(3, 14)); _fillups.Create(vehicle.UserId, vehicle.VehicleId, fillup); } } private int[] RandomizeArray(int[] array) { var random = new Random(); for (int i = array.Length - 1; i > 0; i--) { int swapPosition = random.Next(i + 1); int temp = array[i]; array[i] = array[swapPosition]; array[swapPosition] = temp; } return array; } #region Nested type: FillupData private struct FillupData { public DateTime Date; public double Distance; public int Mileage; public double Units; } #endregion } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace Star { class Sprite { private Texture2D texture; private Vector2 position; private Vector2 size; private Vector2 screenSize; private Vector2 velocity; private Vector2 previousPosition; private Random random = new Random(); private Boolean isRandomMovement = false; public Texture2D Texture { get { return this.texture; } } public Vector2 Position { get { return this.position; } set { this.position = value; } } public Vector2 Size { get { return this.size; } set { this.size = value; } } public Vector2 Velocity { get { return this.velocity; } set { this.velocity = value; } } /* public Vector2 NAME { get { return this.var; } set { this.var = value;} } */ //HIER PROPERTIES EINFUEGEN //SOUNDS EINFUEGEN public Sprite(Texture2D aTexture, Vector2 aPostion, Vector2 aSize, Vector2 aScreenSize) { this.velocity = new Vector2(0L, 0L); this.texture = aTexture; this.position = aPostion; this.previousPosition = aPostion; this.size = aSize; this.screenSize = aScreenSize; } public Boolean CollidesWith(Sprite other) { return (this.position.X + this.size.X > other.position.X // rechte kante von this ist rechts von others linker kante && this.position.X < other.position.X + other.size.X // dieses Sprite ist nicht voellig rechts von other && this.position.Y + this.size.Y > other.position.Y // untere kante ist unterhalb oberer kante von other && this.position.Y < other.position.Y + other.size.Y); // dieses Sprite ist nicht voellig unterhalb von other } public void MoveBack() { this.position = this.previousPosition; } private Vector2 DetermineVelocity() { Vector2 result = this.velocity; if (GamePad.GetState(PlayerIndex.One).IsConnected) { result.X = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X * 5; result.Y = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.Y * -5; } else { KeyboardState state = Keyboard.GetState(); if (state.IsKeyDown(Keys.Up)) { // if (this.velocity > 0) // { // abwaerts, bremsen also...logarithmisch // wie? // } result.Y -= 5; } else if (state.IsKeyDown(Keys.Down)) { // if (this.velocity < 0) // { // aufwaerts, bremsen also...logarithmisch // wie? // } result.Y += 5; } else if (state.IsKeyDown(Keys.Right)) { result.X += 10; } else if (state.IsKeyDown(Keys.Left)) { result.X -= 10; } } return result; } public void RandomMovement() { this.isRandomMovement = true; if (this.velocity == Vector2.Zero) { this.velocity = new Vector2(this.random.Next(1000) % 11 - 5, this.random.Next(1000) % 11 - 5); } DoMove(); } private void DoMove() { this.previousPosition = this.position; this.position += this.velocity; if ((this.screenSize.Y < this.position.Y + this.size.Y) || (0 > this.position.Y)) { this.position.Y = 0 > this.position.Y ? 0 : this.screenSize.Y - this.size.Y; this.velocity.Y *= -1; if (this.isRandomMovement) { this.velocity = new Vector2(this.random.Next(1000) % 40 - 20, this.random.Next(1000) % 40 - 20); if (this.velocity.X == 0) this.velocity.X = 10; if (this.velocity.Y == 0) this.velocity.Y = 10; } } if ((this.screenSize.X < this.position.X + this.size.X) || (0 > this.position.X)) { this.position.X = 0 > this.position.X ? 0 : this.screenSize.X - this.size.X; this.velocity.X *= -1; if (this.isRandomMovement) { this.velocity = new Vector2(this.random.Next(1000) % 11 - 5, this.random.Next(1000) % 11 - 5); if (this.velocity.X == 0) this.velocity.X = 10; if (this.velocity.Y == 0) this.velocity.Y = 10; } } } public void Move() { this.velocity = DetermineVelocity(); DoMove(); } } }
using System; using System.Data.Common; using System.Linq; using System.Threading; using System.Threading.Tasks; using Baseline; using Marten.Events.Archiving; using Marten.Events.Schema; using Marten.Exceptions; using Marten.Internal; using Marten.Internal.Operations; using Marten.Linq; using Marten.Linq.Fields; using Marten.Linq.Filters; using Marten.Linq.Parsing; using Marten.Linq.QueryHandlers; using Marten.Linq.Selectors; using Marten.Linq.SqlGeneration; using Weasel.Postgresql; using Marten.Schema; using Marten.Services; using Marten.Storage; using Remotion.Linq; using Weasel.Core; using Weasel.Postgresql.SqlGeneration; namespace Marten.Events { // NOTE!!!! This type has to remain public for the code generation to work /// <summary> /// Base type for the IEventStorage type that provides all the read/write operation /// mapping for the event store in a running system. The actual implementation of this /// base type is generated and compiled at runtime by Marten /// </summary> public abstract class EventDocumentStorage : IEventStorage { private readonly EventQueryMapping _mapping; private readonly ISerializer _serializer; private readonly string[] _fields; private readonly string _selectClause; private readonly ISqlFragment _defaultWhere; public EventDocumentStorage(StoreOptions options) { Events = options.EventGraph; _mapping = new EventQueryMapping(options); FromObject = _mapping.TableName.QualifiedName; Fields = _mapping; _serializer = options.Serializer(); IdType = Events.StreamIdentity == StreamIdentity.AsGuid ? typeof(Guid) : typeof(string); TenancyStyle = options.Events.TenancyStyle; // The json data column has to go first var table = new EventsTable(Events); var columns = table.SelectColumns(); _fields = columns.Select(x => x.Name).ToArray(); _selectClause = $"select {_fields.Join(", ")} from {Events.DatabaseSchemaName}.mt_events as d"; _defaultWhere = Events.TenancyStyle == TenancyStyle.Conjoined ? CompoundWhereFragment.And(IsNotArchivedFilter.Instance, CurrentTenantFilter.Instance) : IsNotArchivedFilter.Instance; } public void TruncateDocumentStorage(ITenant tenant) { tenant.RunSql($"truncate table {Events.DatabaseSchemaName}.mt_streams cascade"); } public Task TruncateDocumentStorageAsync(ITenant tenant) { return tenant.RunSqlAsync($"truncate table {Events.DatabaseSchemaName}.mt_streams cascade"); } public EventGraph Events { get; } public TenancyStyle TenancyStyle { get; } public IDeletion DeleteForDocument(IEvent document, ITenant tenant) { throw new NotSupportedException(); } public void EjectById(IMartenSession session, object id) { // Nothing } public void RemoveDirtyTracker(IMartenSession session, object id) { // Nothing } public IDeletion HardDeleteForDocument(IEvent document, ITenant tenant) { throw new NotSupportedException(); } public string FromObject { get; } public Type SelectedType => typeof(IEvent); public void WriteSelectClause(CommandBuilder sql) { sql.Append(_selectClause); } public string[] SelectFields() { return _fields; } public ISelector BuildSelector(IMartenSession session) { return this; } public IQueryHandler<T> BuildHandler<T>(IMartenSession session, Statement topStatement, Statement currentStatement) { return LinqHandlerBuilder.BuildHandler<IEvent, T>(this, topStatement); } public ISelectClause UseStatistics(QueryStatistics statistics) { throw new NotSupportedException(); } public Type SourceType => typeof(IEvent); public IFieldMapping Fields { get; } public ISqlFragment FilterDocuments(QueryModel model, ISqlFragment query) { var shouldBeTenanted = Events.TenancyStyle == TenancyStyle.Conjoined && !query.SpecifiesTenant(); if (shouldBeTenanted) { query = query.CombineAnd(CurrentTenantFilter.Instance); } return query.SpecifiesEventArchivalStatus() ? query : query.CombineAnd(IsNotArchivedFilter.Instance); } public ISqlFragment DefaultWhereFragment() { return _defaultWhere; } public bool UseOptimisticConcurrency { get; } = false; public IOperationFragment DeleteFragment => throw new NotSupportedException(); public IOperationFragment HardDeleteFragment { get; } public DuplicatedField[] DuplicatedFields { get; } = new DuplicatedField[0]; public DbObjectName TableName => _mapping.TableName; public Type DocumentType => typeof(IEvent); public object IdentityFor(IEvent document) { return Events.StreamIdentity == StreamIdentity.AsGuid ? (object) document.Id : document.StreamKey; } public Type IdType { get; } public Guid? VersionFor(IEvent document, IMartenSession session) { return null; } public void Store(IMartenSession session, IEvent document) { // Nothing } public void Store(IMartenSession session, IEvent document, Guid? version) { // Nothing } public void Eject(IMartenSession session, IEvent document) { // Nothing } public IStorageOperation Update(IEvent document, IMartenSession session, ITenant tenant) { throw new NotSupportedException(); } public IStorageOperation Insert(IEvent document, IMartenSession session, ITenant tenant) { throw new NotSupportedException(); } public IStorageOperation Upsert(IEvent document, IMartenSession session, ITenant tenant) { throw new NotSupportedException(); } public IStorageOperation Overwrite(IEvent document, IMartenSession session, ITenant tenant) { throw new NotSupportedException(); } public abstract IStorageOperation AppendEvent(EventGraph events, IMartenSession session, StreamAction stream, IEvent e); public abstract IStorageOperation InsertStream(StreamAction stream); public abstract IQueryHandler<StreamState> QueryForStream(StreamAction stream); public abstract IStorageOperation UpdateStreamVersion(StreamAction stream); public IEvent Resolve(DbDataReader reader) { var eventTypeName = reader.GetString(1); var mapping = Events.EventMappingFor(eventTypeName); if (mapping == null) { var dotnetTypeName = reader.GetFieldValue<string>(2); if (dotnetTypeName.IsEmpty()) { throw new UnknownEventTypeException(eventTypeName); } var type = Events.TypeForDotNetName(dotnetTypeName); mapping = Events.EventMappingFor(type); } var data = _serializer.FromJson(mapping.DocumentType, reader, 0).As<object>(); var @event = mapping.Wrap(data); ApplyReaderDataToEvent(reader, @event); return @event; } public abstract void ApplyReaderDataToEvent(DbDataReader reader, IEvent e); public async Task<IEvent> ResolveAsync(DbDataReader reader, CancellationToken token) { var eventTypeName = await reader.GetFieldValueAsync<string>(1, token).ConfigureAwait(false); var mapping = Events.EventMappingFor(eventTypeName); if (mapping == null) { var dotnetTypeName = await reader.GetFieldValueAsync<string>(2, token).ConfigureAwait(false); if (dotnetTypeName.IsEmpty()) { throw new UnknownEventTypeException(eventTypeName); } Type type; try { type = Events.TypeForDotNetName(dotnetTypeName); } catch (ArgumentNullException) { throw new UnknownEventTypeException(dotnetTypeName); } mapping = Events.EventMappingFor(type); } var data = await _serializer.FromJsonAsync(mapping.DocumentType, reader, 0, token).ConfigureAwait(false); var @event = mapping.Wrap(data); await ApplyReaderDataToEventAsync(reader, @event, token).ConfigureAwait(false); return @event; } public abstract Task ApplyReaderDataToEventAsync(DbDataReader reader, IEvent e, CancellationToken token); } }
/* * 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.Net; using System.Collections.Generic; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Physics.Manager; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.CoreModules.Agent.Capabilities; using OpenSim.Region.CoreModules.Avatar.Gods; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Authentication; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid; using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common.Mock; namespace OpenSim.Tests.Common.Setup { /// <summary> /// Helpers for setting up scenes. /// </summary> public class SceneSetupHelpers { // These static variables in order to allow regions to be linked by shared modules and same // CommunicationsManager. private static ISharedRegionModule m_assetService = null; // private static ISharedRegionModule m_authenticationService = null; private static ISharedRegionModule m_inventoryService = null; private static ISharedRegionModule m_gridService = null; private static ISharedRegionModule m_userAccountService = null; private static ISharedRegionModule m_presenceService = null; /// <summary> /// Set up a test scene /// </summary> /// /// Automatically starts service threads, as would the normal runtime. /// /// <returns></returns> public static TestScene SetupScene() { return SetupScene(""); } /// <summary> /// Set up a test scene /// </summary> /// /// <param name="realServices">Starts real inventory and asset services, as opposed to mock ones, if true</param> /// <returns></returns> public static TestScene SetupScene(String realServices) { return SetupScene( "Unit test region", UUID.Random(), 1000, 1000, realServices); } // REFACTORING PROBLEM. No idea what the difference is with the previous one ///// <summary> ///// Set up a test scene ///// </summary> ///// ///// <param name="realServices">Starts real inventory and asset services, as opposed to mock ones, if true</param> ///// <param name="cm">This should be the same if simulating two scenes within a standalone</param> ///// <returns></returns> //public static TestScene SetupScene(String realServices) //{ // return SetupScene( // "Unit test region", UUID.Random(), 1000, 1000, ""); //} /// <summary> /// Set up a test scene /// </summary> /// <param name="name">Name of the region</param> /// <param name="id">ID of the region</param> /// <param name="x">X co-ordinate of the region</param> /// <param name="y">Y co-ordinate of the region</param> /// <param name="cm">This should be the same if simulating two scenes within a standalone</param> /// <returns></returns> public static TestScene SetupScene(string name, UUID id, uint x, uint y) { return SetupScene(name, id, x, y,""); } /// <summary> /// Set up a scene. If it's more then one scene, use the same CommunicationsManager to link regions /// or a different, to get a brand new scene with new shared region modules. /// </summary> /// <param name="name">Name of the region</param> /// <param name="id">ID of the region</param> /// <param name="x">X co-ordinate of the region</param> /// <param name="y">Y co-ordinate of the region</param> /// <param name="cm">This should be the same if simulating two scenes within a standalone</param> /// <param name="realServices">Starts real inventory and asset services, as opposed to mock ones, if true</param> /// <returns></returns> public static TestScene SetupScene( string name, UUID id, uint x, uint y, String realServices) { bool newScene = false; Console.WriteLine("Setting up test scene {0}", name); // REFACTORING PROBLEM! //// If cm is the same as our last commsManager used, this means the tester wants to link //// regions. In this case, don't use the sameshared region modules and dont initialize them again. //// Also, no need to start another MainServer and MainConsole instance. //if (cm == null || cm != commsManager) //{ // System.Console.WriteLine("Starting a brand new scene"); // newScene = true; MainConsole.Instance = new MockConsole("TEST PROMPT"); // MainServer.Instance = new BaseHttpServer(980); // commsManager = cm; //} // We must set up a console otherwise setup of some modules may fail RegionInfo regInfo = new RegionInfo(x, y, new IPEndPoint(IPAddress.Loopback, 9000), "127.0.0.1"); regInfo.RegionName = name; regInfo.RegionID = id; AgentCircuitManager acm = new AgentCircuitManager(); SceneCommunicationService scs = new SceneCommunicationService(); ISimulationDataService simDataService = OpenSim.Server.Base.ServerUtils.LoadPlugin<ISimulationDataService>("OpenSim.Tests.Common.dll", null); IEstateDataService estateDataService = null; IConfigSource configSource = new IniConfigSource(); TestScene testScene = new TestScene( regInfo, acm, scs, simDataService, estateDataService, null, false, false, false, configSource, null); INonSharedRegionModule capsModule = new CapabilitiesModule(); capsModule.Initialise(new IniConfigSource()); testScene.AddRegionModule(capsModule.Name, capsModule); capsModule.AddRegion(testScene); IRegionModule godsModule = new GodsModule(); godsModule.Initialise(testScene, new IniConfigSource()); testScene.AddModule(godsModule.Name, godsModule); realServices = realServices.ToLower(); // IConfigSource config = new IniConfigSource(); // If we have a brand new scene, need to initialize shared region modules if ((m_assetService == null && m_inventoryService == null) || newScene) { if (realServices.Contains("asset")) StartAssetService(testScene, true); else StartAssetService(testScene, false); // For now, always started a 'real' authentication service StartAuthenticationService(testScene, true); if (realServices.Contains("inventory")) StartInventoryService(testScene, true); else StartInventoryService(testScene, false); StartGridService(testScene, true); StartUserAccountService(testScene); StartPresenceService(testScene); } // If not, make sure the shared module gets references to this new scene else { m_assetService.AddRegion(testScene); m_assetService.RegionLoaded(testScene); m_inventoryService.AddRegion(testScene); m_inventoryService.RegionLoaded(testScene); m_userAccountService.AddRegion(testScene); m_userAccountService.RegionLoaded(testScene); m_presenceService.AddRegion(testScene); m_presenceService.RegionLoaded(testScene); } m_inventoryService.PostInitialise(); m_assetService.PostInitialise(); m_userAccountService.PostInitialise(); m_presenceService.PostInitialise(); testScene.RegionInfo.EstateSettings.EstateOwner = UUID.Random(); testScene.SetModuleInterfaces(); testScene.LandChannel = new TestLandChannel(testScene); testScene.LoadWorldMap(); PhysicsPluginManager physicsPluginManager = new PhysicsPluginManager(); physicsPluginManager.LoadPluginsFromAssembly("Physics/OpenSim.Region.Physics.BasicPhysicsPlugin.dll"); testScene.PhysicsScene = physicsPluginManager.GetPhysicsScene("basicphysics", "MarchingCubes", "ZeroMesher", new IniConfigSource(), "test"); // It's really not a good idea to use static variables as they carry over between tests, leading to // problems that are extremely hard to debug. Really, these static fields need to be eliminated - // tests using multiple regions that need to share modules need to find another solution. m_assetService = null; m_inventoryService = null; m_gridService = null; m_userAccountService = null; m_presenceService = null; testScene.RegionInfo.EstateSettings = new EstateSettings(); testScene.LoginsDisabled = false; return testScene; } private static void StartAssetService(Scene testScene, bool real) { ISharedRegionModule assetService = new LocalAssetServicesConnector(); IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("AssetService"); config.Configs["Modules"].Set("AssetServices", "LocalAssetServicesConnector"); if (real) config.Configs["AssetService"].Set("LocalServiceModule", "OpenSim.Services.AssetService.dll:AssetService"); else config.Configs["AssetService"].Set("LocalServiceModule", "OpenSim.Tests.Common.dll:MockAssetService"); config.Configs["AssetService"].Set("StorageProvider", "OpenSim.Tests.Common.dll"); assetService.Initialise(config); assetService.AddRegion(testScene); assetService.RegionLoaded(testScene); testScene.AddRegionModule(assetService.Name, assetService); m_assetService = assetService; } private static void StartAuthenticationService(Scene testScene, bool real) { ISharedRegionModule service = new LocalAuthenticationServicesConnector(); IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("AuthenticationService"); config.Configs["Modules"].Set("AuthenticationServices", "LocalAuthenticationServicesConnector"); if (real) config.Configs["AuthenticationService"].Set( "LocalServiceModule", "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService"); else config.Configs["AuthenticationService"].Set( "LocalServiceModule", "OpenSim.Tests.Common.dll:MockAuthenticationService"); config.Configs["AuthenticationService"].Set("StorageProvider", "OpenSim.Data.Null.dll"); service.Initialise(config); service.AddRegion(testScene); service.RegionLoaded(testScene); testScene.AddRegionModule(service.Name, service); //m_authenticationService = service; } private static void StartInventoryService(Scene testScene, bool real) { ISharedRegionModule inventoryService = new LocalInventoryServicesConnector(); IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("InventoryService"); config.Configs["Modules"].Set("InventoryServices", "LocalInventoryServicesConnector"); if (real) { config.Configs["InventoryService"].Set("LocalServiceModule", "OpenSim.Services.InventoryService.dll:InventoryService"); } else { config.Configs["InventoryService"].Set("LocalServiceModule", "OpenSim.Tests.Common.dll:MockInventoryService"); } config.Configs["InventoryService"].Set("StorageProvider", "OpenSim.Tests.Common.dll"); inventoryService.Initialise(config); inventoryService.AddRegion(testScene); inventoryService.RegionLoaded(testScene); testScene.AddRegionModule(inventoryService.Name, inventoryService); m_inventoryService = inventoryService; } private static void StartGridService(Scene testScene, bool real) { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("GridService"); config.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector"); config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData"); if (real) config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService"); if (m_gridService == null) { ISharedRegionModule gridService = new LocalGridServicesConnector(); gridService.Initialise(config); m_gridService = gridService; } //else // config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Tests.Common.dll:TestGridService"); m_gridService.AddRegion(testScene); m_gridService.RegionLoaded(testScene); //testScene.AddRegionModule(m_gridService.Name, m_gridService); } /// <summary> /// Start a user account service /// </summary> /// <param name="testScene"></param> private static void StartUserAccountService(Scene testScene) { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("UserAccountService"); config.Configs["Modules"].Set("UserAccountServices", "LocalUserAccountServicesConnector"); config.Configs["UserAccountService"].Set("StorageProvider", "OpenSim.Data.Null.dll"); config.Configs["UserAccountService"].Set( "LocalServiceModule", "OpenSim.Services.UserAccountService.dll:UserAccountService"); if (m_userAccountService == null) { ISharedRegionModule userAccountService = new LocalUserAccountServicesConnector(); userAccountService.Initialise(config); m_userAccountService = userAccountService; } m_userAccountService.AddRegion(testScene); m_userAccountService.RegionLoaded(testScene); testScene.AddRegionModule(m_userAccountService.Name, m_userAccountService); } /// <summary> /// Start a presence service /// </summary> /// <param name="testScene"></param> private static void StartPresenceService(Scene testScene) { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("PresenceService"); config.Configs["Modules"].Set("PresenceServices", "LocalPresenceServicesConnector"); config.Configs["PresenceService"].Set("StorageProvider", "OpenSim.Data.Null.dll"); config.Configs["PresenceService"].Set( "LocalServiceModule", "OpenSim.Services.PresenceService.dll:PresenceService"); if (m_presenceService == null) { ISharedRegionModule presenceService = new LocalPresenceServicesConnector(); presenceService.Initialise(config); m_presenceService = presenceService; } m_presenceService.AddRegion(testScene); m_presenceService.RegionLoaded(testScene); testScene.AddRegionModule(m_presenceService.Name, m_presenceService); } /// <summary> /// Setup modules for a scene using their default settings. /// </summary> /// <param name="scene"></param> /// <param name="modules"></param> public static void SetupSceneModules(Scene scene, params object[] modules) { SetupSceneModules(scene, new IniConfigSource(), modules); } /// <summary> /// Setup modules for a scene. /// </summary> /// <param name="scene"></param> /// <param name="config"></param> /// <param name="modules"></param> public static void SetupSceneModules(Scene scene, IConfigSource config, params object[] modules) { List<IRegionModuleBase> newModules = new List<IRegionModuleBase>(); foreach (object module in modules) { if (module is IRegionModule) { IRegionModule m = (IRegionModule)module; m.Initialise(scene, config); scene.AddModule(m.Name, m); m.PostInitialise(); } else if (module is IRegionModuleBase) { // for the new system, everything has to be initialised first, // shared modules have to be post-initialised, then all get an AddRegion with the scene IRegionModuleBase m = (IRegionModuleBase)module; m.Initialise(config); newModules.Add(m); } } foreach (IRegionModuleBase module in newModules) { if (module is ISharedRegionModule) ((ISharedRegionModule)module).PostInitialise(); } foreach (IRegionModuleBase module in newModules) { module.AddRegion(scene); module.RegionLoaded(scene); scene.AddRegionModule(module.Name, module); } scene.SetModuleInterfaces(); } /// <summary> /// Generate some standard agent connection data. /// </summary> /// <param name="agentId"></param> /// <returns></returns> public static AgentCircuitData GenerateAgentData(UUID agentId) { string firstName = "testfirstname"; AgentCircuitData agentData = new AgentCircuitData(); agentData.AgentID = agentId; agentData.firstname = firstName; agentData.lastname = "testlastname"; agentData.SessionID = UUID.Zero; agentData.SecureSessionID = UUID.Zero; agentData.circuitcode = 123; agentData.BaseFolder = UUID.Zero; agentData.InventoryFolder = UUID.Zero; agentData.startpos = Vector3.Zero; agentData.CapsPath = "http://wibble.com"; return agentData; } /// <summary> /// Add a root agent where the details of the agent connection (apart from the id) are unimportant for the test /// </summary> /// <param name="scene"></param> /// <param name="agentId"></param> /// <returns></returns> public static TestClient AddRootAgent(Scene scene, UUID agentId) { return AddRootAgent(scene, GenerateAgentData(agentId)); } /// <summary> /// Add a root agent. /// </summary> /// /// This function /// /// 1) Tells the scene that an agent is coming. Normally, the login service (local if standalone, from the /// userserver if grid) would give initial login data back to the client and separately tell the scene that the /// agent was coming. /// /// 2) Connects the agent with the scene /// /// This function performs actions equivalent with notifying the scene that an agent is /// coming and then actually connecting the agent to the scene. The one step missed out is the very first /// /// <param name="scene"></param> /// <param name="agentData"></param> /// <returns></returns> public static TestClient AddRootAgent(Scene scene, AgentCircuitData agentData) { string reason; // We emulate the proper login sequence here by doing things in four stages // Stage 0: log the presence scene.PresenceService.LoginAgent(agentData.AgentID.ToString(), agentData.SessionID, agentData.SecureSessionID); // Stage 1: simulate login by telling the scene to expect a new user connection if (!scene.NewUserConnection(agentData, (uint)TeleportFlags.ViaLogin, out reason)) Console.WriteLine("NewUserConnection failed: " + reason); // Stage 2: add the new client as a child agent to the scene TestClient client = new TestClient(agentData, scene); scene.AddNewClient(client); // Stage 3: Invoke agent crossing, which converts the child agent into a root agent (with appearance, // inventory, etc.) //scene.AgentCrossing(agentData.AgentID, new Vector3(90, 90, 90), false); OBSOLETE ScenePresence scp = scene.GetScenePresence(agentData.AgentID); scp.MakeRootAgent(new Vector3(90, 90, 90), true); return client; } /// <summary> /// Add a test object /// </summary> /// <param name="scene"></param> /// <returns></returns> public static SceneObjectPart AddSceneObject(Scene scene) { return AddSceneObject(scene, "Test Object"); } /// <summary> /// Add a test object /// </summary> /// <param name="scene"></param> /// <param name="name"></param> /// <returns></returns> public static SceneObjectPart AddSceneObject(Scene scene, string name) { SceneObjectPart part = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero); part.Name = name; //part.UpdatePrimFlags(false, false, true); //part.ObjectFlags |= (uint)PrimFlags.Phantom; scene.AddNewSceneObject(new SceneObjectGroup(part), false); return part; } /// <summary> /// Delete a scene object asynchronously /// </summary> /// <param name="scene"></param> /// <param name="part"></param> /// <param name="action"></param> /// <param name="destinationId"></param> /// <param name="client"></param> public static void DeleteSceneObjectAsync( TestScene scene, SceneObjectPart part, DeRezAction action, UUID destinationId, IClientAPI client) { // Turn off the timer on the async sog deleter - we'll crank it by hand within a unit test AsyncSceneObjectGroupDeleter sogd = scene.SceneObjectGroupDeleter; sogd.Enabled = false; scene.DeRezObjects(client, new List<uint>() { part.LocalId }, UUID.Zero, action, destinationId); sogd.InventoryDeQueueAndDelete(); } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Org.Webrtc { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel']" [global::Android.Runtime.Register ("org/webrtc/DataChannel", DoNotGenerateAcw=true)] public partial class DataChannel : global::Java.Lang.Object { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Buffer']" [global::Android.Runtime.Register ("org/webrtc/DataChannel$Buffer", DoNotGenerateAcw=true)] public partial class Buffer : global::Java.Lang.Object { static IntPtr binary_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Buffer']/field[@name='binary']" [Register ("binary")] public bool Binary { get { if (binary_jfieldId == IntPtr.Zero) binary_jfieldId = JNIEnv.GetFieldID (class_ref, "binary", "Z"); return JNIEnv.GetBooleanField (Handle, binary_jfieldId); } set { if (binary_jfieldId == IntPtr.Zero) binary_jfieldId = JNIEnv.GetFieldID (class_ref, "binary", "Z"); try { JNIEnv.SetField (Handle, binary_jfieldId, value); } finally { } } } static IntPtr data_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Buffer']/field[@name='data']" [Register ("data")] public global::Java.Nio.ByteBuffer Data { get { if (data_jfieldId == IntPtr.Zero) data_jfieldId = JNIEnv.GetFieldID (class_ref, "data", "Ljava/nio/ByteBuffer;"); IntPtr __ret = JNIEnv.GetObjectField (Handle, data_jfieldId); return global::Java.Lang.Object.GetObject<global::Java.Nio.ByteBuffer> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (data_jfieldId == IntPtr.Zero) data_jfieldId = JNIEnv.GetFieldID (class_ref, "data", "Ljava/nio/ByteBuffer;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (Handle, data_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/DataChannel$Buffer", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Buffer); } } protected Buffer (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Ljava_nio_ByteBuffer_Z; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Buffer']/constructor[@name='DataChannel.Buffer' and count(parameter)=2 and parameter[1][@type='java.nio.ByteBuffer'] and parameter[2][@type='boolean']]" [Register (".ctor", "(Ljava/nio/ByteBuffer;Z)V", "")] public unsafe Buffer (global::Java.Nio.ByteBuffer p0, bool p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); if (GetType () != typeof (Buffer)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/nio/ByteBuffer;Z)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/nio/ByteBuffer;Z)V", __args); return; } if (id_ctor_Ljava_nio_ByteBuffer_Z == IntPtr.Zero) id_ctor_Ljava_nio_ByteBuffer_Z = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/nio/ByteBuffer;Z)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_nio_ByteBuffer_Z, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_nio_ByteBuffer_Z, __args); } finally { } } } // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Init']" [global::Android.Runtime.Register ("org/webrtc/DataChannel$Init", DoNotGenerateAcw=true)] public partial class Init : global::Java.Lang.Object { static IntPtr id_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Init']/field[@name='id']" [Register ("id")] public int Id { get { if (id_jfieldId == IntPtr.Zero) id_jfieldId = JNIEnv.GetFieldID (class_ref, "id", "I"); return JNIEnv.GetIntField (Handle, id_jfieldId); } set { if (id_jfieldId == IntPtr.Zero) id_jfieldId = JNIEnv.GetFieldID (class_ref, "id", "I"); try { JNIEnv.SetField (Handle, id_jfieldId, value); } finally { } } } static IntPtr maxRetransmitTimeMs_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Init']/field[@name='maxRetransmitTimeMs']" [Register ("maxRetransmitTimeMs")] public int MaxRetransmitTimeMs { get { if (maxRetransmitTimeMs_jfieldId == IntPtr.Zero) maxRetransmitTimeMs_jfieldId = JNIEnv.GetFieldID (class_ref, "maxRetransmitTimeMs", "I"); return JNIEnv.GetIntField (Handle, maxRetransmitTimeMs_jfieldId); } set { if (maxRetransmitTimeMs_jfieldId == IntPtr.Zero) maxRetransmitTimeMs_jfieldId = JNIEnv.GetFieldID (class_ref, "maxRetransmitTimeMs", "I"); try { JNIEnv.SetField (Handle, maxRetransmitTimeMs_jfieldId, value); } finally { } } } static IntPtr maxRetransmits_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Init']/field[@name='maxRetransmits']" [Register ("maxRetransmits")] public int MaxRetransmits { get { if (maxRetransmits_jfieldId == IntPtr.Zero) maxRetransmits_jfieldId = JNIEnv.GetFieldID (class_ref, "maxRetransmits", "I"); return JNIEnv.GetIntField (Handle, maxRetransmits_jfieldId); } set { if (maxRetransmits_jfieldId == IntPtr.Zero) maxRetransmits_jfieldId = JNIEnv.GetFieldID (class_ref, "maxRetransmits", "I"); try { JNIEnv.SetField (Handle, maxRetransmits_jfieldId, value); } finally { } } } static IntPtr negotiated_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Init']/field[@name='negotiated']" [Register ("negotiated")] public bool Negotiated { get { if (negotiated_jfieldId == IntPtr.Zero) negotiated_jfieldId = JNIEnv.GetFieldID (class_ref, "negotiated", "Z"); return JNIEnv.GetBooleanField (Handle, negotiated_jfieldId); } set { if (negotiated_jfieldId == IntPtr.Zero) negotiated_jfieldId = JNIEnv.GetFieldID (class_ref, "negotiated", "Z"); try { JNIEnv.SetField (Handle, negotiated_jfieldId, value); } finally { } } } static IntPtr ordered_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Init']/field[@name='ordered']" [Register ("ordered")] public bool Ordered { get { if (ordered_jfieldId == IntPtr.Zero) ordered_jfieldId = JNIEnv.GetFieldID (class_ref, "ordered", "Z"); return JNIEnv.GetBooleanField (Handle, ordered_jfieldId); } set { if (ordered_jfieldId == IntPtr.Zero) ordered_jfieldId = JNIEnv.GetFieldID (class_ref, "ordered", "Z"); try { JNIEnv.SetField (Handle, ordered_jfieldId, value); } finally { } } } static IntPtr protocol_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Init']/field[@name='protocol']" [Register ("protocol")] public string Protocol { get { if (protocol_jfieldId == IntPtr.Zero) protocol_jfieldId = JNIEnv.GetFieldID (class_ref, "protocol", "Ljava/lang/String;"); IntPtr __ret = JNIEnv.GetObjectField (Handle, protocol_jfieldId); return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef); } set { if (protocol_jfieldId == IntPtr.Zero) protocol_jfieldId = JNIEnv.GetFieldID (class_ref, "protocol", "Ljava/lang/String;"); IntPtr native_value = JNIEnv.NewString (value); try { JNIEnv.SetField (Handle, protocol_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/DataChannel$Init", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Init); } } protected Init (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.Init']/constructor[@name='DataChannel.Init' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe Init () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { if (GetType () != typeof (Init)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor); } finally { } } } // Metadata.xml XPath interface reference: path="/api/package[@name='org.webrtc']/interface[@name='DataChannel.Observer']" [Register ("org/webrtc/DataChannel$Observer", "", "Org.Webrtc.DataChannel/IObserverInvoker")] public partial interface IObserver : IJavaObject { // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/interface[@name='DataChannel.Observer']/method[@name='onBufferedAmountChange' and count(parameter)=1 and parameter[1][@type='long']]" [Register ("onBufferedAmountChange", "(J)V", "GetOnBufferedAmountChange_JHandler:Org.Webrtc.DataChannel/IObserverInvoker, WebRTCBindings")] void OnBufferedAmountChange (long p0); // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/interface[@name='DataChannel.Observer']/method[@name='onMessage' and count(parameter)=1 and parameter[1][@type='org.webrtc.DataChannel.Buffer']]" [Register ("onMessage", "(Lorg/webrtc/DataChannel$Buffer;)V", "GetOnMessage_Lorg_webrtc_DataChannel_Buffer_Handler:Org.Webrtc.DataChannel/IObserverInvoker, WebRTCBindings")] void OnMessage (global::Org.Webrtc.DataChannel.Buffer p0); // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/interface[@name='DataChannel.Observer']/method[@name='onStateChange' and count(parameter)=0]" [Register ("onStateChange", "()V", "GetOnStateChangeHandler:Org.Webrtc.DataChannel/IObserverInvoker, WebRTCBindings")] void OnStateChange (); } [global::Android.Runtime.Register ("org/webrtc/DataChannel$Observer", DoNotGenerateAcw=true)] internal class IObserverInvoker : global::Java.Lang.Object, IObserver { static IntPtr java_class_ref = JNIEnv.FindClass ("org/webrtc/DataChannel$Observer"); IntPtr class_ref; public static IObserver GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<IObserver> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "org.webrtc.DataChannel.Observer")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public IObserverInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (IObserverInvoker); } } static Delegate cb_onBufferedAmountChange_J; #pragma warning disable 0169 static Delegate GetOnBufferedAmountChange_JHandler () { if (cb_onBufferedAmountChange_J == null) cb_onBufferedAmountChange_J = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, long>) n_OnBufferedAmountChange_J); return cb_onBufferedAmountChange_J; } static void n_OnBufferedAmountChange_J (IntPtr jnienv, IntPtr native__this, long p0) { global::Org.Webrtc.DataChannel.IObserver __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.IObserver> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.OnBufferedAmountChange (p0); } #pragma warning restore 0169 IntPtr id_onBufferedAmountChange_J; public unsafe void OnBufferedAmountChange (long p0) { if (id_onBufferedAmountChange_J == IntPtr.Zero) id_onBufferedAmountChange_J = JNIEnv.GetMethodID (class_ref, "onBufferedAmountChange", "(J)V"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (Handle, id_onBufferedAmountChange_J, __args); } static Delegate cb_onMessage_Lorg_webrtc_DataChannel_Buffer_; #pragma warning disable 0169 static Delegate GetOnMessage_Lorg_webrtc_DataChannel_Buffer_Handler () { if (cb_onMessage_Lorg_webrtc_DataChannel_Buffer_ == null) cb_onMessage_Lorg_webrtc_DataChannel_Buffer_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnMessage_Lorg_webrtc_DataChannel_Buffer_); return cb_onMessage_Lorg_webrtc_DataChannel_Buffer_; } static void n_OnMessage_Lorg_webrtc_DataChannel_Buffer_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Webrtc.DataChannel.IObserver __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.IObserver> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.DataChannel.Buffer p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.Buffer> (native_p0, JniHandleOwnership.DoNotTransfer); __this.OnMessage (p0); } #pragma warning restore 0169 IntPtr id_onMessage_Lorg_webrtc_DataChannel_Buffer_; public unsafe void OnMessage (global::Org.Webrtc.DataChannel.Buffer p0) { if (id_onMessage_Lorg_webrtc_DataChannel_Buffer_ == IntPtr.Zero) id_onMessage_Lorg_webrtc_DataChannel_Buffer_ = JNIEnv.GetMethodID (class_ref, "onMessage", "(Lorg/webrtc/DataChannel$Buffer;)V"); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (Handle, id_onMessage_Lorg_webrtc_DataChannel_Buffer_, __args); } static Delegate cb_onStateChange; #pragma warning disable 0169 static Delegate GetOnStateChangeHandler () { if (cb_onStateChange == null) cb_onStateChange = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_OnStateChange); return cb_onStateChange; } static void n_OnStateChange (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.DataChannel.IObserver __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.IObserver> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.OnStateChange (); } #pragma warning restore 0169 IntPtr id_onStateChange; public unsafe void OnStateChange () { if (id_onStateChange == IntPtr.Zero) id_onStateChange = JNIEnv.GetMethodID (class_ref, "onStateChange", "()V"); JNIEnv.CallVoidMethod (Handle, id_onStateChange); } } // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.State']" [global::Android.Runtime.Register ("org/webrtc/DataChannel$State", DoNotGenerateAcw=true)] public sealed partial class State : global::Java.Lang.Enum { static IntPtr CLOSED_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.State']/field[@name='CLOSED']" [Register ("CLOSED")] public static global::Org.Webrtc.DataChannel.State Closed { get { if (CLOSED_jfieldId == IntPtr.Zero) CLOSED_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "CLOSED", "Lorg/webrtc/DataChannel$State;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, CLOSED_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.State> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr CLOSING_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.State']/field[@name='CLOSING']" [Register ("CLOSING")] public static global::Org.Webrtc.DataChannel.State Closing { get { if (CLOSING_jfieldId == IntPtr.Zero) CLOSING_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "CLOSING", "Lorg/webrtc/DataChannel$State;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, CLOSING_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.State> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr CONNECTING_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.State']/field[@name='CONNECTING']" [Register ("CONNECTING")] public static global::Org.Webrtc.DataChannel.State Connecting { get { if (CONNECTING_jfieldId == IntPtr.Zero) CONNECTING_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "CONNECTING", "Lorg/webrtc/DataChannel$State;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, CONNECTING_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.State> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr OPEN_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.State']/field[@name='OPEN']" [Register ("OPEN")] public static global::Org.Webrtc.DataChannel.State Open { get { if (OPEN_jfieldId == IntPtr.Zero) OPEN_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "OPEN", "Lorg/webrtc/DataChannel$State;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, OPEN_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.State> (__ret, JniHandleOwnership.TransferLocalRef); } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/DataChannel$State", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (State); } } internal State (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_valueOf_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.State']/method[@name='valueOf' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("valueOf", "(Ljava/lang/String;)Lorg/webrtc/DataChannel$State;", "")] public static unsafe global::Org.Webrtc.DataChannel.State ValueOf (string p0) { if (id_valueOf_Ljava_lang_String_ == IntPtr.Zero) id_valueOf_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "valueOf", "(Ljava/lang/String;)Lorg/webrtc/DataChannel$State;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); global::Org.Webrtc.DataChannel.State __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.State> (JNIEnv.CallStaticObjectMethod (class_ref, id_valueOf_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_values; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel.State']/method[@name='values' and count(parameter)=0]" [Register ("values", "()[Lorg/webrtc/DataChannel$State;", "")] public static unsafe global::Org.Webrtc.DataChannel.State[] Values () { if (id_values == IntPtr.Zero) id_values = JNIEnv.GetStaticMethodID (class_ref, "values", "()[Lorg/webrtc/DataChannel$State;"); try { return (global::Org.Webrtc.DataChannel.State[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_values), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Webrtc.DataChannel.State)); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/DataChannel", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (DataChannel); } } protected DataChannel (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_J; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel']/constructor[@name='DataChannel' and count(parameter)=1 and parameter[1][@type='long']]" [Register (".ctor", "(J)V", "")] public unsafe DataChannel (long p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (GetType () != typeof (DataChannel)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(J)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(J)V", __args); return; } if (id_ctor_J == IntPtr.Zero) id_ctor_J = JNIEnv.GetMethodID (class_ref, "<init>", "(J)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_J, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_J, __args); } finally { } } static Delegate cb_bufferedAmount; #pragma warning disable 0169 static Delegate GetBufferedAmountHandler () { if (cb_bufferedAmount == null) cb_bufferedAmount = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, long>) n_BufferedAmount); return cb_bufferedAmount; } static long n_BufferedAmount (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.DataChannel __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.BufferedAmount (); } #pragma warning restore 0169 static IntPtr id_bufferedAmount; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel']/method[@name='bufferedAmount' and count(parameter)=0]" [Register ("bufferedAmount", "()J", "GetBufferedAmountHandler")] public virtual unsafe long BufferedAmount () { if (id_bufferedAmount == IntPtr.Zero) id_bufferedAmount = JNIEnv.GetMethodID (class_ref, "bufferedAmount", "()J"); try { if (GetType () == ThresholdType) return JNIEnv.CallLongMethod (Handle, id_bufferedAmount); else return JNIEnv.CallNonvirtualLongMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "bufferedAmount", "()J")); } finally { } } static Delegate cb_close; #pragma warning disable 0169 static Delegate GetCloseHandler () { if (cb_close == null) cb_close = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Close); return cb_close; } static void n_Close (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.DataChannel __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Close (); } #pragma warning restore 0169 static IntPtr id_close; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel']/method[@name='close' and count(parameter)=0]" [Register ("close", "()V", "GetCloseHandler")] public virtual unsafe void Close () { if (id_close == IntPtr.Zero) id_close = JNIEnv.GetMethodID (class_ref, "close", "()V"); try { if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_close); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "close", "()V")); } finally { } } static Delegate cb_dispose; #pragma warning disable 0169 static Delegate GetDisposeHandler () { if (cb_dispose == null) cb_dispose = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Dispose); return cb_dispose; } static void n_Dispose (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.DataChannel __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Dispose (); } #pragma warning restore 0169 static IntPtr id_dispose; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel']/method[@name='dispose' and count(parameter)=0]" [Register ("dispose", "()V", "GetDisposeHandler")] public virtual unsafe void Dispose () { if (id_dispose == IntPtr.Zero) id_dispose = JNIEnv.GetMethodID (class_ref, "dispose", "()V"); try { if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_dispose); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "dispose", "()V")); } finally { } } static Delegate cb_label; #pragma warning disable 0169 static Delegate GetLabelHandler () { if (cb_label == null) cb_label = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Label); return cb_label; } static IntPtr n_Label (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.DataChannel __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Label ()); } #pragma warning restore 0169 static IntPtr id_label; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel']/method[@name='label' and count(parameter)=0]" [Register ("label", "()Ljava/lang/String;", "GetLabelHandler")] public virtual unsafe string Label () { if (id_label == IntPtr.Zero) id_label = JNIEnv.GetMethodID (class_ref, "label", "()Ljava/lang/String;"); try { if (GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_label), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "label", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } static Delegate cb_registerObserver_Lorg_webrtc_DataChannel_Observer_; #pragma warning disable 0169 static Delegate GetRegisterObserver_Lorg_webrtc_DataChannel_Observer_Handler () { if (cb_registerObserver_Lorg_webrtc_DataChannel_Observer_ == null) cb_registerObserver_Lorg_webrtc_DataChannel_Observer_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_RegisterObserver_Lorg_webrtc_DataChannel_Observer_); return cb_registerObserver_Lorg_webrtc_DataChannel_Observer_; } static void n_RegisterObserver_Lorg_webrtc_DataChannel_Observer_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Webrtc.DataChannel __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.DataChannel.IObserver p0 = (global::Org.Webrtc.DataChannel.IObserver)global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.IObserver> (native_p0, JniHandleOwnership.DoNotTransfer); __this.RegisterObserver (p0); } #pragma warning restore 0169 static IntPtr id_registerObserver_Lorg_webrtc_DataChannel_Observer_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel']/method[@name='registerObserver' and count(parameter)=1 and parameter[1][@type='org.webrtc.DataChannel.Observer']]" [Register ("registerObserver", "(Lorg/webrtc/DataChannel$Observer;)V", "GetRegisterObserver_Lorg_webrtc_DataChannel_Observer_Handler")] public virtual unsafe void RegisterObserver (global::Org.Webrtc.DataChannel.IObserver p0) { if (id_registerObserver_Lorg_webrtc_DataChannel_Observer_ == IntPtr.Zero) id_registerObserver_Lorg_webrtc_DataChannel_Observer_ = JNIEnv.GetMethodID (class_ref, "registerObserver", "(Lorg/webrtc/DataChannel$Observer;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_registerObserver_Lorg_webrtc_DataChannel_Observer_, __args); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "registerObserver", "(Lorg/webrtc/DataChannel$Observer;)V"), __args); } finally { } } static Delegate cb_send_Lorg_webrtc_DataChannel_Buffer_; #pragma warning disable 0169 static Delegate GetSend_Lorg_webrtc_DataChannel_Buffer_Handler () { if (cb_send_Lorg_webrtc_DataChannel_Buffer_ == null) cb_send_Lorg_webrtc_DataChannel_Buffer_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool>) n_Send_Lorg_webrtc_DataChannel_Buffer_); return cb_send_Lorg_webrtc_DataChannel_Buffer_; } static bool n_Send_Lorg_webrtc_DataChannel_Buffer_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Webrtc.DataChannel __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.DataChannel.Buffer p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.Buffer> (native_p0, JniHandleOwnership.DoNotTransfer); bool __ret = __this.Send (p0); return __ret; } #pragma warning restore 0169 static IntPtr id_send_Lorg_webrtc_DataChannel_Buffer_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel']/method[@name='send' and count(parameter)=1 and parameter[1][@type='org.webrtc.DataChannel.Buffer']]" [Register ("send", "(Lorg/webrtc/DataChannel$Buffer;)Z", "GetSend_Lorg_webrtc_DataChannel_Buffer_Handler")] public virtual unsafe bool Send (global::Org.Webrtc.DataChannel.Buffer p0) { if (id_send_Lorg_webrtc_DataChannel_Buffer_ == IntPtr.Zero) id_send_Lorg_webrtc_DataChannel_Buffer_ = JNIEnv.GetMethodID (class_ref, "send", "(Lorg/webrtc/DataChannel$Buffer;)Z"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); bool __ret; if (GetType () == ThresholdType) __ret = JNIEnv.CallBooleanMethod (Handle, id_send_Lorg_webrtc_DataChannel_Buffer_, __args); else __ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "send", "(Lorg/webrtc/DataChannel$Buffer;)Z"), __args); return __ret; } finally { } } static Delegate cb_state; #pragma warning disable 0169 static Delegate GetInvokeStateHandler () { if (cb_state == null) cb_state = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_InvokeState); return cb_state; } static IntPtr n_InvokeState (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.DataChannel __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.InvokeState ()); } #pragma warning restore 0169 static IntPtr id_state; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel']/method[@name='state' and count(parameter)=0]" [Register ("state", "()Lorg/webrtc/DataChannel$State;", "GetInvokeStateHandler")] public virtual unsafe global::Org.Webrtc.DataChannel.State InvokeState () { if (id_state == IntPtr.Zero) id_state = JNIEnv.GetMethodID (class_ref, "state", "()Lorg/webrtc/DataChannel$State;"); try { if (GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.State> (JNIEnv.CallObjectMethod (Handle, id_state), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel.State> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "state", "()Lorg/webrtc/DataChannel$State;")), JniHandleOwnership.TransferLocalRef); } finally { } } static Delegate cb_unregisterObserver; #pragma warning disable 0169 static Delegate GetUnregisterObserverHandler () { if (cb_unregisterObserver == null) cb_unregisterObserver = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_UnregisterObserver); return cb_unregisterObserver; } static void n_UnregisterObserver (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.DataChannel __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.DataChannel> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.UnregisterObserver (); } #pragma warning restore 0169 static IntPtr id_unregisterObserver; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='DataChannel']/method[@name='unregisterObserver' and count(parameter)=0]" [Register ("unregisterObserver", "()V", "GetUnregisterObserverHandler")] public virtual unsafe void UnregisterObserver () { if (id_unregisterObserver == IntPtr.Zero) id_unregisterObserver = JNIEnv.GetMethodID (class_ref, "unregisterObserver", "()V"); try { if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_unregisterObserver); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "unregisterObserver", "()V")); } finally { } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #if !NETFRAMEWORK_3_5 && !SILVERLIGHT_3_0 using System; using System.Collections.Generic; using System.Text; using System.Diagnostics.Contracts; namespace System { public partial interface ITuple { int Size { get; } } #region ITuple contract binding [ContractClass(typeof(ITupleContract))] public partial interface ITuple { } [ContractClassFor(typeof(ITuple))] abstract class ITupleContract : ITuple { public int Size { get { Contract.Ensures(Contract.Result<int>() >= 0); return default(int); } } } #endregion public static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { Contract.Ensures(Contract.Result<Tuple<T1>>() != null); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1>>().Item1, item1)); return default(Tuple<T1>); } public static Tuple<T1,T2> Create<T1,T2>(T1 item1, T2 item2) { Contract.Ensures(Contract.Result<Tuple<T1, T2>>() != null); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2>>().Item1, item1)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2>>().Item2, item2)); return default(Tuple<T1, T2>); } public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) { Contract.Ensures(Contract.Result<Tuple<T1, T2, T3>>() != null); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3>>().Item1, item1)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3>>().Item2, item2)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3>>().Item3, item3)); return default(Tuple<T1, T2, T3>); } public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) { Contract.Ensures(Contract.Result<Tuple<T1, T2, T3, T4>>() != null); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4>>().Item1, item1)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4>>().Item2, item2)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4>>().Item3, item3)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4>>().Item4, item4)); return default(Tuple<T1, T2, T3, T4>); } public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { Contract.Ensures(Contract.Result<Tuple<T1, T2, T3, T4, T5>>() != null); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5>>().Item1, item1)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5>>().Item2, item2)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5>>().Item3, item3)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5>>().Item4, item4)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5>>().Item5, item5)); return default(Tuple<T1, T2, T3, T4, T5>); } public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { Contract.Ensures(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6>>() != null); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6>>().Item1, item1)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6>>().Item2, item2)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6>>().Item3, item3)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6>>().Item4, item4)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6>>().Item5, item5)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6>>().Item6, item6)); return default(Tuple<T1, T2, T3, T4, T5, T6>); } public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { Contract.Ensures(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7>>() != null); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7>>().Item1, item1)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7>>().Item2, item2)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7>>().Item3, item3)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7>>().Item4, item4)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7>>().Item5, item5)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7>>().Item6, item6)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7>>().Item7, item7)); return default(Tuple<T1, T2, T3, T4, T5, T6, T7>); } public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) { Contract.Ensures(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>>() != null); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>>().Item1, item1)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>>().Item2, item2)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>>().Item3, item3)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>>().Item4, item4)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>>().Item5, item5)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>>().Item6, item6)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>>().Item7, item7)); Contract.Ensures(Object.Equals(Contract.Result<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>>().Rest, item8)); return default(Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>); } } public class Tuple<T1> : ITuple { public Tuple(T1 item1) { Contract.Ensures(Object.Equals(this.Item1, item1)); } extern public T1 Item1 { get; } extern int ITuple.Size { get; } } public class Tuple<T1, T2> : ITuple { public Tuple(T1 item1, T2 item2) { Contract.Ensures(Object.Equals(this.Item1, item1)); Contract.Ensures(Object.Equals(this.Item2, item2)); } extern public T1 Item1 { get; } extern public T2 Item2 { get; } extern int ITuple.Size { get; } } public class Tuple<T1, T2, T3> : ITuple { public Tuple(T1 item1, T2 item2, T3 item3) { Contract.Ensures(Object.Equals(this.Item1, item1)); Contract.Ensures(Object.Equals(this.Item2, item2)); Contract.Ensures(Object.Equals(this.Item3, item3)); } extern public T1 Item1 { get; } extern public T2 Item2 { get; } extern public T3 Item3 { get; } extern int ITuple.Size { get; } } public class Tuple<T1, T2, T3, T4> : ITuple { public Tuple(T1 item1, T2 item2, T3 item3, T4 item4) { Contract.Ensures(Object.Equals(this.Item1, item1)); Contract.Ensures(Object.Equals(this.Item2, item2)); Contract.Ensures(Object.Equals(this.Item3, item3)); Contract.Ensures(Object.Equals(this.Item4, item4)); } extern public T1 Item1 { get; } extern public T2 Item2 { get; } extern public T3 Item3 { get; } extern public T4 Item4 { get; } extern int ITuple.Size { get; } } public class Tuple<T1, T2, T3, T4, T5> : ITuple { public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { Contract.Ensures(Object.Equals(this.Item1, item1)); Contract.Ensures(Object.Equals(this.Item2, item2)); Contract.Ensures(Object.Equals(this.Item3, item3)); Contract.Ensures(Object.Equals(this.Item4, item4)); Contract.Ensures(Object.Equals(this.Item5, item5)); } extern public T1 Item1 { get; } extern public T2 Item2 { get; } extern public T3 Item3 { get; } extern public T4 Item4 { get; } extern public T5 Item5 { get; } extern int ITuple.Size { get; } } public class Tuple<T1, T2, T3, T4, T5, T6> : ITuple { public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { Contract.Ensures(Object.Equals(this.Item1, item1)); Contract.Ensures(Object.Equals(this.Item2, item2)); Contract.Ensures(Object.Equals(this.Item3, item3)); Contract.Ensures(Object.Equals(this.Item4, item4)); Contract.Ensures(Object.Equals(this.Item5, item5)); Contract.Ensures(Object.Equals(this.Item6, item6)); } extern public T1 Item1 { get; } extern public T2 Item2 { get; } extern public T3 Item3 { get; } extern public T4 Item4 { get; } extern public T5 Item5 { get; } extern public T6 Item6 { get; } extern int ITuple.Size { get; } } public class Tuple<T1, T2, T3, T4, T5, T6, T7> : ITuple { public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { Contract.Ensures(Object.Equals(this.Item1, item1)); Contract.Ensures(Object.Equals(this.Item2, item2)); Contract.Ensures(Object.Equals(this.Item3, item3)); Contract.Ensures(Object.Equals(this.Item4, item4)); Contract.Ensures(Object.Equals(this.Item5, item5)); Contract.Ensures(Object.Equals(this.Item6, item6)); Contract.Ensures(Object.Equals(this.Item7, item7)); } extern public T1 Item1 { get; } extern public T2 Item2 { get; } extern public T3 Item3 { get; } extern public T4 Item4 { get; } extern public T5 Item5 { get; } extern public T6 Item6 { get; } extern public T7 Item7 { get; } extern int ITuple.Size { get; } } public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : ITuple { public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest item8) { Contract.Ensures(Object.Equals(this.Item1, item1)); Contract.Ensures(Object.Equals(this.Item2, item2)); Contract.Ensures(Object.Equals(this.Item3, item3)); Contract.Ensures(Object.Equals(this.Item4, item4)); Contract.Ensures(Object.Equals(this.Item5, item5)); Contract.Ensures(Object.Equals(this.Item6, item6)); Contract.Ensures(Object.Equals(this.Item7, item7)); Contract.Ensures(Object.Equals(this.Rest, item8)); } extern public T1 Item1 { get; } extern public T2 Item2 { get; } extern public T3 Item3 { get; } extern public T4 Item4 { get; } extern public T5 Item5 { get; } extern public T6 Item6 { get; } extern public T7 Item7 { get; } extern public TRest Rest { get; } extern int ITuple.Size { get; } } } #endif
//------------------------------------------------------------------------------ // <license file="IdScriptableObject.cs"> // // The use and distribution terms for this software are contained in the file // named 'LICENSE', which can be found in the resources directory of this // distribution. // // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // </license> //------------------------------------------------------------------------------ using System; using System.Runtime.InteropServices; namespace EcmaScript.NET { /// <summary> /// Base class for native object implementation that uses IdFunctionObject to export its methods to script via <class-name>.prototype object. /// Any descendant should implement at least the following methods: /// findInstanceIdInfo /// getInstanceIdName /// execIdCall /// methodArity /// To define non-function properties, the descendant should override /// getInstanceIdValue /// setInstanceIdValue /// to get/set property value and provide its default attributes. /// To customize initializition of constructor and protype objects, descendant /// may override scopeInit or fillConstructorProperties methods. /// </summary> public abstract class IdScriptableObject : ScriptableObject, IIdFunctionCall { /// <summary> /// Get maximum id findInstanceIdInfo can generate. /// </summary> protected virtual internal int MaxInstanceId { get { return 0; } } private volatile PrototypeValues prototypeValues; private sealed class PrototypeValues { internal int MaxId { get { return maxId; } } private const int VALUE_SLOT = 0; private const int NAME_SLOT = 1; private const int SLOT_SPAN = 2; private IdScriptableObject obj; private int maxId; private volatile object [] valueArray; private volatile short [] attributeArray; private volatile int lastFoundId = 1; // The following helps to avoid creation of valueArray during runtime // initialization for common case of "constructor" property internal int constructorId; private IdFunctionObject constructor; private short constructorAttrs; internal PrototypeValues (IdScriptableObject obj, int maxId) { if (obj == null) throw new ArgumentNullException ("obj"); if (maxId < 1) throw new ArgumentException ("maxId may not lower than 1"); this.obj = obj; this.maxId = maxId; } internal void InitValue (int id, string name, object value, int attributes) { if (!(1 <= id && id <= maxId)) throw new ArgumentException (); if (name == null) throw new ArgumentException (); if (value == UniqueTag.NotFound) throw new ArgumentException (); ScriptableObject.CheckValidAttributes (attributes); if (obj.FindPrototypeId (name) != id) throw new ArgumentException (name); if (id == constructorId) { if (!(value is IdFunctionObject)) { throw new ArgumentException ("consructor should be initialized with IdFunctionObject"); } constructor = (IdFunctionObject)value; constructorAttrs = (short)attributes; return; } InitSlot (id, name, value, attributes); } private void InitSlot (int id, string name, object value, int attributes) { object [] array = valueArray; if (array == null) throw new ArgumentNullException ("array"); if (value == null) { value = UniqueTag.NullValue; } int index = (id - 1) * SLOT_SPAN; lock (this) { object value2 = array [index + VALUE_SLOT]; if (value2 == null) { array [index + VALUE_SLOT] = value; array [index + NAME_SLOT] = name; attributeArray [id - 1] = (short)attributes; } else { if (!name.Equals (array [index + NAME_SLOT])) throw new ApplicationException (); } } } internal IdFunctionObject createPrecachedConstructor () { if (constructorId != 0) throw new ApplicationException (); constructorId = obj.FindPrototypeId ("constructor"); if (constructorId == 0) { throw new ApplicationException ("No id for constructor property"); } obj.InitPrototypeId (constructorId); if (constructor == null) { throw new ApplicationException (obj.GetType ().FullName + ".initPrototypeId() did not " + "initialize id=" + constructorId); } constructor.InitFunction (obj.ClassName, ScriptableObject.GetTopLevelScope (obj)); constructor.MarkAsConstructor (obj); return constructor; } internal int FindId (string name) { object [] array = valueArray; if (array == null) { return obj.FindPrototypeId (name); } int id = lastFoundId; if ((object)name == array [(id - 1) * SLOT_SPAN + NAME_SLOT]) { return id; } id = obj.FindPrototypeId (name); if (id != 0) { int nameSlot = (id - 1) * SLOT_SPAN + NAME_SLOT; // Make cache to work! array [nameSlot] = name; lastFoundId = id; } return id; } internal bool Has (int id) { object [] array = valueArray; if (array == null) { // Not yet initialized, assume all exists return true; } int valueSlot = (id - 1) * SLOT_SPAN + VALUE_SLOT; object value = array [valueSlot]; if (value == null) { // The particular entry has not been yet initialized return true; } return value != UniqueTag.NotFound; } internal object Get (int id) { object value = EnsureId (id); if (value == UniqueTag.NullValue) { value = null; } return value; } internal void Set (int id, IScriptable start, object value) { if (value == UniqueTag.NotFound) throw new ArgumentException (); EnsureId (id); int attr = attributeArray [id - 1]; if ((attr & ScriptableObject.READONLY) == 0) { if (start == obj) { if (value == null) { value = UniqueTag.NullValue; } int valueSlot = (id - 1) * SLOT_SPAN + VALUE_SLOT; lock (this) { valueArray [valueSlot] = value; } } else { int nameSlot = (id - 1) * SLOT_SPAN + NAME_SLOT; string name = (string)valueArray [nameSlot]; start.Put (name, start, value); } } } internal void Delete (int id) { EnsureId (id); int attr = attributeArray [id - 1]; if ((attr & ScriptableObject.PERMANENT) == 0) { int valueSlot = (id - 1) * SLOT_SPAN + VALUE_SLOT; lock (this) { valueArray [valueSlot] = UniqueTag.NotFound; attributeArray [id - 1] = (short)(ScriptableObject.EMPTY); } } } internal int GetAttributes (int id) { EnsureId (id); return attributeArray [id - 1]; } internal void SetAttributes (int id, int attributes) { ScriptableObject.CheckValidAttributes (attributes); EnsureId (id); lock (this) { attributeArray [id - 1] = (short)attributes; } } internal object [] GetNames (bool getAll, object [] extraEntries) { object [] names = null; int count = 0; for (int id = 1; id <= maxId; ++id) { object value = EnsureId (id); if (getAll || (attributeArray [id - 1] & ScriptableObject.DONTENUM) == 0) { if (value != UniqueTag.NotFound) { int nameSlot = (id - 1) * SLOT_SPAN + NAME_SLOT; string name = (string)valueArray [nameSlot]; if (names == null) { names = new object [maxId]; } names [count++] = name; } } } if (count == 0) { return extraEntries; } else if (extraEntries == null || extraEntries.Length == 0) { if (count != names.Length) { object [] tmp = new object [count]; Array.Copy (names, 0, tmp, 0, count); names = tmp; } return names; } else { int extra = extraEntries.Length; object [] tmp = new object [extra + count]; Array.Copy (extraEntries, 0, tmp, 0, extra); Array.Copy (names, 0, tmp, extra, count); return tmp; } } private object EnsureId (int id) { object [] array = valueArray; if (array == null) { lock (this) { array = valueArray; if (array == null) { array = new object [maxId * SLOT_SPAN]; valueArray = array; attributeArray = new short [maxId]; } } } int valueSlot = (id - 1) * SLOT_SPAN + VALUE_SLOT; object value = array [valueSlot]; if (value == null) { if (id == constructorId) { InitSlot (constructorId, "constructor", constructor, constructorAttrs); constructor = null; // no need to refer it any longer } else { obj.InitPrototypeId (id); } value = array [valueSlot]; if (value == null) { throw new ApplicationException (obj.GetType ().FullName + ".initPrototypeId(int id) " + "did not initialize id=" + id); } } return value; } } public IdScriptableObject () { ; } public IdScriptableObject (IScriptable scope, IScriptable prototype) : base (scope, prototype) { ; } protected internal object DefaultGet (string name) { return base.Get (name, this); } protected internal void DefaultPut (string name, object value) { base.Put (name, this, value); } public override bool Has (string name, IScriptable start) { int info = FindInstanceIdInfo (name); if (info != 0) { int attr = (int)((uint)info >> 16); if ((attr & PERMANENT) != 0) { return true; } int id = (info & 0xFFFF); return UniqueTag.NotFound != GetInstanceIdValue (id); } if (prototypeValues != null) { int id = prototypeValues.FindId (name); if (id != 0) { return prototypeValues.Has (id); } } return base.Has (name, start); } public override object Get (string name, IScriptable start) { int info = FindInstanceIdInfo (name); if (info != 0) { int id = (info & 0xFFFF); return GetInstanceIdValue (id); } if (prototypeValues != null) { int id = prototypeValues.FindId (name); if (id != 0) { return prototypeValues.Get (id); } } return base.Get (name, start); } public override object Put (string name, IScriptable start, object value) { int info = FindInstanceIdInfo (name); if (info != 0) { if (start == this && Sealed) { throw Context.ReportRuntimeErrorById ("msg.modify.sealed", name); } int attr = (int)((uint)info >> 16); if ((attr & READONLY) == 0) { if (start == this) { int id = (info & 0xFFFF); SetInstanceIdValue (id, value); } else { return start.Put (name, start, value); } } return value; } if (prototypeValues != null) { int id = prototypeValues.FindId (name); if (id != 0) { if (start == this && Sealed) { throw Context.ReportRuntimeErrorById ("msg.modify.sealed", name); } prototypeValues.Set (id, start, value); return value; } } return base.Put (name, start, value); } public override void Delete (string name) { int info = FindInstanceIdInfo (name); if (info != 0) { // Let the super class to throw exceptions for sealed objects if (!Sealed) { int attr = (int)((uint)info >> 16); if ((attr & PERMANENT) == 0) { int id = (info & 0xFFFF); SetInstanceIdValue (id, UniqueTag.NotFound); } return; } } if (prototypeValues != null) { int id = prototypeValues.FindId (name); if (id != 0) { if (!Sealed) { prototypeValues.Delete (id); } return; } } base.Delete (name); } public override int GetAttributes (string name) { int info = FindInstanceIdInfo (name); if (info != 0) { int attr = (int)((uint)info >> 16); return attr; } if (prototypeValues != null) { int id = prototypeValues.FindId (name); if (id != 0) { return prototypeValues.GetAttributes (id); } } return base.GetAttributes (name); } public override void SetAttributes (string name, int attributes) { ScriptableObject.CheckValidAttributes (attributes); int info = FindInstanceIdInfo (name); if (info != 0) { int currentAttributes = (int)((uint)info >> 16); if (attributes != currentAttributes) { throw new ApplicationException ("Change of attributes for this id is not supported"); } return; } if (prototypeValues != null) { int id = prototypeValues.FindId (name); if (id != 0) { prototypeValues.SetAttributes (id, attributes); return; } } base.SetAttributes (name, attributes); } internal override object [] GetIds (bool getAll) { object [] result = base.GetIds (getAll); if (prototypeValues != null) { result = prototypeValues.GetNames (getAll, result); } int maxInstanceId = MaxInstanceId; if (maxInstanceId != 0) { object [] ids = null; int count = 0; for (int id = maxInstanceId; id != 0; --id) { string name = GetInstanceIdName (id); int info = FindInstanceIdInfo (name); if (info != 0) { int attr = (int)((uint)info >> 16); if ((attr & PERMANENT) == 0) { if (UniqueTag.NotFound == GetInstanceIdValue (id)) { continue; } } if (getAll || (attr & DONTENUM) == 0) { if (count == 0) { // Need extra room for no more then [1..id] names ids = new object [id]; } ids [count++] = name; } } } if (count != 0) { if (result.Length == 0 && ids.Length == count) { result = ids; } else { object [] tmp = new object [result.Length + count]; Array.Copy (result, 0, tmp, 0, result.Length); Array.Copy (ids, 0, tmp, result.Length, count); result = tmp; } } } return result; } protected internal static int InstanceIdInfo (int attributes, int id) { return (attributes << 16) | id; } /// <summary> /// Map name to id of instance property. /// Should return 0 if not found or the result of /// {@link #instanceIdInfo(int, int)}. /// </summary> protected internal virtual int FindInstanceIdInfo (string name) { return 0; } /// <summary> /// Map id back to property name it defines. /// </summary> protected internal virtual string GetInstanceIdName (int id) { throw new ArgumentException (Convert.ToString (id)); } /// <summary> /// Get id value. /// * If id value is constant, descendant can call cacheIdValue to store /// * value in the permanent cache. /// * Default implementation creates IdFunctionObject instance for given id /// * and cache its value /// </summary> protected internal virtual object GetInstanceIdValue (int id) { throw new ApplicationException (Convert.ToString (id)); } /// <summary> /// Set or delete id value. If value == NOT_FOUND , the implementation /// should make sure that the following getInstanceIdValue return NOT_FOUND. /// </summary> protected internal virtual void SetInstanceIdValue (int id, object value) { throw new ApplicationException (Convert.ToString (id)); } /// <summary>'thisObj' will be null if invoked as constructor, in which case /// * instance of Scriptable should be returned. /// </summary> public virtual object ExecIdCall (IdFunctionObject f, Context cx, IScriptable scope, IScriptable thisObj, object [] args) { throw f.Unknown (); } public IdFunctionObject ExportAsJSClass (int maxPrototypeId, IScriptable scope, bool zealed) { return ExportAsJSClass (maxPrototypeId, scope, zealed, ScriptableObject.DONTENUM); } public IdFunctionObject ExportAsJSClass (int maxPrototypeId, IScriptable scope, bool zealed, int attributes) { // Set scope and prototype unless this is top level scope itself if (scope != this && scope != null) { ParentScope = scope; SetPrototype (GetObjectPrototype (scope)); } ActivatePrototypeMap (maxPrototypeId); IdFunctionObject ctor = prototypeValues.createPrecachedConstructor (); if (zealed) { SealObject (); } FillConstructorProperties (ctor); if (zealed) { ctor.SealObject (); } ctor.ExportAsScopeProperty (attributes); return ctor; } public void ActivatePrototypeMap (int maxPrototypeId) { PrototypeValues values = new PrototypeValues (this, maxPrototypeId); lock (this) { if (prototypeValues != null) throw new ApplicationException (); prototypeValues = values; } } public void InitPrototypeMethod (object tag, int id, string name, int arity) { IScriptable scope = ScriptableObject.GetTopLevelScope (this); IdFunctionObject f = NewIdFunction (tag, id, name, arity, scope); prototypeValues.InitValue (id, name, f, DONTENUM); } public void InitPrototypeConstructor (IdFunctionObject f) { int id = prototypeValues.constructorId; if (id == 0) throw new ApplicationException (); if (f.MethodId != id) throw new ArgumentException (); if (Sealed) { f.SealObject (); } prototypeValues.InitValue (id, "constructor", f, DONTENUM); } public void InitPrototypeValue (int id, string name, object value, int attributes) { prototypeValues.InitValue (id, name, value, attributes); } protected internal virtual void InitPrototypeId (int id) { throw new ApplicationException (Convert.ToString (id)); } protected internal virtual int FindPrototypeId (string name) { throw new ApplicationException (name); } protected internal virtual void FillConstructorProperties (IdFunctionObject ctor) { } protected internal virtual void AddIdFunctionProperty (IScriptable obj, object tag, int id, string name, int arity) { IScriptable scope = ScriptableObject.GetTopLevelScope (obj); IdFunctionObject f = NewIdFunction (tag, id, name, arity, scope); f.AddAsProperty (obj); } /// <summary> /// Utility method to construct type error to indicate incompatible call /// when converting script thisObj to a particular type is not possible. /// Possible usage would be to have a private function like realThis: /// <pre> /// private static NativeSomething realThis(Scriptable thisObj, /// IdFunctionObject f) /// { /// if (!(thisObj instanceof NativeSomething)) /// throw incompatibleCallError(f); /// return (NativeSomething)thisObj; /// } /// </pre> /// Note that although such function can be implemented universally via /// java.lang.Class.isInstance(), it would be much more slower. /// </summary> /// <param name="readOnly">specify if the function f does not change state of /// object. /// </param> /// <returns> Scriptable object suitable for a check by the instanceof /// operator. /// </returns> /// <throws> RuntimeException if no more instanceof target can be found </throws> protected internal static EcmaScriptError IncompatibleCallError (IdFunctionObject f) { throw ScriptRuntime.TypeErrorById ("msg.incompat.call", f.FunctionName); } private IdFunctionObject NewIdFunction (object tag, int id, string name, int arity, IScriptable scope) { IdFunctionObject f = new IdFunctionObject (this, tag, id, name, arity, scope); if (Sealed) { f.SealObject (); } return f; } } }
// 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 AndInt32() { var test = new SimpleBinaryOpTest__AndInt32(); 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__AndInt32 { 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(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); 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<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, 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<Int32> _fld1; public Vector256<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndInt32 testClass) { var result = Avx2.And(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndInt32 testClass) { fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx2.And( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public SimpleBinaryOpTest__AndInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, 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.And( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_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.And( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_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.And( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_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.And), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(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.And), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(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.And), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int32>* pClsVar1 = &_clsVar1) fixed (Vector256<Int32>* pClsVar2 = &_clsVar2) { var result = Avx2.And( Avx.LoadVector256((Int32*)(pClsVar1)), Avx.LoadVector256((Int32*)(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<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.And(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((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.And(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((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndInt32(); var result = Avx2.And(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__AndInt32(); fixed (Vector256<Int32>* pFld1 = &test._fld1) fixed (Vector256<Int32>* pFld2 = &test._fld2) { var result = Avx2.And( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx2.And( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(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.And(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.And( Avx.LoadVector256((Int32*)(&test._fld1)), Avx.LoadVector256((Int32*)(&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<Int32> op1, Vector256<Int32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((int)(left[0] & right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(left[i] & right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.And)}<Int32>(Vector256<Int32>, Vector256<Int32>): {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; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.IO; using System.Security.Cryptography; using System.Text; using System.Windows.Forms; using DeOps.Services.Trust; using DeOps.Implementation; using DeOps.Implementation.Protocol; using DeOps.Interface; namespace DeOps.Services.Profile { public partial class ProfileView : ViewShell { OpCore Core; ProfileService Profiles; TrustService Trust; ulong UserID; public uint ProjectID; public Dictionary<string, string> TextFields = new Dictionary<string, string>(); public Dictionary<string, string> FileFields = new Dictionary<string, string>(); public ProfileView(ProfileService profile, ulong id, uint project) { InitializeComponent(); Profiles = profile; Core = profile.Core; Trust = Core.Trust; UserID = id; ProjectID = project; } public override void Init() { Profiles.ProfileUpdate += new ProfileUpdateHandler(Profile_Update); Trust.GuiUpdate += new LinkGuiUpdateHandler(Trust_Update); Core.KeepDataGui += new KeepDataHandler(Core_KeepData); OpProfile profile = Profiles.GetProfile(UserID); if (profile == null) DisplayLoading(); else Profile_Update(profile); // have to set twice (init document?) for page to show up if (GuiUtils.IsRunningOnMono()) { if (profile == null) DisplayLoading(); else Profile_Update(profile); } List<ulong> ids = new List<ulong>(); ids.AddRange(Trust.GetUplinkIDs(UserID, ProjectID)); foreach (ulong id in ids) Profiles.Research(id); } public override bool Fin() { Profiles.ProfileUpdate -= new ProfileUpdateHandler(Profile_Update); Trust.GuiUpdate -= new LinkGuiUpdateHandler(Trust_Update); Core.KeepDataGui -= new KeepDataHandler(Core_KeepData); return true; } void Core_KeepData() { Core.KeepData.SafeAdd(UserID, true); } private void DisplayLoading() { string html = @"<html> <body> <table width=""100%"" height=""100%""> <tr valign=""middle""> <td align=""center""> <b>Loading...</b> </td> </tr> </table> </body> </html>"; Browser.SetDocNoClick(html); } public override string GetTitle(bool small) { if (small) return "Profile"; if (UserID == Profiles.Core.UserID) return "My Profile"; return Profiles.Core.GetName(UserID) + "'s Profile"; } public override Size GetDefaultSize() { return new Size(500, 625); } public override Icon GetIcon() { return ProfileRes.IconX; } void Trust_Update(ulong key) { // if updated node is local, or higher, refresh so motd updates if (key != UserID && !Core.Trust.IsHigher(UserID, key, ProjectID)) return; OpProfile profile = Profiles.GetProfile(UserID); if (profile == null) return; Profile_Update(profile); } void Profile_Update(OpProfile profile) { // if self or in uplink chain, update profile List<ulong> uplinks = new List<ulong>(); uplinks.Add(UserID); uplinks.AddRange(Core.Trust.GetUplinkIDs(UserID, ProjectID)); if (!uplinks.Contains(profile.UserID)) return; // get fields from profile // if temp/id dir exists use it // clear temp/id dir // extract files to temp dir // get html // insert fields into html // display string tempPath = Profiles.ExtractPath; // create if needed, clear of pre-existing data if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath); // get the profile for this display profile = Profiles.GetProfile(UserID); if (profile == null) return; // not secure else { string[] files = Directory.GetFiles(tempPath); foreach (string path in files) File.Delete(path); } string template = LoadProfile(Profiles, profile, tempPath, TextFields, FileFields); if (template == null) { template = @"<html> <body> <table width=""100%"" height=""100%""> <tr valign=""middle""> <td align=""center""> <b>Unable to Load</b> </td> </tr> </table> </body> </html>"; } string html = FleshTemplate(Profiles, profile.UserID, ProjectID, template, TextFields, FileFields); Browser.SetDocNoClick(html); } private static string LoadProfile(ProfileService service, OpProfile profile, string tempPath, Dictionary<string, string> textFields, Dictionary<string, string> fileFields) { string template = null; textFields.Clear(); textFields["local_help"] = (profile.UserID == service.Core.UserID) ? "<font size=2>Right-click or click <a href='http://edit'>here</a> to Edit</font>" : ""; if(fileFields != null) fileFields.Clear(); if (!profile.Loaded) service.LoadProfile(profile.UserID); try { using (TaggedStream stream = new TaggedStream(service.GetFilePath(profile), service.Core.GuiProtocol)) using (IVCryptoStream crypto = IVCryptoStream.Load(stream, profile.File.Header.FileKey)) { int buffSize = 4096; byte[] buffer = new byte[4096]; long bytesLeft = profile.EmbeddedStart; while (bytesLeft > 0) { int readSize = (bytesLeft > (long)buffSize) ? buffSize : (int)bytesLeft; int read = crypto.Read(buffer, 0, readSize); bytesLeft -= (long)read; } // load file foreach (ProfileAttachment attached in profile.Attached) { if (attached.Name.StartsWith("template")) { byte[] html = new byte[attached.Size]; crypto.Read(html, 0, (int)attached.Size); UTF8Encoding utf = new UTF8Encoding(); template = utf.GetString(html); } else if (attached.Name.StartsWith("fields")) { byte[] data = new byte[attached.Size]; crypto.Read(data, 0, (int)attached.Size); int start = 0, length = data.Length; G2ReadResult streamStatus = G2ReadResult.PACKET_GOOD; while (streamStatus == G2ReadResult.PACKET_GOOD) { G2ReceivedPacket packet = new G2ReceivedPacket(); packet.Root = new G2Header(data); streamStatus = G2Protocol.ReadNextPacket(packet.Root, ref start, ref length); if (streamStatus != G2ReadResult.PACKET_GOOD) break; if (packet.Root.Name == ProfilePacket.Field) { ProfileField field = ProfileField.Decode(packet.Root); if (field.Value == null) continue; if (field.FieldType == ProfileFieldType.Text) textFields[field.Name] = UTF8Encoding.UTF8.GetString(field.Value); else if (field.FieldType == ProfileFieldType.File && fileFields != null) fileFields[field.Name] = UTF8Encoding.UTF8.GetString(field.Value); } } } else if (attached.Name.StartsWith("file=") && fileFields != null) { string name = attached.Name.Substring(5); try { string fileKey = null; foreach (string key in fileFields.Keys) if (name == fileFields[key]) { fileKey = key; break; } fileFields[fileKey] = tempPath + Path.DirectorySeparatorChar + name; using (FileStream extract = new FileStream(fileFields[fileKey], FileMode.CreateNew, FileAccess.Write)) { long remaining = attached.Size; byte[] buff = new byte[2096]; while (remaining > 0) { int read = (remaining > 2096) ? 2096 : (int)remaining; remaining -= read; crypto.Read(buff, 0, read); extract.Write(buff, 0, read); } } } catch { } } } } } catch (Exception) { } return template; } public static string FleshTemplate(ProfileService service, ulong id, uint project, string template, Dictionary<string, string> textFields, Dictionary<string, string> fileFields) { string final = template; // get link OpLink link = service.Core.Trust.GetLink(id, project); if (link == null) return ""; // replace fields while (final.Contains("<?")) { // get full tag name int start = final.IndexOf("<?"); int end = final.IndexOf("?>"); if (end == -1) break; string fulltag = final.Substring(start, end + 2 - start); string tag = fulltag.Substring(2, fulltag.Length - 4); string[] parts = tag.Split(new char[] { ':' }); bool tagfilled = false; if (parts.Length == 2) { if (parts[0] == "text" && textFields.ContainsKey(parts[1])) { final = final.Replace(fulltag, textFields[parts[1]]); tagfilled = true; } else if (parts[0] == "file" && fileFields != null && fileFields.ContainsKey(parts[1]) ) { string path = fileFields[parts[1]]; if (File.Exists(path)) { path = "file:///" + path; path = path.Replace(Path.DirectorySeparatorChar, '/'); final = final.Replace(fulltag, path); tagfilled = true; } } // load default photo if none in file else if (parts[0] == "file" && fileFields != null && parts[1] == "Photo") { string path = service.ExtractPath; // create if needed, clear of pre-existing data if (!Directory.Exists(path)) Directory.CreateDirectory(path); path += Path.DirectorySeparatorChar + "DefaultPhoto.jpg"; ProfileRes.DefaultPhoto.Save(path); if (File.Exists(path)) { path = "file:///" + path; path = path.Replace(Path.DirectorySeparatorChar, '/'); final = final.Replace(fulltag, path); tagfilled = true; } } else if (parts[0] == "link" && link != null) { tagfilled = true; if (parts[1] == "name") final = final.Replace(fulltag, service.Core.GetName(id)); else if (parts[1] == "title") { if (link.Uplink != null && link.Uplink.Titles.ContainsKey(id)) final = final.Replace(fulltag, link.Uplink.Titles[id]); else final = final.Replace(fulltag, ""); } else tagfilled = false; } else if (parts[0] == "motd") { if (parts[1] == "start") { string motd = FleshMotd(service, template, link.UserID, project); int startMotd = final.IndexOf("<?motd:start?>"); int endMotd = final.IndexOf("<?motd:end?>"); if (endMotd > startMotd) { endMotd += "<?motd:end?>".Length; final = final.Remove(startMotd, endMotd - startMotd); final = final.Insert(startMotd, motd); } } if (parts[1] == "next") return final; } } if (!tagfilled) final = final.Replace(fulltag, ""); } return final; } private static string FleshMotd(ProfileService service, string template, ulong id, uint project) { // extract motd template string startTag = "<?motd:start?>"; string nextTag = "<?motd:next?>"; int start = template.IndexOf(startTag) + startTag.Length; int end = template.IndexOf("<?motd:end?>"); if (end < start) return ""; string motdTemplate = template.Substring(start, end - start); // get links in chain up List<ulong> uplinks = new List<ulong>(); uplinks.Add(id); uplinks.AddRange(service.Core.Trust.GetUplinkIDs(id, project)); uplinks.Reverse(); // build cascading motds string finalMotd = ""; foreach (ulong uplink in uplinks) { OpProfile upperProfile = service.GetProfile(uplink); if (upperProfile != null) { Dictionary<string, string> textFields = new Dictionary<string, string>(); LoadProfile(service, upperProfile, null, textFields, null); string motdTag = "MOTD-" + project.ToString(); if(!textFields.ContainsKey(motdTag)) textFields[motdTag] = "No announcements"; textFields["MOTD"] = textFields[motdTag]; string currentMotd = motdTemplate; currentMotd = FleshTemplate(service, uplink, project, currentMotd, textFields, null); if (finalMotd == "") finalMotd = currentMotd; else if(finalMotd.IndexOf(nextTag) != -1) finalMotd = finalMotd.Replace(nextTag, currentMotd); } } finalMotd = finalMotd.Replace(nextTag, ""); return finalMotd; } private void RightClickMenu_Opening(object sender, CancelEventArgs e) { if (UserID != Profiles.Core.UserID) { e.Cancel = true; return; } } private void EditMenu_Click(object sender, EventArgs e) { EditProfile edit = new EditProfile(Profiles, this); edit.ShowDialog(this); } public uint GetProjectID() { return ProjectID; // call is a MarshalByRefObject so cant access value types directly } private void Browser_Navigating(object sender, WebBrowserNavigatingEventArgs e) { string url = e.Url.OriginalString; if (GuiUtils.IsRunningOnMono() && url.StartsWith("wyciwyg")) return; if (url.StartsWith("about:blank")) return; url = url.Replace("http://", ""); url = url.TrimEnd('/'); string[] command = url.Split('/'); if (command.Length > 0) if (command[0] == "edit") EditMenu.PerformClick(); e.Cancel = true; } } }
using System; using System.ComponentModel.DataAnnotations; using System.Linq; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Signum.Engine; using Signum.Engine.Authorization; using Signum.Engine.Mailing; using Signum.Engine.Operations; using Signum.Entities; using Signum.Entities.Authorization; using Signum.Entities.Basics; using Signum.React.Filters; using Signum.Services; using Signum.Utilities; using Signum.Engine.Basics; namespace Signum.React.Authorization { [ValidateModelFilter] public class AuthController : ControllerBase { [HttpPost("api/auth/login"), SignumAllowAnonymous] public ActionResult<LoginResponse> Login([Required, FromBody] LoginRequest data) { if (string.IsNullOrEmpty(data.userName)) return ModelError("userName", LoginAuthMessage.UserNameMustHaveAValue.NiceToString()); if (string.IsNullOrEmpty(data.password)) return ModelError("password", LoginAuthMessage.PasswordMustHaveAValue.NiceToString()); string authenticationType; // Attempt to login UserEntity user; try { if (AuthLogic.Authorizer == null) user = AuthLogic.Login(data.userName, Security.EncodePassword(data.password), out authenticationType); else user = AuthLogic.Authorizer.Login(data.userName, data.password, out authenticationType); } catch (Exception e) when (e is IncorrectUsernameException || e is IncorrectPasswordException) { if (AuthServer.MergeInvalidUsernameAndPasswordMessages) { return ModelError("login", LoginAuthMessage.InvalidUsernameOrPassword.NiceToString()); } else if (e is IncorrectUsernameException) { return ModelError("userName", LoginAuthMessage.InvalidUsername.NiceToString()); } else if (e is IncorrectPasswordException) { return ModelError("password", LoginAuthMessage.InvalidPassword.NiceToString()); } throw; } catch (Exception e) { return ModelError("login", e.Message); } AuthServer.OnUserPreLogin(ControllerContext, user); AuthServer.AddUserSession(ControllerContext, user); if (data.rememberMe == true) { UserTicketServer.SaveCookie(ControllerContext); } var token = AuthTokenServer.CreateToken(user); return new LoginResponse { userEntity = user, token = token, authenticationType = authenticationType }; } [HttpGet("api/auth/loginFromApiKey")] public LoginResponse LoginFromApiKey(string apiKey) { var token = AuthTokenServer.CreateToken(UserEntity.Current); return new LoginResponse { userEntity = UserEntity.Current, token = token, authenticationType = "api-key" }; } [HttpPost("api/auth/loginFromCookie"), SignumAllowAnonymous] public LoginResponse? LoginFromCookie() { if (!UserTicketServer.LoginFromCookie(ControllerContext)) return null; var token = AuthTokenServer.CreateToken(UserEntity.Current); return new LoginResponse { userEntity = UserEntity.Current, token = token, authenticationType = "cookie" }; } [HttpPost("api/auth/loginWindowsAuthentication"), Authorize, SignumAllowAnonymous] public LoginResponse? LoginWindowsAuthentication(bool throwError) { string? error = WindowsAuthenticationServer.LoginWindowsAuthentication(ControllerContext); if (error != null) { if (throwError) throw new InvalidOperationException(error); return null; } var token = AuthTokenServer.CreateToken(UserEntity.Current); return new LoginResponse { userEntity = UserEntity.Current, token = token, authenticationType = "windows" }; } [HttpPost("api/auth/loginWithAzureAD"), SignumAllowAnonymous] public LoginResponse? LoginWithAzureAD([FromBody, Required] string jwt, [FromQuery] bool throwErrors = true) { if (!AzureADAuthenticationServer.LoginAzureADAuthentication(ControllerContext, jwt, throwErrors)) return null; var token = AuthTokenServer.CreateToken(UserEntity.Current); return new LoginResponse { userEntity = UserEntity.Current, token = token, authenticationType = "azureAD" }; } [HttpGet("api/auth/currentUser")] public UserEntity? GetCurrentUser() { var result = UserEntity.Current; return result.Is(AuthLogic.AnonymousUser) ? null : result; } [HttpPost("api/auth/logout")] public void Logout() { AuthServer.UserLoggingOut?.Invoke(ControllerContext, UserEntity.Current); UserTicketServer.RemoveCookie(ControllerContext); } [HttpPost("api/auth/ChangePassword")] public ActionResult<LoginResponse> ChangePassword([Required, FromBody] ChangePasswordRequest request) { if (string.IsNullOrEmpty(request.newPassword)) return ModelError("newPassword", LoginAuthMessage.PasswordMustHaveAValue.NiceToString()); var error = UserEntity.OnValidatePassword(request.newPassword); if (error.HasText()) return ModelError("newPassword", error); var user = UserEntity.Current; if(string.IsNullOrEmpty(request.oldPassword)) { if(user.PasswordHash != null) return ModelError("oldPassword", LoginAuthMessage.PasswordMustHaveAValue.NiceToString()); } else { if (user.PasswordHash == null || !user.PasswordHash.SequenceEqual(Security.EncodePassword(request.oldPassword))) return ModelError("oldPassword", LoginAuthMessage.InvalidPassword.NiceToString()); } user.PasswordHash = Security.EncodePassword(request.newPassword); using (AuthLogic.Disable()) using (OperationLogic.AllowSave<UserEntity>()) { user.Save(); } return new LoginResponse { userEntity = user, token = AuthTokenServer.CreateToken(UserEntity.Current), authenticationType = "changePassword" }; } [HttpPost("api/auth/forgotPasswordEmail"), SignumAllowAnonymous] public string? ForgotPasswordEmail([Required, FromBody] ForgotPasswordRequest request) { if (string.IsNullOrEmpty(request.eMail)) return LoginAuthMessage.EnterYourUserEmail.NiceToString(); try { ResetPasswordRequestLogic.SendResetPasswordRequestEmail(request.eMail); } catch (Exception ex) { return ex.Message; } return null; } [HttpPost("api/auth/resetPassword"), SignumAllowAnonymous] public ActionResult<LoginResponse> ResetPassword([Required, FromBody] ResetPasswordRequest request) { if (string.IsNullOrEmpty(request.newPassword)) return ModelError("newPassword", LoginAuthMessage.PasswordMustHaveAValue.NiceToString()); var error = UserEntity.OnValidatePassword(request.newPassword); if (error != null) return ModelError("newPassword", error); var rpr = ResetPasswordRequestLogic.ResetPasswordRequestExecute(request.code, request.newPassword); return new LoginResponse { userEntity = rpr.User, token = AuthTokenServer.CreateToken(rpr.User), authenticationType = "resetPassword" }; } private BadRequestObjectResult ModelError(string field, string error) { ModelState.AddModelError(field, error); return new BadRequestObjectResult(ModelState); } #pragma warning disable IDE1006 // Naming Styles public class LoginRequest { public string userName { get; set; } public string password { get; set; } public bool? rememberMe { get; set; } } public class LoginResponse { public string authenticationType { get; set; } public string token { get; set; } public UserEntity userEntity { get; set; } } public class ChangePasswordRequest { public string oldPassword { get; set; } public string newPassword { get; set; } } public class ResetPasswordRequest { public string code { get; set; } public string newPassword { get; set; } } public class ForgotPasswordRequest { public string eMail { get; set; } } #pragma warning restore IDE1006 // Naming Styles } }
// Copyright (c) 2015, Outercurve Foundation. // 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 the Outercurve Foundation 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. using System; using System.Collections; using System.IO; using System.Collections.Generic; using System.Web.Services.Protocols; using System.Xml.XPath; using WebsitePanel.Providers.Common; using WebsitePanel.Providers.Utils; using WebsitePanel.Server.Utils; using Microsoft.Win32; namespace WebsitePanel.Providers.Mail { public class SmarterMail2 : HostingServiceProviderBase, IMailServer { #region Constants public const string SYSTEM_DOMAIN_ADMIN = "system.domain.admin"; public const string SYSTEM_CATCH_ALL = "system.catch.all"; #endregion #region Public Properties protected string AdminUsername { get { return ProviderSettings["AdminUsername"]; } } protected string AdminPassword { get { return ProviderSettings["AdminPassword"]; } } protected bool ImportDomainAdmin { get { bool res; bool.TryParse(ProviderSettings[Constants.ImportDomainAdmin], out res); return res; } } protected bool InheritDomainDefaultLimits { get { bool res; bool.TryParse(ProviderSettings[Constants.InheritDomainDefaultLimits], out res); return res; } } protected string DomainsPath { get { return FileUtils.EvaluateSystemVariables(ProviderSettings["DomainsPath"]); } } protected string ServerIP { get { string val = ProviderSettings["ServerIPAddress"]; if(String.IsNullOrEmpty(val)) return "127.0.0.1"; string ip = val.Trim(); if (ip.IndexOf(";") > -1) { string[] ips = ip.Split(';'); ip = String.IsNullOrEmpty(ips[1]) ? ips[0] : ips[1]; // get internal IP part } return ip; } } protected string ServiceUrl { get { return ProviderSettings["ServiceUrl"]; } } #endregion #region Mail domains /// <summary> /// Returns domain info /// </summary> /// <param name="domainName">Domain name</param> /// <returns>Domain info</returns> public virtual MailDomain GetDomain(string domainName) { try { svcDomainAdmin domains = new svcDomainAdmin(); PrepareProxy(domains); DomainSettingsResult result = domains.GetDomainSettings(AdminUsername, AdminPassword, domainName); if (!result.Result) throw new Exception(result.Message); // fill domain properties MailDomain domain = new MailDomain(); domain.Name = domainName; domain.Path = result.Path; domain.ServerIP = result.ServerIP; domain.ImapPort = result.ImapPort; domain.SmtpPort = result.SmtpPort; domain.PopPort = result.PopPort; domain.MaxAliases = result.MaxAliases; domain.MaxDomainAliases = result.MaxDomainAliases; domain.MaxLists = result.MaxLists; domain.MaxDomainSizeInMB = result.MaxDomainSizeInMB; domain.MaxDomainUsers = result.MaxDomainUsers; domain.MaxMailboxSizeInMB = result.MaxMailboxSizeInMB; domain.MaxMessageSize = result.MaxMessageSize; domain.MaxRecipients = result.MaxRecipients; domain.RequireSmtpAuthentication = result.RequireSmtpAuthentication; domain.ListCommandAddress = result.ListCommandAddress; domain.ShowContentFilteringMenu = result.ShowContentFilteringMenu; domain.ShowDomainAliasMenu = result.ShowDomainAliasMenu; domain.ShowListMenu = result.ShowListMenu; domain.ShowSpamMenu = result.ShowSpamMenu; domain.ShowsStatsMenu = result.ShowStatsMenu; // get additional domain settings string[] requestedSettings = new string[] { "catchall", "isenabled", "ldapport", "altsmtpport", "sharedcalendar", "sharedcontact", "sharedfolder", "sharednotes", "sharedtasks", "sharedgal", "bypassforwardblacklist", }; SettingsRequestResult addResult = domains.GetRequestedDomainSettings(AdminUsername, AdminPassword, domainName, requestedSettings); if (!addResult.Result) throw new Exception(addResult.Message); FillMailDomainFields(domain, addResult); // get catch-all address if (!String.IsNullOrEmpty(domain.CatchAllAccount)) { // get catch-all group string groupName = SYSTEM_CATCH_ALL + "@" + domain.Name; if (GroupExists(groupName)) { // get the first member of this group MailGroup group = GetGroup(groupName); domain.CatchAllAccount = GetAccountName(group.Members[0]); } } /* //get license information if (GetProductLicenseInfo() == "PRO") { domain[MailDomain.SMARTERMAIL_LICENSE_TYPE] = "PRO"; } if (GetProductLicenseInfo() == "ENT") { domain[MailDomain.SMARTERMAIL_LICENSE_TYPE] = "ENT"; } if (GetProductLicenseInfo() == "FREE") { domain[MailDomain.SMARTERMAIL_LICENSE_TYPE] = "FREE"; } */ return domain; } catch (Exception ex) { throw new Exception("Could not get mail domain", ex); } } private static void FillMailDomainFields(MailDomain domain, SettingsRequestResult addResult) { foreach (string pair in addResult.settingValues) { string[] parts = pair.Split('='); switch (parts[0]) { case "catchall": domain.CatchAllAccount = parts[1]; break; case "isenabled": domain.Enabled = Boolean.Parse(parts[1]); break; case "ldapport": domain.LdapPort = int.Parse(parts[1]); break; case "altsmtpport": domain.SmtpPortAlt = int.Parse(parts[1]); break; case "sharedcalendar": domain.SharedCalendars = Boolean.Parse(parts[1]); break; case "sharedcontact": domain.SharedContacts = Boolean.Parse(parts[1]); break; case "sharedfolder": domain.SharedFolders = Boolean.Parse(parts[1]); break; case "sharednotes": domain.SharedNotes = Boolean.Parse(parts[1]); break; case "sharedtasks": domain.SharedTasks = Boolean.Parse(parts[1]); break; case "sharedgal": domain.IsGlobalAddressList = Boolean.Parse(parts[1]); break; case "bypassforwardblacklist": domain.BypassForwardBlackList = Boolean.Parse(parts[1]); break; } } } /// <summary> /// Returns a list of all domain names /// </summary> /// <returns>Array with domain names</returns> public virtual string[] GetDomains() { try { svcDomainAdmin domains = new svcDomainAdmin(); PrepareProxy(domains); DomainListResult result = domains.GetAllDomains(AdminUsername, AdminPassword); if (!result.Result) throw new Exception(result.Message); return result.DomainNames; } catch (Exception ex) { throw new Exception("Could not get the list of mail domains", ex); } } /// <summary> /// Checks whether the specified domain exists /// </summary> /// <param name="domainName">Domain name</param> /// <returns>true if the specified domain exists, otherwise false</returns> public virtual bool DomainExists(string domainName) { try { svcDomainAdmin domains = new svcDomainAdmin(); PrepareProxy(domains); DomainSettingsResult result = domains.GetDomainSettings(AdminUsername, AdminPassword, domainName); return result.Result; } catch (Exception ex) { throw new Exception("Could not check whether mail domain exists", ex); } } /// <summary> /// Creates a new domain in the specified folder /// </summary> /// <param name="domain">Domain info</param> public virtual void CreateDomain(MailDomain domain) { try { svcDomainAdmin domains = new svcDomainAdmin(); PrepareProxy(domains); DomainSettingsResult defaultDomainSettings = domains.GetDomainDefaults(AdminUsername, AdminPassword); SettingsRequestResult defaultRequestedSettings = domains.GetRequestedDomainDefaults(AdminUsername, AdminPassword, new string[] { "defaultaltsmtpport", "defaultimapport", "defaultmaxaliases", "defaultmaxdomainaliases", "defaultmaxdomainsize", "defaultmaxdomainusers", "defaultmaxlists", "defaultmaxmailboxsize", "defaultmaxmessagesize", "defaultmaxrecipients", "defaultpopport", "defaultshowcontentfilteringmenu", "defaultshowdomainaliasmenu", "defaultshowlistmenu", "defaultshowspammenu", "defaultshowstatmenu", "defaultsmtpauthenticationrequired", "defaultsmtpport", "defaultbypassforwardblacklist", "defaultldapport", "defaultldapdisallowoptout", "defaultsharedcalendar", "defaultsharedcontact", "defaultsharedfolder", "defaultsharedtasks", "defaultsharedgal" }); string[] requestedDomainDefaults = defaultRequestedSettings.settingValues; //domain Path is taken from WebsitePanel Service settings GenericResult1 result = null; if (!InheritDomainDefaultLimits) { result = domains.AddDomain(AdminUsername, AdminPassword, domain.Name, Path.Combine(DomainsPath, domain.Name), SYSTEM_DOMAIN_ADMIN, // admin username Guid.NewGuid().ToString("P"), // admin password "Domain", // admin first name "Administrator", // admin last name ServerIP, defaultDomainSettings.ImapPort, defaultDomainSettings.PopPort, defaultDomainSettings.SmtpPort, domain.MaxAliases, domain.MaxDomainSizeInMB, domain.MaxDomainUsers, domain.MaxMailboxSizeInMB, domain.MaxMessageSize, domain.MaxRecipients, domain.MaxDomainAliases, domain.MaxLists, defaultDomainSettings.ShowDomainAliasMenu,// ShowDomainAliasMenu defaultDomainSettings.ShowContentFilteringMenu,// ShowContentFilteringMenu defaultDomainSettings.ShowSpamMenu, // ShowSpamMenu defaultDomainSettings.ShowStatsMenu, // ShowStatsMenu defaultDomainSettings.RequireSmtpAuthentication, defaultDomainSettings.ShowListMenu, // ShowListMenu defaultDomainSettings.ListCommandAddress); } else { result = domains.AddDomain(AdminUsername, AdminPassword, domain.Name, Path.Combine(DomainsPath, domain.Name), SYSTEM_DOMAIN_ADMIN, // admin username Guid.NewGuid().ToString("P"), // admin password "Domain", // admin first name "Administrator", // admin last name ServerIP, defaultDomainSettings.ImapPort, defaultDomainSettings.PopPort, defaultDomainSettings.SmtpPort, defaultDomainSettings.MaxAliases, defaultDomainSettings.MaxDomainSizeInMB, defaultDomainSettings.MaxDomainUsers, defaultDomainSettings.MaxMailboxSizeInMB, defaultDomainSettings.MaxMessageSize, defaultDomainSettings.MaxRecipients, defaultDomainSettings.MaxDomainAliases, defaultDomainSettings.MaxLists, defaultDomainSettings.ShowDomainAliasMenu,// ShowDomainAliasMenu defaultDomainSettings.ShowContentFilteringMenu,// ShowContentFilteringMenu defaultDomainSettings.ShowSpamMenu, // ShowSpamMenu defaultDomainSettings.ShowStatsMenu, // ShowStatsMenu defaultDomainSettings.RequireSmtpAuthentication, defaultDomainSettings.ShowListMenu, // ShowListMenu defaultDomainSettings.ListCommandAddress); } if (!result.Result) throw new Exception(result.Message); // update additional settings result = domains.SetRequestedDomainSettings(AdminUsername, AdminPassword, domain.Name, requestedDomainDefaults); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not create mail domain", ex); } } /// <summary> /// Updates the settings for the specified domain /// </summary> /// <param name="domain">Domain info</param> public virtual void UpdateDomain(MailDomain domain) { try { // load original domain MailDomain origDomain = GetDomain(domain.Name); svcDomainAdmin domains = new svcDomainAdmin(); PrepareProxy(domains); GenericResult1 result = domains.UpdateDomain(AdminUsername, AdminPassword, domain.Name, origDomain.ServerIP, domain.ImapPort, domain.PopPort, domain.SmtpPort, domain.MaxAliases, domain.MaxDomainSizeInMB, domain.MaxDomainUsers, domain.MaxMailboxSizeInMB, domain.MaxMessageSize, domain.MaxRecipients, domain.MaxDomainAliases, domain.MaxLists, domain.ShowDomainAliasMenu, // ShowDomainAliasMenu domain.ShowContentFilteringMenu, // ShowContentFilteringMenu domain.ShowSpamMenu, // ShowSpamMenu domain.ShowsStatsMenu, // ShowStatsMenu origDomain.RequireSmtpAuthentication, domain.ShowListMenu, // ShowListMenu origDomain.ListCommandAddress); if (!result.Result) throw new Exception(result.Message); // update catch-all group UpdateDomainCatchAllGroup(domain.Name, domain.CatchAllAccount); // update additional settings result = domains.SetRequestedDomainSettings(AdminUsername, AdminPassword, domain.Name, new string[] { "isenabled=" + domain.Enabled, "catchall=" + (!String.IsNullOrEmpty(domain.CatchAllAccount) ? SYSTEM_CATCH_ALL : ""), "altsmtpport=" + domain.SmtpPortAlt, "ldapport=" + domain.LdapPort, "sharedcalendar=" + domain.SharedCalendars, "sharedcontact=" + domain.SharedContacts, "sharedfolder=" + domain.SharedFolders, "sharednotes=" + domain.SharedNotes, "sharedtasks=" + domain.SharedTasks, "sharedgal=" + domain.IsGlobalAddressList, "bypassforwardblacklist=" + domain.BypassForwardBlackList, }); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not update mail domain", ex); } } /// <summary> /// Deletes the specified domain /// </summary> /// <param name="domainName"></param> public virtual void DeleteDomain(string domainName) { try { svcDomainAdmin domains = new svcDomainAdmin(); PrepareProxy(domains); GenericResult1 result = domains.DeleteDomain(AdminUsername, AdminPassword, domainName, true // delete files ); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not delete mail domain", ex); } } private void UpdateDomainCatchAllGroup(string domainName, string mailboxName) { // check if system catch all group exists string groupName = SYSTEM_CATCH_ALL + "@" + domainName; if (GroupExists(groupName)) { // delete group DeleteGroup(groupName); } if (!String.IsNullOrEmpty(mailboxName)) { // create catch-all group MailGroup group = new MailGroup(); group.Name = groupName; group.Enabled = true; group.Members = new string[] { mailboxName + "@" + domainName }; // create CreateGroup(group); } } #endregion #region Domain aliases public virtual bool DomainAliasExists(string domainName, string aliasName) { try { string[] aliases = GetDomainAliases(domainName); foreach (string alias in aliases) { if (String.Compare(alias, aliasName, true) == 0) return true; } return false; } catch (Exception ex) { throw new Exception("Could not check whether mail domain alias exists", ex); } } public virtual void AddDomainAlias(string domainName, string aliasName) { try { svcDomainAliasAdmin aliases = new svcDomainAliasAdmin(); PrepareProxy(aliases); GenericResult1 result = aliases.AddDomainAlias(AdminUsername, AdminPassword, domainName, aliasName); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not add mail domain alias", ex); } } public virtual void DeleteDomainAlias(string domainName, string aliasName) { try { svcDomainAliasAdmin aliases = new svcDomainAliasAdmin(); PrepareProxy(aliases); GenericResult1 result = aliases.DeleteDomainAlias(AdminUsername, AdminPassword, domainName, aliasName); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not delete mail domain alias", ex); } } /// <summary> /// Returns all domain aliases that belong to the specified domain /// </summary> /// <param name="domainName">Domain name</param> /// <returns>Array with domain names</returns> public virtual string[] GetDomainAliases(string domainName) { try { svcDomainAliasAdmin aliases = new svcDomainAliasAdmin(); PrepareProxy(aliases); DomainAliasInfoListResult result = aliases.GetAliases(AdminUsername, AdminPassword, domainName); if (!result.Result) throw new Exception(result.Message); return result.DomainAliasNames; } catch (Exception ex) { throw new Exception("Could not get the list of mail domain aliases", ex); } } #endregion #region Domain Groups (Aliases) public virtual bool GroupExists(string groupName) { try { svcAliasAdmin svcGroups = new svcAliasAdmin(); PrepareProxy(svcGroups); AliasInfoResult result = svcGroups.GetAlias(AdminUsername, AdminPassword, GetDomainName(groupName), groupName); return (result.Result && result.AliasInfo.Name != "Empty"); } catch (Exception ex) { throw new Exception("Could not check whether mail domain group exists", ex); } } public virtual MailGroup[] GetGroups(string domainName) { try { svcAliasAdmin svcGroups = new svcAliasAdmin(); PrepareProxy(svcGroups); AliasInfoListResult result = svcGroups.GetAliases(AdminUsername, AdminPassword, domainName); if (!result.Result) throw new Exception(result.Message); MailGroup[] groups = new MailGroup[result.AliasInfos.Length]; for (int i = 0; i < groups.Length; i++) { groups[i] = new MailGroup(); groups[i].Name = result.AliasInfos[i].Name + "@" + domainName; groups[i].Members = result.AliasInfos[i].Addresses; groups[i].Enabled = true; // by default } return groups; } catch (Exception ex) { throw new Exception("Could not get the list of mail domain groups", ex); } } public virtual MailGroup GetGroup(string groupName) { try { svcAliasAdmin svcGroups = new svcAliasAdmin(); PrepareProxy(svcGroups); AliasInfoResult result = svcGroups.GetAlias(AdminUsername, AdminPassword, GetDomainName(groupName), groupName); if (!result.Result) throw new Exception(result.Message); MailGroup group = new MailGroup(); group.Name = groupName; group.Members = result.AliasInfo.Addresses; group.Enabled = true; // by default return group; } catch (Exception ex) { throw new Exception("Could not get mail domain group", ex); } } public virtual void CreateGroup(MailGroup group) { try { svcAliasAdmin svcGroups = new svcAliasAdmin(); PrepareProxy(svcGroups); GenericResult1 result = svcGroups.AddAlias(AdminUsername, AdminPassword, GetDomainName(group.Name), group.Name, group.Members); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not create mail domain group", ex); } } public virtual void UpdateGroup(MailGroup group) { try { svcAliasAdmin svcGroups = new svcAliasAdmin(); PrepareProxy(svcGroups); GenericResult1 result = svcGroups.UpdateAlias(AdminUsername, AdminPassword, GetDomainName(group.Name), group.Name, group.Members); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not update mail domain group", ex); } } public virtual void DeleteGroup(string groupName) { try { svcAliasAdmin svcGroups = new svcAliasAdmin(); PrepareProxy(svcGroups); GenericResult1 result = svcGroups.DeleteAlias(AdminUsername, AdminPassword, GetDomainName(groupName), groupName); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not delete mail domain group", ex); } } #endregion #region Mailboxes public virtual bool AccountExists(string mailboxName) { try { svcUserAdmin users = new svcUserAdmin(); PrepareProxy(users); UserInfoResult result = users.GetUser(AdminUsername, AdminPassword, mailboxName); return result.Result; } catch (Exception ex) { throw new Exception("Could not check whether mailbox exists", ex); } } /// <summary> /// Returns all users that belong to the specified domain /// </summary> /// <param name="domainName">Domain name</param> /// <returns>Array with user names</returns> public virtual MailAccount[] GetAccounts(string domainName) { try { svcUserAdmin users = new svcUserAdmin(); PrepareProxy(users); UserInfoListResult result = users.GetUsers(AdminUsername, AdminPassword, domainName); if (!result.Result) throw new Exception(result.Message); List<MailAccount> accounts = new List<MailAccount>(); foreach (UserInfo user in result.Users) { if (user.IsDomainAdmin && !ImportDomainAdmin) continue; MailAccount account = new MailAccount(); account.Name = user.UserName; account.Password = user.Password; accounts.Add(account); } return accounts.ToArray(); } catch (Exception ex) { throw new Exception("Could not get the list of domain mailboxes", ex); } } public virtual MailAccount GetAccount(string mailboxName) { try { svcUserAdmin users = new svcUserAdmin(); PrepareProxy(users); UserInfoResult result = users.GetUser(AdminUsername, AdminPassword, mailboxName); if (!result.Result) throw new Exception(result.Message); MailAccount mailbox = new MailAccount(); mailbox.Name = result.UserInfo.UserName; mailbox.Password = result.UserInfo.Password; mailbox.FirstName = result.UserInfo.FirstName; mailbox.LastName = result.UserInfo.LastName; mailbox.IsDomainAdmin = result.UserInfo.IsDomainAdmin; // get additional settings string[] requestedSettings = new string[] { "isenabled", "maxsize", "passwordlocked", "replytoaddress", "signature" }; SettingsRequestResult addResult = users.GetRequestedUserSettings(AdminUsername, AdminPassword, mailboxName, requestedSettings); if (!addResult.Result) throw new Exception(addResult.Message); foreach (string pair in addResult.settingValues) { string[] parts = pair.Split('='); if (parts[0] == "isenabled") mailbox.Enabled = Boolean.Parse(parts[1]); else if (parts[0] == "maxsize") mailbox.MaxMailboxSize = Int32.Parse(parts[1]); else if (parts[0] == "passwordlocked") mailbox.PasswordLocked = Boolean.Parse(parts[1]); else if (parts[0] == "replytoaddress") mailbox.ReplyTo = parts[1]; else if (parts[0] == "signature") mailbox.Signature = parts[1]; } // get forwardings info UserForwardingInfoResult forwResult = users.GetUserForwardingInfo(AdminUsername, AdminPassword, mailboxName); if (!forwResult.Result) throw new Exception(forwResult.Message); string[] forwAddresses = forwResult.ForwardingAddress.Split(';', ','); List<string> listForAddresses = new List<string>(); foreach (string forwAddress in forwAddresses) { if (!String.IsNullOrEmpty(forwAddress.Trim())) listForAddresses.Add(forwAddress.Trim()); } mailbox.ForwardingAddresses = listForAddresses.ToArray(); mailbox.DeleteOnForward = forwResult.DeleteOnForward; // get autoresponder info UserAutoResponseResult respResult = users.GetUserAutoResponseInfo(AdminUsername, AdminPassword, mailboxName); if (!respResult.Result) throw new Exception(respResult.Message); mailbox.ResponderEnabled = respResult.Enabled; mailbox.ResponderSubject = respResult.Subject; mailbox.ResponderMessage = respResult.Body; return mailbox; } catch (Exception ex) { throw new Exception("Could not get mailbox", ex); } } public virtual void CreateAccount(MailAccount mailbox) { try { svcUserAdmin users = new svcUserAdmin(); PrepareProxy(users); GenericResult1 result = users.AddUser(AdminUsername, AdminPassword, mailbox.Name, mailbox.Password, GetDomainName(mailbox.Name), mailbox.FirstName, mailbox.LastName, false // domain admin is false ); if (!result.Result) throw new Exception(result.Message); // set additional settings result = users.SetRequestedUserSettings(AdminUsername, AdminPassword, mailbox.Name, new string[] { "isenabled=" + mailbox.Enabled, "maxsize=" + (mailbox.MaxMailboxSize), "passwordlocked=" + mailbox.PasswordLocked, "replytoaddress=" + (mailbox.ReplyTo ?? ""), "signature=" + (mailbox.Signature ?? "") }); if (!result.Result) throw new Exception(result.Message); // set forwarding settings result = users.UpdateUserForwardingInfo(AdminUsername, AdminPassword, mailbox.Name, mailbox.DeleteOnForward, (mailbox.ForwardingAddresses != null ? String.Join(", ", mailbox.ForwardingAddresses) : "")); if (!result.Result) throw new Exception(result.Message); // set autoresponder settings result = users.UpdateUserAutoResponseInfo(AdminUsername, AdminPassword, mailbox.Name, mailbox.ResponderEnabled, (mailbox.ResponderSubject ?? ""), (mailbox.ResponderMessage ?? "")); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not create mailbox", ex); } } public virtual void UpdateAccount(MailAccount mailbox) { try { //get original account MailAccount account = GetAccount(mailbox.Name); svcUserAdmin users = new svcUserAdmin(); PrepareProxy(users); GenericResult1 result = users.UpdateUser(AdminUsername, AdminPassword, mailbox.Name, mailbox.Password, mailbox.FirstName, mailbox.LastName, account.IsDomainAdmin ); if (!result.Result) throw new Exception(result.Message); // set additional settings result = users.SetRequestedUserSettings(AdminUsername, AdminPassword, mailbox.Name, new string[] { "isenabled=" + mailbox.Enabled, "maxsize=" + (mailbox.MaxMailboxSize), "passwordlocked=" + mailbox.PasswordLocked, "replytoaddress=" + (mailbox.ReplyTo ?? ""), "signature=" + (mailbox.Signature ?? "") }); if (!result.Result) throw new Exception(result.Message); // set forwarding settings result = users.UpdateUserForwardingInfo(AdminUsername, AdminPassword, mailbox.Name, mailbox.DeleteOnForward, (mailbox.ForwardingAddresses != null ? String.Join(", ", mailbox.ForwardingAddresses) : "")); if (!result.Result) throw new Exception(result.Message); // set autoresponder settings result = users.UpdateUserAutoResponseInfo(AdminUsername, AdminPassword, mailbox.Name, mailbox.ResponderEnabled, (mailbox.ResponderSubject ?? ""), (mailbox.ResponderMessage ?? "")); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not update mailbox", ex); } } public virtual void DeleteAccount(string mailboxName) { try { svcUserAdmin users = new svcUserAdmin(); PrepareProxy(users); GenericResult1 result = users.DeleteUser(AdminUsername, AdminPassword, mailboxName, GetDomainName(mailboxName)); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not delete mailbox", ex); } } #endregion #region Mail Aliases public bool MailAliasExists(string mailAliasName) { try { svcAliasAdmin aliases = new svcAliasAdmin(); PrepareProxy(aliases); AliasInfoResult result = aliases.GetAlias(AdminUsername, AdminPassword, GetDomainName(mailAliasName), mailAliasName); if ((result.AliasInfo.Name.Equals("Empty")) && (result.AliasInfo.Addresses.Length == 0)) return false; return true; } catch (Exception ex) { throw new Exception("Could not check whether mail alias exists", ex); } } public MailAlias[] GetMailAliases(string domainName) { try { svcAliasAdmin aliases = new svcAliasAdmin(); PrepareProxy(aliases); AliasInfoListResult result = aliases.GetAliases(AdminUsername, AdminPassword, domainName); if (!result.Result) throw new Exception(result.Message); List<MailAlias> aliasesList = new List<MailAlias>(); foreach (AliasInfo alias in result.AliasInfos) { if (alias.Addresses.Length == 1) { MailAlias mailAlias = new MailAlias(); mailAlias.Name = alias.Name + "@" + domainName; mailAlias.ForwardTo = alias.Addresses[0]; aliasesList.Add(mailAlias); } } return aliasesList.ToArray(); } catch (Exception ex) { throw new Exception("Could not get the list of mail aliases", ex); } } public MailAlias GetMailAlias(string mailAliasName) { svcAliasAdmin aliases = new svcAliasAdmin(); PrepareProxy(aliases); MailAlias alias = new MailAlias(); MailAlias newAlias = new MailAlias(); //convert old alliases created as mailboxes if (!MailAliasExists(mailAliasName)) { MailAccount account = GetAccount(mailAliasName); newAlias.Name = account.Name; newAlias.ForwardTo = account.ForwardingAddresses[0]; DeleteAccount(mailAliasName); CreateMailAlias(newAlias); return newAlias; } AliasInfoResult result = aliases.GetAlias(AdminUsername, AdminPassword, GetDomainName(mailAliasName), mailAliasName); alias.Name = result.AliasInfo.Name; alias.ForwardTo = result.AliasInfo.Addresses[0]; return alias; } public void CreateMailAlias(MailAlias mailAlias) { try { svcAliasAdmin aliases = new svcAliasAdmin(); PrepareProxy(aliases); GenericResult1 result = aliases.AddAlias(AdminUsername, AdminPassword, GetDomainName(mailAlias.Name), mailAlias.Name, new string[] { mailAlias.ForwardTo }); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { if (MailAliasExists(mailAlias.Name)) { DeleteMailAlias(mailAlias.Name); } Log.WriteError(ex); throw new Exception("Could not create mail alias", ex); } } public void UpdateMailAlias(MailAlias mailAlias) { try { svcAliasAdmin aliases = new svcAliasAdmin(); PrepareProxy(aliases); GenericResult1 result = aliases.UpdateAlias(AdminUsername, AdminPassword, GetDomainName(mailAlias.Name), mailAlias.Name, new string[] { mailAlias.ForwardTo }); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not update mailAlias", ex); } } public void DeleteMailAlias(string mailAliasName) { try { svcAliasAdmin aliases = new svcAliasAdmin(); PrepareProxy(aliases); GenericResult1 result = aliases.DeleteAlias(AdminUsername, AdminPassword, GetDomainName(mailAliasName), mailAliasName); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not delete mailAlias", ex); } } #endregion #region Mailing lists public virtual bool ListExists(string listName) { try { WebsitePanelMailListAdmin svcLists = new WebsitePanelMailListAdmin(); PrepareProxy(svcLists); GenericResult result = svcLists.MailingListExists(AdminUsername, AdminPassword, listName); return result.Result; } catch (Exception ex) { throw new Exception("Could not check whether mailing list exists", ex); } } public virtual MailList[] GetLists(string domainName) { try { WebsitePanelMailListAdmin svcLists = new WebsitePanelMailListAdmin(); PrepareProxy(svcLists); MailingListsResult result = svcLists.GetMailingLists(AdminUsername, AdminPassword, domainName); if (!result.Result) throw new Exception(result.Message); List<MailList> items = new List<MailList>(); foreach (MailingListInfo listInfo in result.MailingLists) { MailList item = new MailList(); item.Name = listInfo.Name; item.Description = listInfo.Description; } return items.ToArray(); } catch (Exception ex) { throw new Exception("Could not get mail list", ex); } } public virtual MailList GetList(string listName) { try { WebsitePanelMailListAdmin svcLists = new WebsitePanelMailListAdmin(); PrepareProxy(svcLists); MailingListResult result = svcLists.GetMailingList(AdminUsername, AdminPassword, listName); if (!result.Result) throw new Exception(result.Message); MailList item = new MailList(); item.Description = result.MailingList.Description; item.EnableSubjectPrefix = result.MailingList.EnableSubjectPrefix; item.SubjectPrefix = result.MailingList.SubjectPrefix; item.Enabled = true; item.MaxMessageSize = result.MailingList.MaxMessageSize; item.MaxRecipientsPerMessage = result.MailingList.MaxRecipientsPerMessage; item.Members = result.MailingList.Members ?? new string[] { }; item.Moderated = !String.IsNullOrEmpty(result.MailingList.ModeratorAddress); item.ModeratorAddress = result.MailingList.ModeratorAddress; item.Name = result.MailingList.Name; item.Password = result.MailingList.Password; item.RequirePassword = result.MailingList.RequirePassword; // post mode PostingMode postMode = PostingMode.AnyoneCanPost; if (result.MailingList.PostingMode == MailListPostOptions.ModeratorOnly) postMode = PostingMode.ModeratorCanPost; else if (result.MailingList.PostingMode == MailListPostOptions.SubscribersOnly) postMode = PostingMode.MembersCanPost; item.PostingMode = postMode; item.ReplyToMode = result.MailingList.ReplyToList ? ReplyTo.RepliesToList : ReplyTo.RepliesToSender; return item; } catch (Exception ex) { throw new Exception("Could not get mail list", ex); } } public virtual void CreateList(MailList list) { try { WebsitePanelMailListAdmin svcLists = new WebsitePanelMailListAdmin(); PrepareProxy(svcLists); MailListPostOptions postMode = MailListPostOptions.Anyone; if (list.PostingMode == PostingMode.MembersCanPost) postMode = MailListPostOptions.SubscribersOnly; if (list.PostingMode == PostingMode.ModeratorCanPost) postMode = MailListPostOptions.ModeratorOnly; GenericResult result = svcLists.AddMailingList(AdminUsername, AdminPassword, GetDomainName(list.Name), GetAccountName(list.Name), list.ModeratorAddress, list.Description, list.MaxMessageSize, list.MaxRecipientsPerMessage, list.EnableSubjectPrefix, list.SubjectPrefix, list.Members, postMode, (list.ReplyToMode == ReplyTo.RepliesToList), list.Password, list.RequirePassword); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not create mail list", ex); } } public virtual void UpdateList(MailList list) { try { WebsitePanelMailListAdmin svcLists = new WebsitePanelMailListAdmin(); PrepareProxy(svcLists); MailListPostOptions postMode = MailListPostOptions.Anyone; if (list.PostingMode == PostingMode.MembersCanPost) postMode = MailListPostOptions.SubscribersOnly; if (list.PostingMode == PostingMode.ModeratorCanPost) postMode = MailListPostOptions.ModeratorOnly; GenericResult result = svcLists.UpdateMailingList(AdminUsername, AdminPassword, list.Name, list.ModeratorAddress, list.Description, list.MaxMessageSize, list.MaxRecipientsPerMessage, list.EnableSubjectPrefix, list.SubjectPrefix, list.Members, postMode, (list.ReplyToMode == ReplyTo.RepliesToList), list.Password, list.RequirePassword); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not update mail list", ex); } } /// <summary> /// Deletes specified mail list. /// </summary> /// <param name="listName">Mail list name.</param> public virtual void DeleteList(string listName) { try { WebsitePanelMailListAdmin svcLists = new WebsitePanelMailListAdmin(); PrepareProxy(svcLists); GenericResult result = svcLists.DeleteMailingList(AdminUsername, AdminPassword, listName); if (!result.Result) throw new Exception(result.Message); } catch (Exception ex) { throw new Exception("Could not delete mail list", ex); } } #endregion #region IHostingServiceProvier methods public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled) { foreach (ServiceProviderItem item in items) { if (item is MailDomain) { try { // enable/disable mail domain if (DomainExists(item.Name)) { MailDomain mailDomain = GetDomain(item.Name); mailDomain.Enabled = enabled; UpdateDomain(mailDomain); } } catch(Exception ex) { Log.WriteError(String.Format("Error switching '{0}' SmarterMail domain", item.Name), ex); } } } } public override void DeleteServiceItems(ServiceProviderItem[] items) { foreach (ServiceProviderItem item in items) { if (item is MailDomain) { try { // delete mail domain DeleteDomain(item.Name); } catch (Exception ex) { Log.WriteError(String.Format("Error deleting '{0}' SmarterMail domain", item.Name), ex); } } } } public override ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items) { List<ServiceProviderItemDiskSpace> itemsDiskspace = new List<ServiceProviderItemDiskSpace>(); // update items with diskspace foreach (ServiceProviderItem item in items) { if (item is MailAccount) { try { // get mailbox size string name = item.Name; // try to get SmarterMail postoffices path string poPath = DomainsPath; if (poPath == null) continue; string mailboxName = name.Substring(0, name.IndexOf("@")); string domainName = name.Substring(name.IndexOf("@") + 1); string mailboxPath = Path.Combine(DomainsPath, String.Format("{0}\\Users\\{1}", domainName, mailboxName)); Log.WriteStart(String.Format("Calculating '{0}' folder size", mailboxPath)); // calculate disk space ServiceProviderItemDiskSpace diskspace = new ServiceProviderItemDiskSpace(); diskspace.ItemId = item.Id; //diskspace.DiskSpace = 0; diskspace.DiskSpace = FileUtils.CalculateFolderSize(mailboxPath); itemsDiskspace.Add(diskspace); Log.WriteEnd(String.Format("Calculating '{0}' folder size", mailboxPath)); } catch (Exception ex) { Log.WriteError(ex); } } } return itemsDiskspace.ToArray(); } public override ServiceProviderItemBandwidth[] GetServiceItemsBandwidth(ServiceProviderItem[] items, DateTime since) { ServiceProviderItemBandwidth[] itemsBandwidth = new ServiceProviderItemBandwidth[items.Length]; // update items with diskspace for (int i = 0; i < items.Length; i++) { ServiceProviderItem item = items[i]; // create new bandwidth object itemsBandwidth[i] = new ServiceProviderItemBandwidth(); itemsBandwidth[i].ItemId = item.Id; itemsBandwidth[i].Days = new DailyStatistics[0]; if (item is MailDomain) { try { // get daily statistics itemsBandwidth[i].Days = GetDailyStatistics(since, item.Name); } catch (Exception ex) { Log.WriteError(ex); System.Diagnostics.Debug.WriteLine(ex); } } } return itemsBandwidth; } public DailyStatistics[] GetDailyStatistics(DateTime since, string maildomainName) { ArrayList days = new ArrayList(); // read statistics DateTime now = DateTime.Now; DateTime date = since; try { while (date < now) { svcDomainAdmin domains = new svcDomainAdmin(); PrepareProxy(domains); StatInfoResult result = domains.GetDomainStatistics(AdminUsername, AdminPassword, maildomainName, date, date); if (!result.Result) throw new Exception(result.Message); if (result.BytesReceived != 0 | result.BytesSent != 0) { DailyStatistics dailyStats = new DailyStatistics(); dailyStats.Year = date.Year; dailyStats.Month = date.Month; dailyStats.Day = date.Day; dailyStats.BytesSent = result.BytesSent; dailyStats.BytesReceived = result.BytesReceived; days.Add(dailyStats); } // advance day date = date.AddDays(1); } } catch(Exception ex) { Log.WriteError("Could not get SmarterMail domain statistics", ex); } return (DailyStatistics[])days.ToArray(typeof(DailyStatistics)); } #endregion #region Helper Members protected void PrepareProxy(SoapHttpClientProtocol proxy) { string smarterUrl = ServiceUrl; int idx = proxy.Url.LastIndexOf("/"); // strip the last slash if any if (smarterUrl[smarterUrl.Length - 1] == '/') smarterUrl = smarterUrl.Substring(0, smarterUrl.Length - 1); proxy.Url = smarterUrl + proxy.Url.Substring(idx); } protected string GetDomainName(string email) { return email.Substring(email.IndexOf('@') + 1); } protected string GetAccountName(string email) { return email.Substring(0, email.IndexOf('@')); } #endregion ///<summary> /// /// Checks whether service is installed within the system. This method will be /// used by server creation wizard for automatic services detection and configuring. /// ///</summary> /// ///<returns> ///True if service is installed; otherwise - false. ///</returns> /// public override bool IsInstalled() { string productName = null; string productVersion = null; RegistryKey HKLM = Registry.LocalMachine; RegistryKey key = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"); String[] names = null; if (key != null) { names = key.GetSubKeyNames(); foreach (string s in names) { RegistryKey subkey = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + s); if (subkey != null) if (!String.IsNullOrEmpty((string)subkey.GetValue("DisplayName"))) { productName = (string)subkey.GetValue("DisplayName"); } if (productName != null) if (productName.Equals("SmarterMail")) { if (subkey != null) productVersion = (string)subkey.GetValue("DisplayVersion"); break; } } if (!String.IsNullOrEmpty(productVersion)) { string[] split = productVersion.Split(new char[] { '.' }); return split[0].Equals("2"); } } else { key = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"); if (key == null) { return false; } names = key.GetSubKeyNames(); foreach (string s in names) { RegistryKey subkey = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" + s); if (subkey != null) if (!String.IsNullOrEmpty((string)subkey.GetValue("DisplayName"))) { productName = (string)subkey.GetValue("DisplayName"); } if (productName != null) if (productName.Equals("SmarterMail")) { if (subkey != null) productVersion = (string)subkey.GetValue("DisplayVersion"); break; } } if (!String.IsNullOrEmpty(productVersion)) { string[] split = productVersion.Split(new[] { '.' }); return split[0].Equals("2"); } } return false; } } }
//----------------------------------------------------------------------------- // Torque // Copyright GarageGames, LLC 2011 //----------------------------------------------------------------------------- // RocketLauncher weapon. // This script file contains all of the necessary datablocks needed for the // RocketLauncher. These datablocks include sound profiles, light descriptions, // particle effects, explosions, projectiles, items (weapon and ammo), shell // casings (if any), and finally the weapon image which contains the state // machine that determines how the weapon operates. // The main "fire" method/mode is handled in "../scripts/server/weapons.cs" // through a "WeaponImage" namespace function. This reduces duplicated code, // although a unique fire method could still be implemented for this weapon. // The "alt-fire" method/mode is handled in "../scripts/server/rocketlaucner.cs". // Alt-fire for the Rocketlauncher allows you to "charge up" the number of // projectiles, up to 3, that get fired. Hold to increase the number of shots // and release to fire. After three shots are loaded and in the pipe, the // weapon will automatically discharge on it's own. // ---------------------------------------------------------------------------- // Sound profiles // ---------------------------------------------------------------------------- datablock SFXProfile(RocketLauncherReloadSound) { filename = "art/sound/weapons/Crossbow_reload"; description = AudioClose3d; preload = true; }; datablock SFXProfile(RocketLauncherFireSound) { filename = "art/sound/weapons/explosion_mono_01"; description = AudioClose3d; preload = true; }; datablock SFXProfile(RocketLauncherIncLoadSound) { filename = "art/sound/weapons/relbow_mono_01"; description = AudioClose3d; preload = true; }; datablock SFXProfile(RocketLauncherFireEmptySound) { filename = "art/sound/weapons/Crossbow_firing_empty"; description = AudioClose3d; preload = true; }; datablock SFXProfile(RocketLauncherExplosionSound) { filename = "art/sound/weapons/Crossbow_explosion"; description = AudioDefault3d; preload = true; }; // ---------------------------------------------------------------------------- // Lights for the projectile(s) // ---------------------------------------------------------------------------- datablock LightDescription(RocketLauncherLightDesc) { range = 4.0; color = "1 1 0"; brightness = 5.0; animationType = PulseLightAnim; animationPeriod = 0.25; //flareType = SimpleLightFlare0; }; datablock LightDescription(RocketLauncherWaterLightDesc) { radius = 2.0; color = "1 1 1"; brightness = 5.0; animationType = PulseLightAnim; animationPeriod = 0.25; //flareType = SimpleLightFlare0; }; //---------------------------------------------------------------------------- // Debris //---------------------------------------------------------------------------- datablock ParticleData(RocketDebrisTrailParticle) { textureName = "art/shapes/particles/impact"; dragCoeffiecient = 0; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 1200;//1000; lifetimeVarianceMS = 299;//500; useInvAlpha = true;//false; spinSpeed = 1; spinRandomMin = -300.0; spinRandomMax = 0; colors[0] = "1 0.897638 0.795276 0.4"; colors[1] = "0.795276 0.795276 0.795276 0.6"; colors[2] = "0 0 0 0"; sizes[0] = 0.5;//1.0; sizes[1] = 2; sizes[2] = 1;//1.0; times[0] = 0.0; times[1] = 0.498039; times[2] = 1.0; animTexName = "art/shapes/particles/impact"; times[3] = "1"; }; datablock ParticleEmitterData(RocketDebrisTrailEmitter) { ejectionPeriodMS = 6;//8; periodVarianceMS = 2;//4; ejectionVelocity = 1.0; velocityVariance = 0.5; thetaMin = 0.0; thetaMax = 180.0; phiReferenceVel = 0; phiVariance = 360; ejectionoffset = 0.0;//0.3; particles = "RocketDebrisTrailParticle"; }; datablock DebrisData(RocketDebris) { shapeFile = "art/shapes/weapons/SwarmGun/rocket.dts"; emitters[0] = RocketDebrisTrailEmitter; elasticity = 0.5; friction = 0.5; numBounces = 1;//2; bounceVariance = 1; explodeOnMaxBounce = true; staticOnMaxBounce = false; snapOnMaxBounce = false; minSpinSpeed = 400; maxSpinSpeed = 800; render2D = false; lifetime = 0.25;//0.5;//1;//2; lifetimeVariance = 0.0;//0.25;//0.5; velocity = 35;//30;//15; velocityVariance = 10;//5; fade = true; useRadiusMass = true; baseRadius = 0.3; gravModifier = 1.0; terminalVelocity = 45; ignoreWater = false; }; // ---------------------------------------------------------------------------- // Splash effects // ---------------------------------------------------------------------------- datablock ParticleData(RocketSplashMist) { dragCoefficient = 1.0; windCoefficient = 2.0; gravityCoefficient = 0.3; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 600; lifetimeVarianceMS = 100; useInvAlpha = false; spinRandomMin = -90.0; spinRandomMax = 500.0; spinSpeed = 1; textureName = "art/shapes/particles/smoke"; colors[0] = "0.7 0.8 1.0 1.0"; colors[1] = "0.7 0.8 1.0 0.5"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.2;//0.5; sizes[1] = 0.4;//0.5; sizes[2] = 0.8; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(RocketSplashMistEmitter) { ejectionPeriodMS = 5; periodVarianceMS = 0; ejectionVelocity = 3.0; velocityVariance = 2.0; ejectionOffset = 0.15; thetaMin = 85; thetaMax = 85; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; lifetimeMS = 250; particles = "RocketSplashMist"; }; datablock ParticleData(RocketSplashParticle) { dragCoefficient = 1; windCoefficient = 0.9; gravityCoefficient = 0.3; inheritedVelFactor = 0.2; constantAcceleration = -1.4; lifetimeMS = 600; lifetimeVarianceMS = 200; textureName = "art/shapes/particles/droplet"; colors[0] = "0.7 0.8 1.0 1.0"; colors[1] = "0.7 0.8 1.0 0.5"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.5; sizes[1] = 0.25; sizes[2] = 0.25; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(RocketSplashEmitter) { ejectionPeriodMS = 4; periodVarianceMS = 0; ejectionVelocity = 7.3; velocityVariance = 2.0; ejectionOffset = 0.0; thetaMin = 30; thetaMax = 80; phiReferenceVel = 00; phiVariance = 360; overrideAdvance = false; orientParticles = true; orientOnVelocity = true; lifetimeMS = 100; particles = "RocketSplashParticle"; }; datablock ParticleData(RocketSplashRingParticle) { textureName = "art/shapes/particles/wake"; dragCoefficient = 0.0; gravityCoefficient = 0.0; inheritedVelFactor = 0.0; lifetimeMS = 2500; lifetimeVarianceMS = 200; windCoefficient = 0.0; useInvAlpha = 1; spinRandomMin = 30.0; spinRandomMax = 30.0; spinSpeed = 1; animateTexture = true; framesPerSec = 1; animTexTiling = "2 1"; animTexFrames = "0 1"; colors[0] = "0.7 0.8 1.0 1.0"; colors[1] = "0.7 0.8 1.0 0.5"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 2.0; sizes[1] = 4.0; sizes[2] = 8.0; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(RocketSplashRingEmitter) { lifetimeMS = "100"; ejectionPeriodMS = 200; periodVarianceMS = 10; ejectionVelocity = 0; velocityVariance = 0; ejectionOffset = 0; thetaMin = 89; thetaMax = 90; phiReferenceVel = 0; phiVariance = 1; alignParticles = 1; alignDirection = "0 0 1"; particles = "RocketSplashRingParticle"; }; datablock SplashData(RocketSplash) { // numSegments = 15; // ejectionFreq = 15; // ejectionAngle = 40; // ringLifetime = 0.5; // lifetimeMS = 300; // velocity = 4.0; // startRadius = 0.0; // acceleration = -3.0; // texWrap = 5.0; // texture = "art/shapes/particles/splash"; emitter[0] = RocketSplashEmitter; emitter[1] = RocketSplashMistEmitter; emitter[2] = RocketSplashRingEmitter; // colors[0] = "0.7 0.8 1.0 0.0"; // colors[1] = "0.7 0.8 1.0 0.3"; // colors[2] = "0.7 0.8 1.0 0.7"; // colors[3] = "0.7 0.8 1.0 0.0"; // // times[0] = 0.0; // times[1] = 0.4; // times[2] = 0.8; // times[3] = 1.0; }; // ---------------------------------------------------------------------------- // Explosion Particle effects // ---------------------------------------------------------------------------- datablock ParticleData(RocketExpFire) { gravityCoefficient = "-0.50061"; lifetimeMS = "400"; lifetimeVarianceMS = "299"; spinSpeed = "1"; spinRandomMin = "-200"; spinRandomMax = "0"; textureName = "art/shapes/particles/smoke"; animTexName = "art/shapes/particles/smoke"; colors[0] = "1 0.897638 0.795276 1"; colors[1] = "0.795276 0.393701 0 0.6"; colors[2] = "0 0 0 0"; sizes[0] = "1.99902"; sizes[1] = "7.99915"; sizes[2] = "3.99805"; times[1] = "0.392157"; times[2] = "1"; times[3] = "1"; }; datablock ParticleEmitterData(RocketExpFireEmitter) { ejectionPeriodMS = "10"; periodVarianceMS = "5"; ejectionVelocity = "3"; velocityVariance = "2"; particles = "RocketExpFire"; blendStyle = "NORMAL"; }; datablock ParticleData(RocketExpFireball) { textureName = "art/shapes/particles/fireball.png"; lifetimeMS = "300"; lifetimeVarianceMS = "299"; spinSpeed = "1"; spinRandomMin = "-400"; spinRandomMax = "0"; animTexName = "art/shapes/particles/fireball.png"; colors[0] = "1 0.897638 0.795276 0.2"; colors[1] = "1 0.496063 0 0.6"; colors[2] = "0.0944882 0.0944882 0.0944882 0"; sizes[0] = "0.997986"; sizes[1] = "1.99902"; sizes[2] = "2.99701"; times[1] = "0.498039"; times[2] = "1"; times[3] = "1"; gravityCoefficient = "-1"; }; datablock ParticleEmitterData(RocketExpFireballEmitter) { particles = "RocketExpFireball"; blendStyle = "ADDITIVE"; ejectionPeriodMS = "10"; periodVarianceMS = "5"; ejectionVelocity = "4"; velocityVariance = "2"; ejectionOffset = "2"; thetaMax = "120"; }; datablock ParticleData(RocketExpSmoke) { lifetimeMS = 1200;//"1250"; lifetimeVarianceMS = 299;//200;//"250"; textureName = "art/shapes/particles/smoke"; animTexName = "art/shapes/particles/smoke"; useInvAlpha = "1"; gravityCoefficient = "-0.100122"; spinSpeed = "1"; spinRandomMin = "-100"; spinRandomMax = "0"; colors[0] = "0.897638 0.795276 0.692913 0.4";//"0.192157 0.192157 0.192157 0.0944882"; colors[1] = "0.897638 0.897638 0.897638 0.8";//"0.454902 0.454902 0.454902 0.897638"; colors[2] = "0.4 0.4 0.4 0";//"1 1 1 0"; sizes[0] = "1.99597"; sizes[1] = "3.99805"; sizes[2] = "7.99915"; times[1] = "0.494118"; times[2] = "1"; times[3] = "1"; }; datablock ParticleEmitterData(RocketExpSmokeEmitter) { ejectionPeriodMS = "15"; periodVarianceMS = "5"; //ejectionOffset = "1"; thetaMax = "180"; particles = "RocketExpSmoke"; blendStyle = "NORMAL"; }; datablock ParticleData(RocketExpSparks) { textureName = "art/shapes/particles/droplet.png"; lifetimeMS = "100"; lifetimeVarianceMS = "50"; animTexName = "art/shapes/particles/droplet.png"; inheritedVelFactor = "0.391389"; sizes[0] = "1.99902"; sizes[1] = "2.49954"; sizes[2] = "0.997986"; colors[0] = "1.0 0.9 0.8 0.2"; colors[1] = "1.0 0.9 0.8 0.8"; colors[2] = "0.8 0.4 0.0 0.0"; times[0] = "0"; times[1] = "0.34902"; times[2] = "1"; times[3] = "1"; }; datablock ParticleEmitterData(RocketExpSparksEmitter) { particles = "RocketExpSparks"; blendStyle = "NORMAL"; ejectionPeriodMS = "10"; periodVarianceMS = "5"; ejectionVelocity = "60"; velocityVariance = "10"; thetaMax = "120"; phiReferenceVel = 0; phiVariance = "360"; ejectionOffset = "0"; orientParticles = true; orientOnVelocity = true; }; datablock ParticleData(RocketExpSubFireParticles) { textureName = "art/shapes/particles/fireball.png"; gravityCoefficient = "-0.202686"; lifetimeMS = "400"; lifetimeVarianceMS = "299"; spinSpeed = "1"; spinRandomMin = "-200"; spinRandomMax = "0"; animTexName = "art/shapes/particles/fireball.png"; colors[0] = "1 0.897638 0.795276 0.2"; colors[1] = "1 0.496063 0 1"; colors[2] = "0.0944882 0.0944882 0.0944882 0"; sizes[0] = "0.997986"; sizes[1] = "1.99902"; sizes[2] = "2.99701"; times[1] = "0.498039"; times[2] = "1"; times[3] = "1"; }; datablock ParticleEmitterData(RocketExpSubFireEmitter) { particles = "RocketExpSubFireParticles"; blendStyle = "ADDITIVE"; ejectionPeriodMS = "10"; periodVarianceMS = "5"; ejectionVelocity = "4"; velocityVariance = "2"; thetaMax = "120"; }; datablock ParticleData(RocketExpSubSmoke) { textureName = "art/shapes/particles/smoke"; gravityCoefficient = "-0.40293"; lifetimeMS = "800"; lifetimeVarianceMS = "299"; spinSpeed = "1"; spinRandomMin = "-200"; spinRandomMax = "0"; animTexName = "art/shapes/particles/smoke"; colors[0] = "0.4 0.35 0.3 0.393701"; colors[1] = "0.45 0.45 0.45 0.795276"; colors[2] = "0.4 0.4 0.4 0"; sizes[0] = "1.99902"; sizes[1] = "3.99805"; sizes[2] = "7.99915"; times[1] = "0.4"; times[2] = "1"; times[3] = "1"; }; datablock ParticleEmitterData(RocketExpSubSmokeEmitter) { particles = "RocketExpSubSmoke"; ejectionPeriodMS = "30"; periodVarianceMS = "10"; ejectionVelocity = "2"; velocityVariance = "1"; ejectionOffset = 1;//"2"; blendStyle = "NORMAL"; }; // ---------------------------------------------------------------------------- // Water Explosion // ---------------------------------------------------------------------------- datablock ParticleData(RLWaterExpDust) { textureName = "art/shapes/particles/steam"; dragCoefficient = 1.0; gravityCoefficient = -0.01; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 2500; lifetimeVarianceMS = 250; useInvAlpha = false; spinSpeed = 1; spinRandomMin = -90.0; spinRandomMax = 500.0; colors[0] = "0.6 0.6 1.0 0.5"; colors[1] = "0.6 0.6 1.0 0.3"; sizes[0] = 0.25; sizes[1] = 1.5; times[0] = 0.0; times[1] = 1.0; }; datablock ParticleEmitterData(RLWaterExpDustEmitter) { ejectionPeriodMS = 1; periodVarianceMS = 0; ejectionVelocity = 10; velocityVariance = 0.0; ejectionOffset = 0.0; thetaMin = 85; thetaMax = 85; phiReferenceVel = 0; phiVariance = 360; overrideAdvances = false; lifetimeMS = 75; particles = "RLWaterExpDust"; }; datablock ParticleData(RLWaterExpSparks) { textureName = "art/shapes/particles/spark_wet"; dragCoefficient = 1; gravityCoefficient = 0.0; inheritedVelFactor = 0.2; constantAcceleration = 0.0; lifetimeMS = 500; lifetimeVarianceMS = 250; colors[0] = "0.6 0.6 1.0 1.0"; colors[1] = "0.6 0.6 1.0 1.0"; colors[2] = "0.6 0.6 1.0 0.0"; sizes[0] = 0.5; sizes[1] = 0.5; sizes[2] = 0.75; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(RLWaterExpSparkEmitter) { ejectionPeriodMS = 2; periodVarianceMS = 0; ejectionVelocity = 12; velocityVariance = 6.75; ejectionOffset = 0.0; thetaMin = 0; thetaMax = 60; phiReferenceVel = 0; phiVariance = 360; overrideAdvances = false; orientParticles = true; lifetimeMS = 100; particles = "RLWaterExpSparks"; }; datablock ParticleData(RLWaterExpSmoke) { textureName = "art/shapes/particles/smoke"; dragCoeffiecient = 0.4; gravityCoefficient = -0.25; inheritedVelFactor = 0.025; constantAcceleration = -1.1; lifetimeMS = 1250; lifetimeVarianceMS = 0; useInvAlpha = false; spinSpeed = 1; spinRandomMin = -200.0; spinRandomMax = 200.0; colors[0] = "0.1 0.1 1.0 1.0"; colors[1] = "0.4 0.4 1.0 1.0"; colors[2] = "0.4 0.4 1.0 0.0"; sizes[0] = 2.0; sizes[1] = 6.0; sizes[2] = 2.0; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(RLWaterExpSmokeEmitter) { ejectionPeriodMS = 15; periodVarianceMS = 0; ejectionVelocity = 6.25; velocityVariance = 0.25; thetaMin = 0.0; thetaMax = 90.0; lifetimeMS = 250; particles = "RLWaterExpSmoke"; }; datablock ParticleData(RLWaterExpBubbles) { textureName = "art/shapes/particles/millsplash01"; dragCoefficient = 0.0; gravityCoefficient = -0.05; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 1500; lifetimeVarianceMS = 250; useInvAlpha = false; spinRandomMin = -100.0; spinRandomMax = 100.0; spinSpeed = 1; colors[0] = "0.7 0.8 1.0 0.0"; colors[1] = "0.7 0.8 1.0 0.4"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.2; sizes[1] = 0.4; sizes[2] = 0.8; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(RLWaterExpBubbleEmitter) { ejectionPeriodMS = 5; periodVarianceMS = 0; ejectionVelocity = 1.0; ejectionOffset = 3.0; velocityVariance = 0.5; thetaMin = 0; thetaMax = 80; phiReferenceVel = 0; phiVariance = 360; overrideAdvances = false; particles = "RLWaterExpBubbles"; }; datablock ExplosionData(RocketLauncherWaterExplosion) { //soundProfile = RLWaterExplosionSound; emitter[0] = RLWaterExpDustEmitter; emitter[1] = RLWaterExpSparkEmitter; emitter[2] = RLWaterExpSmokeEmitter; emitter[3] = RLWaterExpBubbleEmitter; shakeCamera = true; camShakeFreq = "10.0 11.0 9.0"; camShakeAmp = "20.0 20.0 20.0"; camShakeDuration = 1.5; camShakeRadius = 20.0; lightStartRadius = 20.0; lightEndRadius = 0.0; lightStartColor = "0.9 0.9 0.8"; lightEndColor = "0.6 0.6 1.0"; lightStartBrightness = 2.0; lightEndBrightness = 0.0; }; // ---------------------------------------------------------------------------- // Dry/Air Explosion Objects // ---------------------------------------------------------------------------- datablock ExplosionData(RocketSubExplosion) { lifeTimeMS = 100; offset = 0.4; emitter[0] = RocketExpSubFireEmitter; emitter[1] = RocketExpSubSmokeEmitter; }; datablock ExplosionData(RocketLauncherExplosion) { soundProfile = RocketLauncherExplosionSound; lifeTimeMS = 200; // I want a quick bang and dissipation, not a slow burn-out // Volume particles particleEmitter = RocketExpSmokeEmitter; particleDensity = 10;//20; particleRadius = 1;//2; // Point emission emitter[0] = RocketExpFireEmitter; emitter[1] = RocketExpSparksEmitter; emitter[2] = RocketExpSparksEmitter; emitter[3] = RocketExpFireballEmitter; // Sub explosion objects subExplosion[0] = RocketSubExplosion; // Camera Shaking shakeCamera = true; camShakeFreq = "10.0 11.0 9.0"; camShakeAmp = "15.0 15.0 15.0"; camShakeDuration = 1.5; camShakeRadius = 20; // Exploding debris debris = RocketDebris; debrisThetaMin = 0;//10; debrisThetaMax = 90;//80; debrisNum = 5; debrisNumVariance = 2; debrisVelocity = 1;//2; debrisVelocityVariance = 0.2;//0.5; lightStartRadius = 6.0; lightEndRadius = 0.0; lightStartColor = "1.0 0.7 0.2"; lightEndColor = "0.9 0.7 0.0"; lightStartBrightness = 2.5; lightEndBrightness = 0.0; lightNormalOffset = 3.0; }; // ---------------------------------------------------------------------------- // Underwater Rocket projectile trail // ---------------------------------------------------------------------------- datablock ParticleData(RocketTrailWaterParticle) { textureName = "art/shapes/particles/bubble"; dragCoefficient = 0.0; gravityCoefficient = 0.1; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 1500; lifetimeVarianceMS = 600; useInvAlpha = false; spinRandomMin = -100.0; spinRandomMax = 100.0; spinSpeed = 1; colors[0] = "0.7 0.8 1.0 1.0"; colors[1] = "0.7 0.8 1.0 0.4"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.05; sizes[1] = 0.05; sizes[2] = 0.05; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(RocketTrailWaterEmitter) { ejectionPeriodMS = 5; periodVarianceMS = 0; ejectionVelocity = 1.0; ejectionOffset = 0.1; velocityVariance = 0.5; thetaMin = 0.0; thetaMax = 80.0; phiReferenceVel = 0; phiVariance = 360; overrideAdvances = false; particles = RocketTrailWaterParticle; }; // ---------------------------------------------------------------------------- // Normal-fire Projectile Object // ---------------------------------------------------------------------------- datablock ParticleData(RocketProjSmokeTrail) { textureName = "art/shapes/particles/smoke"; dragCoeffiecient = 0; gravityCoefficient = -0.202686; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 750; lifetimeVarianceMS = 749; useInvAlpha = true; spinRandomMin = -60; spinRandomMax = 0; spinSpeed = 1; colors[0] = "0.3 0.3 0.3 0.598425"; colors[1] = "0.9 0.9 0.9 0.897638"; colors[2] = "0.9 0.9 0.9 0"; sizes[0] = 0.247207; sizes[1] = 0.497467; sizes[2] = 0.747726; times[0] = 0.0; times[1] = 0.4; times[2] = 1.0; animTexName = "art/shapes/particles/smoke"; times[3] = "1"; }; datablock ParticleEmitterData(RocketProjSmokeTrailEmitter) { ejectionPeriodMS = 1; periodVarianceMS = 0; ejectionVelocity = 0.75; velocityVariance = 0; thetaMin = 0.0; thetaMax = 0.0; phiReferenceVel = 90; phiVariance = 0; particles = "RocketProjSmokeTrail"; }; datablock ProjectileData(RocketLauncherProjectile) { projectileShapeName = "art/shapes/weapons/SwarmGun/rocket.dts"; directDamage = 30; radiusDamage = 30; damageRadius = 5; areaImpulse = 2500; explosion = RocketLauncherExplosion; waterExplosion = RocketLauncherWaterExplosion; decal = ScorchRXDecal; splash = RocketSplash; particleEmitter = RocketProjSmokeTrailEmitter; particleWaterEmitter = RocketTrailWaterEmitter; muzzleVelocity = 100; velInheritFactor = 0.3; armingDelay = 0; lifetime = 5000; //(500m / 100m/s = 5000ms) fadeDelay = 4500; bounceElasticity = 0; bounceFriction = 0; isBallistic = false; gravityMod = 0.80; lightDesc = RocketLauncherLightDesc; damageType = "RocketDamage"; }; // ---------------------------------------------------------------------------- // Underwater Projectile // ---------------------------------------------------------------------------- datablock ProjectileData(RocketWetProjectile) { projectileShapeName = "art/shapes/weapons/SwarmGun/rocket.dts"; directDamage = 20; radiusDamage = 10; damageRadius = 10; areaImpulse = 2000; explosion = RocketLauncherWaterExplosion; particleEmitter = RocketProjSmokeTrailEmitter; particleWaterEmitter = RocketTrailWaterEmitter; muzzleVelocity = 20; velInheritFactor = 0.3; armingDelay = 0; lifetime = 5000; //(500m / 100m/s = 5000ms) fadeDelay = 4500; bounceElasticity = 0.2; bounceFriction = 0.4; isBallistic = true; gravityMod = 0.80; lightDesc = RocketLauncherWaterLightDesc; damageType = "RocketDamage"; }; // ---------------------------------------------------------------------------- // Shell that's ejected during reload. // ---------------------------------------------------------------------------- datablock DebrisData(RocketlauncherShellCasing) { shapeFile = "art/shapes/weapons/SwarmGun/rocket.dts"; lifetime = 6.0; minSpinSpeed = 300.0; maxSpinSpeed = 400.0; elasticity = 0.65; friction = 0.05; numBounces = 5; staticOnMaxBounce = true; snapOnMaxBounce = false; fade = true; }; // ---------------------------------------------------------------------------- // Particle Emitter played when firing. // ---------------------------------------------------------------------------- datablock ParticleData(RocketLauncherfiring1Particle) { textureName = "art/shapes/particles/fireball"; dragCoefficient = 100.0; gravityCoefficient = -0.25;//-0.5;//0.0; inheritedVelFactor = 0.25;//1.0; constantAcceleration = 0.1; lifetimeMS = 400; lifetimeVarianceMS = 100; useInvAlpha = false; spinSpeed = 1; spinRandomMin = -200; spinRandomMax = 200; colors[0] = "1 0.9 0.8 0.1"; colors[1] = "1 0.5 0 0.3"; colors[2] = "0.1 0.1 0.1 0"; sizes[0] = 0.2;//1; sizes[1] = 0.25;//0.15;//0.75; sizes[2] = 0.3;//0.1;//0.5; times[0] = 0.0; times[1] = 0.5;//0.294118; times[2] = 1.0; }; datablock ParticleEmitterData(RocketLauncherfiring1Emitter) { ejectionPeriodMS = 15;//75; periodVarianceMS = 5; ejectionVelocity = 1; ejectionOffset = 0.0; velocityVariance = 0; thetaMin = 0.0; thetaMax = 180;//10.0; particles = "RocketLauncherfiring1Particle"; blendStyle = "ADDITIVE"; }; datablock ParticleData(RocketLauncherfiring2Particle) { textureName = "art/shapes/particles/impact"; dragCoefficient = 100.0; gravityCoefficient = -0.5;//0.0; inheritedVelFactor = 0.25;//1.0; constantAcceleration = 0.1; lifetimeMS = 1600;//400; lifetimeVarianceMS = 400;//100; useInvAlpha = false; spinSpeed = 1; spinRandomMin = -200; spinRandomMax = 200; colors[0] = "0.4 0.4 0.4 0.2"; colors[1] = "0.4 0.4 0.4 0.1"; colors[2] = "0.0 0.0 0.0 0.0"; sizes[0] = 0.2;//1; sizes[1] = 0.15;//0.75; sizes[2] = 0.1;//0.5; times[0] = 0.0; times[1] = 0.5;//0.294118; times[2] = 1.0; }; datablock ParticleEmitterData(RocketLauncherfiring2Emitter) { ejectionPeriodMS = 15;//75; periodVarianceMS = 5; ejectionVelocity = 1; ejectionOffset = 0.0; velocityVariance = 0; thetaMin = 0.0; thetaMax = 180;//10.0; particles = "RocketLauncherfiring2Particle"; blendStyle = "NORMAL"; }; // ---------------------------------------------------------------------------- // Ammo Item // ---------------------------------------------------------------------------- datablock ItemData(RocketLauncherAmmo) { // Mission editor category category = "Ammo"; // Add the Ammo namespace as a parent. The ammo namespace provides // common ammo related functions and hooks into the inventory system. className = "Ammo"; // Basic Item properties shapeFile = "art/shapes/weapons/SwarmGun/rocket.dts"; mass = 2; elasticity = 0.2; friction = 0.6; // Dynamic properties defined by the scripts pickUpName = "Rockets"; maxInventory = 20; }; // ---------------------------------------------------------------------------- // Weapon Item. This is the item that exists in the world, // i.e. when it's been dropped, thrown or is acting as re-spawnable item. // When the weapon is mounted onto a shape, the Image is used. // ---------------------------------------------------------------------------- datablock ItemData(RocketLauncher) { // Mission editor category category = "Weapon"; // Hook into Item Weapon class hierarchy. The weapon namespace // provides common weapon handling functions in addition to hooks // into the inventory system. className = "Weapon"; // Basic Item properties shapefile = "art/shapes/weapons/SwarmGun/swarmgun.dts"; mass = 5; elasticity = 0.2; friction = 0.6; emap = true; // Dynamic properties defined by the scripts pickUpName = "SwarmGun"; description = "RocketLauncher"; image = RocketLauncherImage; // weaponHUD previewImage = 'swarmer.png'; reticle = 'reticle_rocketlauncher'; }; // ---------------------------------------------------------------------------- // Image which does all the work. Images do not normally exist in // the world, they can only be mounted on ShapeBase objects. // ---------------------------------------------------------------------------- datablock ShapeBaseImageData(RocketLauncherImage) { // Basic Item properties shapefile = "art/shapes/weapons/SwarmGun/swarmgun.dts"; emap = true; // Specify mount point & offset for 3rd person, and eye offset // for first person rendering. mountPoint = 0; offset = "0.0 0.15 0.025"; eyeOffset = "0.25 0.6 -0.4"; // 0.25=right/left 0.5=forward/backward, -0.5=up/down // When firing from a point offset from the eye, muzzle correction // will adjust the muzzle vector to point to the eye LOS point. // Since this weapon doesn't actually fire from the muzzle point, // we need to turn this off. correctMuzzleVector = false; // Add the WeaponImage namespace as a parent, WeaponImage namespace // provides some hooks into the inventory system. className = "WeaponImage"; // Projectile && Ammo. item = RocketLauncher; ammo = RocketLauncherAmmo; projectile = RocketLauncherProjectile; wetProjectile = RocketWetProjectile; projectileType = Projectile; // shell casings casing = RocketlauncherShellCasing; shellExitDir = "1.0 0.3 1.0"; shellExitOffset = "0.15 -0.56 -0.1"; shellExitVariance = 15.0; shellVelocity = 3.0; // Let there be light - NoLight, ConstantLight, PulsingLight, WeaponFireLight. lightType = "WeaponFireLight"; lightColor = "1.0 1.0 0.9"; lightDuration = 200; lightRadius = 10; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. // Initial start up state stateName[0] = "Preactivate"; stateTransitionOnLoaded[0] = "Activate"; stateTransitionOnNoAmmo[0] = "NoAmmo"; // Activating the gun. // Called when the weapon is first mounted and there is ammo. stateName[1] = "Activate"; stateTransitionOnTimeout[1] = "Ready"; stateTimeoutValue[1] = 0.6; stateSequence[1] = "Activate"; // Ready to fire, just waiting for the trigger stateName[2] = "Ready"; stateTransitionOnNoAmmo[2] = "NoAmmo"; stateTransitionOnTriggerDown[2] = "CheckWet"; stateTransitionOnAltTriggerDown[2] = "CheckWetAlt"; stateSequence[2] = "Ready"; // Fire the weapon. Calls the fire script which does the actual work. stateName[3] = "Fire"; stateTransitionOnTimeout[3] = "PostFire"; stateTimeoutValue[3] = 0.9; stateFire[3] = true; stateRecoil[3] = LightRecoil; stateAllowImageChange[3] = false; stateSequence[3] = "Fire"; stateScript[3] = "onFire"; stateSound[3] = RocketLauncherFireSound; stateEmitter[3] = RocketLauncherfiring1Emitter; stateEmitterTime[3] = 0.6; // Check ammo stateName[4] = "PostFire"; stateTransitionOnAmmo[4] = "Reload"; stateTransitionOnNoAmmo[4] = "NoAmmo"; // Play the reload animation, and transition into stateName[5] = "Reload"; stateTransitionOnTimeout[5] = "Ready"; stateTimeoutValue[5] = 0.9; stateAllowImageChange[5] = false; stateSequence[5] = "Reload"; stateEjectShell[5] = false; // set to true to enable shell casing eject stateSound[5] = RocketLauncherReloadSound; stateEmitter[5] = RocketLauncherfiring2Emitter; stateEmitterTime[5] = 2.4; // No ammo in the weapon, just idle until something shows up. // Play the dry fire sound if the trigger iS pulled. stateName[6] = "NoAmmo"; stateTransitionOnAmmo[6] = "Reload"; stateSequence[6] = "NoAmmo"; stateTransitionOnTriggerDown[6] = "DryFire"; // No ammo dry fire stateName[7] = "DryFire"; stateTimeoutValue[7] = 1.0; stateTransitionOnTimeout[7] = "NoAmmo"; stateSound[7] = RocketLauncherFireEmptySound; // Check if wet stateName[8] = "CheckWet"; stateTransitionOnWet[8] = "WetFire"; stateTransitionOnNotWet[8] = "Fire"; // Check if alt wet stateName[9] = "CheckWetAlt"; stateTransitionOnWet[9] = "WetFire"; stateTransitionOnNotWet[9] = "ChargeUp1"; // Wet fire stateName[10] = "WetFire"; stateTransitionOnTimeout[10] = "PostFire"; stateTimeoutValue[10] = 0.9; stateFire[10] = true; stateRecoil[10] = LightRecoil; stateAllowImageChange[10] = false; stateSequence[10] = "Fire"; stateScript[10] = "onWetFire"; stateSound[10] = RocketLauncherFireSound; // Begin "charge up", 1 in the pipe stateName[11] = "ChargeUp1"; stateScript[11] = "readyLoad"; stateSound[11] = RocketLauncherIncLoadSound; stateTransitionOnAltTriggerUp[11] = "AltFire"; stateTransitionOnTimeout[11] = "ChargeUp2"; stateTimeoutValue[11] = 0.8; stateWaitForTimeout[11] = false; // Charge up, 2 in the pipe stateName[12] = "ChargeUp2"; stateScript[12] = "incLoad"; stateSound[12] = RocketLauncherIncLoadSound; stateTransitionOnAltTriggerUp[12] = "AltFire"; stateTransitionOnTimeout[12] = "ChargeUp3"; stateTimeoutValue[12] = 0.8; stateWaitForTimeout[12] = false; // Charge up, 3 in the pipe stateName[13] = "ChargeUp3"; stateScript[13] = "incLoad"; stateSound[13] = RocketLauncherIncLoadSound; stateTransitionOnAltTriggerUp[13] = "AltFire"; stateTransitionOnTimeout[13] = "Altfire"; // lets force them to fire stateTimeOutValue[13] = 1.2; stateWaitForTimeout[13] = false; // Alt-fire stateName[14] = "AltFire"; stateTransitionOnTimeout[14] = "PostFire"; stateTimeoutValue[14] = 1.2; stateFire[14] = true; stateRecoil[14] = LightRecoil; stateAllowImageChange[14] = false; stateSequence[14] = "Fire"; stateScript[14] = "onAltFire"; stateSound[14] = RocketLauncherFireSound; stateEmitter[14] = RocketLauncherfiring1Emitter; stateEmitterTime[14] = 1.2; };
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Copyright (C) 2004 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.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using Xunit; namespace System.Data.Tests { public class DataTableReadXmlSchemaTest : RemoteExecutorTestBase { private DataSet CreateTestSet() { var ds = new DataSet(); ds.Tables.Add("Table1"); ds.Tables.Add("Table2"); ds.Tables[0].Columns.Add("Column1_1"); ds.Tables[0].Columns.Add("Column1_2"); ds.Tables[0].Columns.Add("Column1_3"); ds.Tables[1].Columns.Add("Column2_1"); ds.Tables[1].Columns.Add("Column2_2"); ds.Tables[1].Columns.Add("Column2_3"); ds.Tables[0].Rows.Add(new object[] { "ppp", "www", "xxx" }); ds.Relations.Add("Rel1", ds.Tables[0].Columns[2], ds.Tables[1].Columns[0]); return ds; } [Fact] public void SuspiciousDataSetElement() { string schema = @"<?xml version='1.0'?> <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:attribute name='foo' type='xsd:string'/> <xsd:attribute name='bar' type='xsd:string'/> <xsd:complexType name='attRef'> <xsd:attribute name='att1' type='xsd:int'/> <xsd:attribute name='att2' type='xsd:string'/> </xsd:complexType> <xsd:element name='doc'> <xsd:complexType> <xsd:choice> <xsd:element name='elem' type='attRef'/> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>"; var ds = new DataSet(); ds.Tables.Add(new DataTable("elem")); ds.Tables[0].ReadXmlSchema(new StringReader(schema)); DataSetAssertion.AssertDataTable("table", ds.Tables[0], "elem", 2, 0, 0, 0, 0, 0); } [Fact] public void UnusedComplexTypesIgnored() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'> <xs:element name='Root'> <xs:complexType> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Orphan' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { var ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables.Add(new DataTable("unusedType")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataSetAssertion.AssertDataTable("dt", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); // Here "unusedType" table is never imported. ds.Tables[1].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void IsDataSetAndTypeIgnored() { string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' type='unusedType' msdata:IsDataSet='{0}'> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { // When explicit msdata:IsDataSet value is "false", then // treat as usual. string xs = string.Format(xsbase, "false"); var ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataSetAssertion.AssertDataTable("dt", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); // Even if a global element uses a complexType, it will be // ignored if the element has msdata:IsDataSet='true' xs = string.Format(xsbase, "true"); ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void NestedReferenceNotAllowed() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' type='unusedType' msdata:IsDataSet='true'> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> <xs:element name='Foo'> <xs:complexType> <xs:sequence> <xs:element ref='Root' /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { // DataSet element cannot be converted into a DataTable. // (i.e. cannot be referenced in any other elements) var ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void LocaleOnRootWithoutIsDataSet() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' msdata:Locale='ja-JP'> <xs:complexType> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> <xs:attribute name='Attr' type='xs:integer' /> </xs:complexType> </xs:element> </xs:schema>"; var ds = new DataSet(); ds.Tables.Add("Root"); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("dt", dt, "Root", 2, 0, 0, 0, 0, 0); Assert.Equal("ja-JP", dt.Locale.Name); // DataTable's Locale comes from msdata:Locale DataSetAssertion.AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); DataSetAssertion.AssertDataColumn("col2", dt.Columns[1], "Child", false, false, 0, 1, "Child", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); } [Fact] public void PrefixedTargetNS() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:x='urn:foo' targetNamespace='urn:foo' elementFormDefault='qualified'> <xs:element name='DS' msdata:IsDataSet='true'> <xs:complexType> <xs:choice> <xs:element ref='x:R1' /> <xs:element ref='x:R2' /> </xs:choice> </xs:complexType> <xs:key name='key'> <xs:selector xpath='./any/string_is_OK/x:R1'/> <xs:field xpath='x:Child2'/> </xs:key> <xs:keyref name='kref' refer='x:key'> <xs:selector xpath='.//x:R2'/> <xs:field xpath='x:Child2'/> </xs:keyref> </xs:element> <xs:element name='R3' type='x:RootType' /> <xs:complexType name='extracted'> <xs:choice> <xs:element ref='x:R1' /> <xs:element ref='x:R2' /> </xs:choice> </xs:complexType> <xs:element name='R1' type='x:RootType'> <xs:unique name='Rkey'> <xs:selector xpath='.//x:Child1'/> <xs:field xpath='.'/> </xs:unique> <xs:keyref name='Rkref' refer='x:Rkey'> <xs:selector xpath='.//x:Child2'/> <xs:field xpath='.'/> </xs:keyref> </xs:element> <xs:element name='R2' type='x:RootType'> </xs:element> <xs:complexType name='RootType'> <xs:choice> <xs:element name='Child1' type='xs:string'> </xs:element> <xs:element name='Child2' type='xs:string' /> </xs:choice> <xs:attribute name='Attr' type='xs:integer' /> </xs:complexType> </xs:schema>"; // No prefixes on tables and columns var ds = new DataSet(); ds.Tables.Add(new DataTable("R3")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("R3", dt, "R3", 3, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); } private void ReadTest1Check(DataSet ds) { DataSetAssertion.AssertDataSet("dataset", ds, "NewDataSet", 2, 1); DataSetAssertion.AssertDataTable("tbl1", ds.Tables[0], "Table1", 3, 0, 0, 1, 1, 0); DataSetAssertion.AssertDataTable("tbl2", ds.Tables[1], "Table2", 3, 0, 1, 0, 1, 0); DataRelation rel = ds.Relations[0]; DataSetAssertion.AssertDataRelation("rel", rel, "Rel1", false, new string[] { "Column1_3" }, new string[] { "Column2_1" }, true, true); DataSetAssertion.AssertUniqueConstraint("uc", rel.ParentKeyConstraint, "Constraint1", false, new string[] { "Column1_3" }); DataSetAssertion.AssertForeignKeyConstraint("fk", rel.ChildKeyConstraint, "Rel1", AcceptRejectRule.None, Rule.Cascade, Rule.Cascade, new string[] { "Column2_1" }, new string[] { "Column1_3" }); } [Fact] public void TestSampleFileSimpleTables() { var ds = new DataSet(); ds.Tables.Add(new DataTable("foo")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='ct' /> <xs:complexType name='ct'> <xs:simpleContent> <xs:extension base='xs:integer'> <xs:attribute name='attr' /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:schema>")); DataSetAssertion.AssertDataSet("005", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("attr", dt.Columns[0], "attr", true, false, 0, 1, "attr", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); DataSetAssertion.AssertDataColumn("text", dt.Columns[1], "foo_text", false, false, 0, 1, "foo_text", MappingType.SimpleContent, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); ds = new DataSet(); ds.Tables.Add(new DataTable("foo")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='st' /> <xs:complexType name='st'> <xs:attribute name='att1' /> <xs:attribute name='att2' type='xs:int' default='2' /> </xs:complexType> </xs:schema>")); DataSetAssertion.AssertDataSet("006", ds, "NewDataSet", 1, 0); dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("att1", dt.Columns["att1"], "att1", true, false, 0, 1, "att1", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, /*0*/-1, string.Empty, false, false); DataSetAssertion.AssertDataColumn("att2", dt.Columns["att2"], "att2", true, false, 0, 1, "att2", MappingType.Attribute, typeof(int), 2, string.Empty, -1, string.Empty, /*1*/-1, string.Empty, false, false); } [Fact] public void TestSampleFileComplexTables3() { var ds = new DataSet(); ds.Tables.Add(new DataTable("e")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<!-- Modified w3ctests attQ014.xsd --> <xsd:schema xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" targetNamespace=""http://xsdtesting"" xmlns:x=""http://xsdtesting""> <xsd:element name=""root""> <xsd:complexType> <xsd:sequence> <xsd:element name=""e""> <xsd:complexType> <xsd:simpleContent> <xsd:extension base=""xsd:decimal""> <xsd:attribute name=""a"" type=""xsd:string""/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>")); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("root", dt, "e", 2, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("attr", dt.Columns[0], "a", true, false, 0, 1, "a", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); DataSetAssertion.AssertDataColumn("simple", dt.Columns[1], "e_text", false, false, 0, 1, "e_text", MappingType.SimpleContent, typeof(decimal), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); } [Fact] public void TestSampleFileXPath() { var ds = new DataSet(); ds.Tables.Add(new DataTable("Track")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <xs:schema targetNamespace=""http://neurosaudio.com/Tracks.xsd"" xmlns=""http://neurosaudio.com/Tracks.xsd"" xmlns:mstns=""http://neurosaudio.com/Tracks.xsd"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"" elementFormDefault=""qualified"" id=""Tracks""> <xs:element name=""Tracks""> <xs:complexType> <xs:sequence> <xs:element name=""Track"" minOccurs=""0"" maxOccurs=""unbounded""> <xs:complexType> <xs:sequence> <xs:element name=""Title"" type=""xs:string"" /> <xs:element name=""Artist"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Album"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Performer"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Sequence"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Genre"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Comment"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Year"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Duration"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Path"" type=""xs:string"" /> <xs:element name=""DevicePath"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""FileSize"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Source"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""FlashStatus"" type=""xs:unsignedInt"" /> <xs:element name=""HDStatus"" type=""xs:unsignedInt"" /> </xs:sequence> <xs:attribute name=""ID"" type=""xs:unsignedInt"" msdata:AutoIncrement=""true"" msdata:AutoIncrementSeed=""1"" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <xs:key name=""TrackPK"" msdata:PrimaryKey=""true""> <xs:selector xpath="".//mstns:Track"" /> <xs:field xpath=""@ID"" /> </xs:key> </xs:element> </xs:schema>")); } [Fact] public void ReadConstraints() { const string Schema = @"<?xml version=""1.0"" encoding=""utf-8""?> <xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xs:element name=""NewDataSet"" msdata:IsDataSet=""true"" msdata:Locale=""en-US""> <xs:complexType> <xs:choice maxOccurs=""unbounded""> <xs:element name=""Table1""> <xs:complexType> <xs:sequence> <xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""Table2""> <xs:complexType> <xs:sequence> <xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> <xs:unique name=""Constraint1""> <xs:selector xpath="".//Table1"" /> <xs:field xpath=""col1"" /> </xs:unique> <xs:keyref name=""fk1"" refer=""Constraint1"" msdata:ConstraintOnly=""true""> <xs:selector xpath="".//Table2"" /> <xs:field xpath=""col1"" /> </xs:keyref> </xs:element> </xs:schema>"; var ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables.Add(new DataTable()); ds.Tables[0].ReadXmlSchema(new StringReader(Schema)); ds.Tables[1].ReadXmlSchema(new StringReader(Schema)); Assert.Equal(0, ds.Relations.Count); Assert.Equal(1, ds.Tables[0].Constraints.Count); Assert.Equal(0, ds.Tables[1].Constraints.Count); Assert.Equal("Constraint1", ds.Tables[0].Constraints[0].ConstraintName); } [Fact] public void XsdSchemaSerializationIgnoresLocale() { RemoteInvoke(() => { var serializer = new BinaryFormatter(); var table = new DataTable(); table.Columns.Add(new DataColumn("RowID", typeof(int)) { AutoIncrement = true, AutoIncrementSeed = -1, // These lines produce attributes within the schema portion of the underlying XML representation of the DataTable with the values "-1" and "-2". AutoIncrementStep = -2, }); table.Columns.Add("Value", typeof(string)); table.Rows.Add(1, "Test"); table.Rows.Add(2, "Data"); var buffer = new MemoryStream(); var savedCulture = CultureInfo.CurrentCulture; try { // Before serializing, update the culture to use a weird negative number format. This test is ensuring that this is ignored. CultureInfo.CurrentCulture = new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } }; serializer.Serialize(buffer, table); } finally { CultureInfo.CurrentCulture = savedCulture; } // The raw serialized data now contains an embedded XML schema. We need to verify that this embedded schema used "-1" for the numeric value // negative 1, instead of "()1" as indicated by the current culture. string rawSerializedData = System.Text.Encoding.ASCII.GetString(buffer.ToArray()); const string SchemaStartTag = "<xs:schema"; const string SchemaEndTag = "</xs:schema>"; int schemaStart = rawSerializedData.IndexOf(SchemaStartTag); int schemaEnd = rawSerializedData.IndexOf(SchemaEndTag); Assert.True(schemaStart >= 0); Assert.True(schemaEnd > schemaStart); Assert.True(rawSerializedData.IndexOf("<xs:schema", schemaStart + 1) < 0); schemaEnd += SchemaEndTag.Length; string rawSchemaXML = rawSerializedData.Substring( startIndex: schemaStart, length: schemaEnd - schemaStart); Assert.Contains(@"AutoIncrementSeed=""-1""", rawSchemaXML); Assert.Contains(@"AutoIncrementStep=""-2""", rawSchemaXML); Assert.DoesNotContain("()1", rawSchemaXML); Assert.DoesNotContain("()2", rawSchemaXML); }); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework does not yet have the fix for this bug")] public void XsdSchemaDeserializationIgnoresLocale() { RemoteInvoke(() => { var serializer = new BinaryFormatter(); /* Test data generator: var table = new DataTable(); table.Columns.Add(new DataColumn("RowID", typeof(int)) { AutoIncrement = true, AutoIncrementSeed = -1, // These lines produce attributes within the schema portion of the underlying XML representation of the DataTable with the value "-1". AutoIncrementStep = -2, }); table.Columns.Add("Value", typeof(string)); table.Rows.Add(1, "Test"); table.Rows.Add(2, "Data"); var buffer = new MemoryStream(); serializer.Serialize(buffer, table); This test data (binary serializer output) embeds the following XML schema: <?xml version="1.0" encoding="utf-16"?> <xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="Table1"> <xs:complexType> <xs:sequence> <xs:element name="RowID" msdata:AutoIncrement="true" msdata:AutoIncrementSeed="-1" msdata:AutoIncrementStep="-2" type="xs:int" msdata:targetNamespace="" minOccurs="0" /> <xs:element name="Value" type="xs:string" msdata:targetNamespace="" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="tmpDataSet" msdata:IsDataSet="true" msdata:MainDataTable="Table1" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded" /> </xs:complexType> </xs:element> </xs:schema> The bug being tested here is that the negative integer values in AutoInecrementSeed and AutoIncrementStep fail to parse because the deserialization code incorrectly uses the current culture instead of the invariant culture when parsing strings like "-1" and "-2". */ var buffer = new MemoryStream(new byte[] { 0,1,0,0,0,255,255,255,255,1,0,0,0,0,0,0,0,12,2,0,0,0,78,83,121,115,116,101,109,46,68,97,116,97,44,32,86,101,114,115,105,111,110,61,52,46,48,46,48,46,48,44,32,67,117, 108,116,117,114,101,61,110,101,117,116,114,97,108,44,32,80,117,98,108,105,99,75,101,121,84,111,107,101,110,61,98,55,55,97,53,99,53,54,49,57,51,52,101,48,56,57,5,1,0, 0,0,21,83,121,115,116,101,109,46,68,97,116,97,46,68,97,116,97,84,97,98,108,101,3,0,0,0,25,68,97,116,97,84,97,98,108,101,46,82,101,109,111,116,105,110,103,86,101,114, 115,105,111,110,9,88,109,108,83,99,104,101,109,97,11,88,109,108,68,105,102,102,71,114,97,109,3,1,1,14,83,121,115,116,101,109,46,86,101,114,115,105,111,110,2,0,0,0,9, 3,0,0,0,6,4,0,0,0,177,6,60,63,120,109,108,32,118,101,114,115,105,111,110,61,34,49,46,48,34,32,101,110,99,111,100,105,110,103,61,34,117,116,102,45,49,54,34,63,62,13, 10,60,120,115,58,115,99,104,101,109,97,32,120,109,108,110,115,61,34,34,32,120,109,108,110,115,58,120,115,61,34,104,116,116,112,58,47,47,119,119,119,46,119,51,46,111, 114,103,47,50,48,48,49,47,88,77,76,83,99,104,101,109,97,34,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105, 99,114,111,115,111,102,116,45,99,111,109,58,120,109,108,45,109,115,100,97,116,97,34,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34, 84,97,98,108,101,49,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,115,101,113,117,101,110, 99,101,62,13,10,32,32,32,32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,82,111,119,73,68,34,32,109,115,100,97,116,97,58,65,117,116, 111,73,110,99,114,101,109,101,110,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,101,101,100,61,34,45, 49,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,116,101,112,61,34,45,50,34,32,116,121,112,101,61,34,120,115,58,105,110,116,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,86,97,108,117,101,34,32,116,121,112,101,61,34,120,115,58,115,116,114,105,110,103,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,60,47,120,115,58,115,101,113,117,101,110,99,101,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47,120,115, 58,101,108,101,109,101,110,116,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,116,109,112,68,97,116,97,83,101,116,34,32,109,115,100, 97,116,97,58,73,115,68,97,116,97,83,101,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,77,97,105,110,68,97,116,97,84,97,98,108,101,61,34,84,97,98,108,101, 49,34,32,109,115,100,97,116,97,58,85,115,101,67,117,114,114,101,110,116,76,111,99,97,108,101,61,34,116,114,117,101,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109, 112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,99,104,111,105,99,101,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,109,97,120,79,99,99, 117,114,115,61,34,117,110,98,111,117,110,100,101,100,34,32,47,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47, 120,115,58,101,108,101,109,101,110,116,62,13,10,60,47,120,115,58,115,99,104,101,109,97,62,6,5,0,0,0,221,3,60,100,105,102,102,103,114,58,100,105,102,102,103,114,97, 109,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45,99,111,109,58,120,109,108, 45,109,115,100,97,116,97,34,32,120,109,108,110,115,58,100,105,102,102,103,114,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45, 99,111,109,58,120,109,108,45,100,105,102,102,103,114,97,109,45,118,49,34,62,13,10,32,32,60,116,109,112,68,97,116,97,83,101,116,62,13,10,32,32,32,32,60,84,97,98,108, 101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,49,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,48,34,32,100,105,102, 102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,49,60,47,82,111,119,73, 68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,84,101,115,116,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32,32,32,32,60, 84,97,98,108,101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,50,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,49,34,32, 100,105,102,102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,50,60,47, 82,111,119,73,68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,68,97,116,97,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32, 32,60,47,116,109,112,68,97,116,97,83,101,116,62,13,10,60,47,100,105,102,102,103,114,58,100,105,102,102,103,114,97,109,62,4,3,0,0,0,14,83,121,115,116,101,109,46,86, 101,114,115,105,111,110,4,0,0,0,6,95,77,97,106,111,114,6,95,77,105,110,111,114,6,95,66,117,105,108,100,9,95,82,101,118,105,115,105,111,110,0,0,0,0,8,8,8,8,2,0,0,0,0, 0,0,0,255,255,255,255,255,255,255,255,11 }); DataTable table; var savedCulture = CultureInfo.CurrentCulture; try { // Before deserializing, update the culture to use a weird negative number format. This test is ensuring that this is ignored. // The bug this test is testing would cause "-1" to no longer be treated as a valid representation of the value -1, instead // only accepting the string "()1". CultureInfo.CurrentCulture = new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } }; table = (DataTable)serializer.Deserialize(buffer); // BUG: System.Exception: "-1 is not a valid value for Int64." } } finally { CultureInfo.CurrentCulture = savedCulture; } DataColumn rowIDColumn = table.Columns["RowID"]; Assert.Equal(-1, rowIDColumn.AutoIncrementSeed); Assert.Equal(-2, rowIDColumn.AutoIncrementStep); }); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "Exists to provide notification of when the full framework gets the bug fix, at which point the preceding test can be re-enabled")] public void XsdSchemaDeserializationOnFullFrameworkStillHasBug() { var serializer = new BinaryFormatter(); var buffer = new MemoryStream(new byte[] { 0,1,0,0,0,255,255,255,255,1,0,0,0,0,0,0,0,12,2,0,0,0,78,83,121,115,116,101,109,46,68,97,116,97,44,32,86,101,114,115,105,111,110,61,52,46,48,46,48,46,48,44,32,67,117, 108,116,117,114,101,61,110,101,117,116,114,97,108,44,32,80,117,98,108,105,99,75,101,121,84,111,107,101,110,61,98,55,55,97,53,99,53,54,49,57,51,52,101,48,56,57,5,1,0, 0,0,21,83,121,115,116,101,109,46,68,97,116,97,46,68,97,116,97,84,97,98,108,101,3,0,0,0,25,68,97,116,97,84,97,98,108,101,46,82,101,109,111,116,105,110,103,86,101,114, 115,105,111,110,9,88,109,108,83,99,104,101,109,97,11,88,109,108,68,105,102,102,71,114,97,109,3,1,1,14,83,121,115,116,101,109,46,86,101,114,115,105,111,110,2,0,0,0,9, 3,0,0,0,6,4,0,0,0,177,6,60,63,120,109,108,32,118,101,114,115,105,111,110,61,34,49,46,48,34,32,101,110,99,111,100,105,110,103,61,34,117,116,102,45,49,54,34,63,62,13, 10,60,120,115,58,115,99,104,101,109,97,32,120,109,108,110,115,61,34,34,32,120,109,108,110,115,58,120,115,61,34,104,116,116,112,58,47,47,119,119,119,46,119,51,46,111, 114,103,47,50,48,48,49,47,88,77,76,83,99,104,101,109,97,34,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105, 99,114,111,115,111,102,116,45,99,111,109,58,120,109,108,45,109,115,100,97,116,97,34,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34, 84,97,98,108,101,49,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,115,101,113,117,101,110, 99,101,62,13,10,32,32,32,32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,82,111,119,73,68,34,32,109,115,100,97,116,97,58,65,117,116, 111,73,110,99,114,101,109,101,110,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,101,101,100,61,34,45, 49,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,116,101,112,61,34,45,50,34,32,116,121,112,101,61,34,120,115,58,105,110,116,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,86,97,108,117,101,34,32,116,121,112,101,61,34,120,115,58,115,116,114,105,110,103,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,60,47,120,115,58,115,101,113,117,101,110,99,101,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47,120,115, 58,101,108,101,109,101,110,116,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,116,109,112,68,97,116,97,83,101,116,34,32,109,115,100, 97,116,97,58,73,115,68,97,116,97,83,101,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,77,97,105,110,68,97,116,97,84,97,98,108,101,61,34,84,97,98,108,101, 49,34,32,109,115,100,97,116,97,58,85,115,101,67,117,114,114,101,110,116,76,111,99,97,108,101,61,34,116,114,117,101,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109, 112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,99,104,111,105,99,101,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,109,97,120,79,99,99, 117,114,115,61,34,117,110,98,111,117,110,100,101,100,34,32,47,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47, 120,115,58,101,108,101,109,101,110,116,62,13,10,60,47,120,115,58,115,99,104,101,109,97,62,6,5,0,0,0,221,3,60,100,105,102,102,103,114,58,100,105,102,102,103,114,97, 109,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45,99,111,109,58,120,109,108, 45,109,115,100,97,116,97,34,32,120,109,108,110,115,58,100,105,102,102,103,114,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45, 99,111,109,58,120,109,108,45,100,105,102,102,103,114,97,109,45,118,49,34,62,13,10,32,32,60,116,109,112,68,97,116,97,83,101,116,62,13,10,32,32,32,32,60,84,97,98,108, 101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,49,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,48,34,32,100,105,102, 102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,49,60,47,82,111,119,73, 68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,84,101,115,116,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32,32,32,32,60, 84,97,98,108,101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,50,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,49,34,32, 100,105,102,102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,50,60,47, 82,111,119,73,68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,68,97,116,97,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32, 32,60,47,116,109,112,68,97,116,97,83,101,116,62,13,10,60,47,100,105,102,102,103,114,58,100,105,102,102,103,114,97,109,62,4,3,0,0,0,14,83,121,115,116,101,109,46,86, 101,114,115,105,111,110,4,0,0,0,6,95,77,97,106,111,114,6,95,77,105,110,111,114,6,95,66,117,105,108,100,9,95,82,101,118,105,115,105,111,110,0,0,0,0,8,8,8,8,2,0,0,0,0, 0,0,0,255,255,255,255,255,255,255,255,11 }); Exception exception; CultureInfo savedCulture = CultureInfo.CurrentCulture; try { exception = Assert.Throws<TargetInvocationException>(() => { // Before deserializing, update the culture to use a weird negative number format. The bug this test is testing causes "-1" to no // longer be treated as a valid representation of the value -1, instead only accepting the string "()1". CultureInfo.CurrentCulture = new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } }; serializer.Deserialize(buffer); // BUG: System.Exception: "-1 is not a valid value for Int64." }); } finally { CultureInfo.CurrentCulture = savedCulture; } Assert.IsAssignableFrom<FormatException>(exception.InnerException.InnerException); } } }
namespace Gu.State { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; [DebuggerDisplay("{DebuggerDisplay,nq}")] internal sealed class DiffBuilder : IDisposable { private static readonly object RankDiffKey = new object(); private readonly IRefCounted<ReferencePair> refCountedPair; private readonly MemberSettings settings; private readonly IBorrowed<Dictionary<object, SubDiff>> borrowedDiffs; private readonly IBorrowed<Dictionary<object, IRefCounted<DiffBuilder>>> borrowedSubBuilders; private readonly List<SubDiff> diffs = new List<SubDiff>(); private readonly object gate = new object(); private readonly ValueDiff valueDiff; private bool needsRefresh; private bool isRefreshing; private bool isPurging; private bool isUpdatingDiffs; private bool isCheckingHasMemberOrIndexDiff; private bool disposed; private DiffBuilder(IRefCounted<ReferencePair> refCountedPair, MemberSettings settings) { this.refCountedPair = refCountedPair; this.settings = settings; this.borrowedDiffs = DictionaryPool<object, SubDiff>.Borrow(); this.borrowedSubBuilders = DictionaryPool<object, IRefCounted<DiffBuilder>>.Borrow(); this.valueDiff = new ValueDiff(refCountedPair.Value.X, refCountedPair.Value.Y, this.diffs); } internal bool IsEmpty { get { Debug.Assert(!this.disposed, "this.disposed"); lock (this.gate) { this.Refresh(); return this.KeyedDiffs.Count == 0; } } } private string DebuggerDisplay => $"{typeof(DiffBuilder).Name} for {this.refCountedPair.Value.X.GetType().Name}"; private Dictionary<object, SubDiff> KeyedDiffs => this.borrowedDiffs.Value; private Dictionary<object, IRefCounted<DiffBuilder>> KeyedSubBuilders => this.borrowedSubBuilders.Value; public void Dispose() { lock (this.gate) { if (this.disposed) { return; } this.disposed = true; foreach (var disposer in this.KeyedSubBuilders.Values) { disposer.Dispose(); } this.borrowedDiffs.Dispose(); this.borrowedSubBuilders.Dispose(); this.refCountedPair.Dispose(); } } internal static IRefCounted<DiffBuilder> GetOrCreate(object x, object y, MemberSettings settings) { return TrackerCache.GetOrAdd(x, y, settings, pair => new DiffBuilder(pair, settings)); } internal static bool TryCreate(object x, object y, MemberSettings settings, out IRefCounted<DiffBuilder> subDiffBuilder) { subDiffBuilder = TrackerCache.GetOrAdd(x, y, settings, pair => new DiffBuilder(pair, settings), out var created); return created; } internal ValueDiff CreateValueDiffOrNull() { Debug.Assert(!this.disposed, "this.disposed"); lock (this.gate) { this.Refresh(); return this.IsEmpty ? null : this.valueDiff; } } internal bool TryAdd(MemberInfo member, object xValue, object yValue) { Debug.Assert(!this.disposed, "this.disposed"); lock (this.gate) { if (this.KeyedSubBuilders.ContainsKey(member)) { this.Add(member, xValue, yValue); return true; } if (!this.KeyedDiffs.TryGetValue(member, out var old)) { this.Add(member, xValue, yValue); return true; } if (old.Diffs.Count > 0) { this.Add(member, xValue, yValue); return true; } if (EqualBy.TryGetValueEquals(xValue, old.X, this.settings, out var xEqual) && xEqual && EqualBy.TryGetValueEquals(yValue, old.Y, this.settings, out var yEqual) && yEqual) { return false; } this.Add(member, xValue, yValue); return true; } } internal void Add(MemberInfo member, object xValue, object yValue) { Debug.Assert(!this.disposed, "this.disposed"); lock (this.gate) { this.needsRefresh = true; this.KeyedDiffs[member] = MemberDiff.Create(member, xValue, yValue); this.UpdateSubBuilder(member, null); } } internal void Add(MemberDiff memberDiff) { Debug.Assert(!this.disposed, "this.disposed"); lock (this.gate) { this.needsRefresh = true; this.KeyedDiffs[memberDiff.MemberInfo] = memberDiff; this.UpdateSubBuilder(memberDiff.MemberInfo, null); } } internal void Remove(object memberOrIndexOrKey) { Debug.Assert(!this.disposed, "this.disposed"); lock (this.gate) { this.needsRefresh = true; this.KeyedDiffs.Remove(memberOrIndexOrKey); this.UpdateSubBuilder(memberOrIndexOrKey, null); } } internal void ClearIndexDiffs() { Debug.Assert(!this.disposed, "this.disposed"); lock (this.gate) { using var borrowed = ListPool<object>.Borrow(); foreach (var subDiff in this.KeyedDiffs) { if (subDiff.Value is IndexDiff indexDiff) { borrowed.Value.Add(indexDiff.Index); } } foreach (var index in borrowed.Value) { this.needsRefresh = true; this.Remove(index); } } } internal void Add(IndexDiff indexDiff) { Debug.Assert(!this.disposed, "this.disposed"); lock (this.gate) { this.needsRefresh = true; this.KeyedDiffs[indexDiff.Index] = indexDiff; this.UpdateSubBuilder(indexDiff.Index, null); } } internal void Add(RankDiff rankDiff) { lock (this.gate) { this.needsRefresh = true; this.KeyedDiffs[RankDiffKey] = rankDiff; } } internal void AddLazy(MemberInfo member, DiffBuilder builder) { Debug.Assert(!this.disposed, "this.disposed"); lock (this.gate) { this.needsRefresh = true; this.KeyedDiffs[member] = MemberDiff.Create(member, builder.valueDiff); this.UpdateSubBuilder(member, builder); } } internal void AddLazy(object index, DiffBuilder builder) { Debug.Assert(!this.disposed, "this.disposed"); lock (this.gate) { this.needsRefresh = true; this.KeyedDiffs[index] = new IndexDiff(index, builder.valueDiff); this.UpdateSubBuilder(index, builder); } } internal void Refresh() { _ = this.TryRefresh(); } internal bool TryRefresh() { if (!this.needsRefresh || this.isRefreshing) { return false; } lock (this.gate) { if (!this.needsRefresh || this.isRefreshing) { return false; } this.isRefreshing = true; this.Purge(); var changed = this.TryUpdateDiffs(); this.isRefreshing = false; this.needsRefresh = false; return changed; } } private void Purge() { if (!this.needsRefresh || this.isPurging) { return; } lock (this.gate) { if (!this.needsRefresh || this.isPurging) { return; } this.isPurging = true; using (var borrowedList = ListPool<object>.Borrow()) { borrowedList.Value.Clear(); foreach (var keyAndBuilder in this.KeyedSubBuilders) { var builder = keyAndBuilder.Value.Value; builder.Purge(); if (!builder.HasMemberOrIndexDiff()) { borrowedList.Value.Add(keyAndBuilder.Key); } } foreach (var key in borrowedList.Value) { this.Remove(key); } } this.isPurging = false; } } private bool HasMemberOrIndexDiff() { if (this.isCheckingHasMemberOrIndexDiff) { return false; } this.isCheckingHasMemberOrIndexDiff = true; var result = this.KeyedDiffs.Count > this.KeyedSubBuilders.Count || this.KeyedSubBuilders.Any(kd => kd.Value.Value.HasMemberOrIndexDiff()); this.isCheckingHasMemberOrIndexDiff = false; return result; } private bool TryUpdateDiffs() { if (!this.needsRefresh || this.isUpdatingDiffs) { return false; } lock (this.gate) { if (!this.needsRefresh || this.isUpdatingDiffs) { return false; } var changed = this.diffs.Count != this.KeyedDiffs.Count; this.isUpdatingDiffs = true; foreach (var keyedSubBuilder in this.KeyedSubBuilders) { changed |= keyedSubBuilder.Value.Value.TryUpdateDiffs(); } using (var borrow = ListPool<SubDiff>.Borrow()) { foreach (var keyAndDiff in this.KeyedDiffs) { borrow.Value.Add(keyAndDiff.Value); } borrow.Value.Sort(SubDiffComparer.Default); for (var index = 0; index < borrow.Value.Count; index++) { if (!changed) { changed |= !ReferenceEquals(borrow.Value[index], this.diffs[index]); } this.diffs.SetElementAt(index, borrow.Value[index]); } this.diffs.TrimLengthTo(this.KeyedDiffs.Count); } this.isUpdatingDiffs = false; return changed; } } private void UpdateSubBuilder(object key, DiffBuilder builder) { if (builder is null) { this.KeyedSubBuilders.TryRemoveAndDispose(key); return; } if (!builder.TryRefCount(out var refCounted, out _)) { throw Throw.ShouldNeverGetHereException("UpdateSubBuilder failed, try refcount failed"); } this.KeyedSubBuilders.AddOrUpdate(key, refCounted); } private sealed class SubDiffComparer : IComparer<SubDiff> { internal static readonly SubDiffComparer Default = new SubDiffComparer(); private SubDiffComparer() { } public int Compare(SubDiff x, SubDiff y) { if (TryCompareType(x, y, out var result)) { return result; } if (TryCompare<IndexDiff>(x, y, CompareIndex, out result) || TryCompare<MemberDiff>(x, y, CompareMemberName, out result)) { return result; } return 0; } private static int CompareIndex(IndexDiff x, IndexDiff y) { if (x.Index is int && y.Index is int) { return ((int)x.Index).CompareTo(y.Index); } if ((x.X == PaddedPairs.MissingItem || x.Y == PaddedPairs.MissingItem) && (y.X == PaddedPairs.MissingItem || y.Y == PaddedPairs.MissingItem)) { var xv = (x.X == PaddedPairs.MissingItem ? 1 : 0) + (x.Y == PaddedPairs.MissingItem ? -1 : 0); var yv = (y.X == PaddedPairs.MissingItem ? 1 : 0) + (y.Y == PaddedPairs.MissingItem ? -1 : 0); return xv.CompareTo(yv); } return 0; } private static int CompareMemberName(MemberDiff x, MemberDiff y) { return string.Compare(x.MemberInfo.Name, y.MemberInfo.Name, StringComparison.Ordinal); } private static bool TryCompare<T>(SubDiff x, SubDiff y, Func<T, T, int> compare, out int result) where T : SubDiff { if (x is T && y is T) { result = compare((T)x, (T)y); return true; } result = 0; return false; } private static bool TryCompareType(SubDiff x, SubDiff y, out int result) { if (x.GetType() == y.GetType()) { result = 0; return false; } if (TryIs<MemberDiff, IndexDiff>(x, y, out _) || TryIs<MemberDiff, RankDiff>(x, y, out _) || TryIs<RankDiff, IndexDiff>(x, y, out _)) { result = -1; return true; } result = 0; return true; } private static bool TryIs<T1, T2>(SubDiff x, SubDiff y, out int result) where T1 : SubDiff where T2 : SubDiff { if (x is T1 && y is T2) { result = 1; return true; } if (x is T2 && y is T1) { result = -1; return true; } result = 0; return false; } } } }
// ---------------------------------------------------------------------------------- // // 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 Management.Storage.ScenarioTest.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using MS.Test.Common.MsTestLib; using StorageTestLib; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace Management.Storage.ScenarioTest.Common { /// <summary> /// general settings for container related tests /// </summary> [TestClass] public abstract class TestBase { protected static CloudBlobUtil blobUtil; protected static CloudQueueUtil queueUtil; protected static CloudTableUtil tableUtil; protected static CloudStorageAccount StorageAccount; protected static Random random; private static int ContainerInitCount = 0; private static int QueueInitCount = 0; private static int TableInitCount = 0; public const string ConfirmExceptionMessage = "The host was attempting to request confirmation"; protected Agent agent; private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes /// <summary> /// Use ClassInitialize to run code before running the first test in the class /// the derived class should use it's custom class initialize /// first init common bvt /// second set storage context in powershell /// </summary> /// <param name="testContext">Test context object</param> [ClassInitialize()] public static void TestClassInitialize(TestContext testContext) { Test.Info(string.Format("{0} Class Initialize", testContext.FullyQualifiedTestClassName)); Test.FullClassName = testContext.FullyQualifiedTestClassName; StorageAccount = GetCloudStorageAccountFromConfig(); //init the blob helper for blob related operations blobUtil = new CloudBlobUtil(StorageAccount); queueUtil = new CloudQueueUtil(StorageAccount); tableUtil = new CloudTableUtil(StorageAccount); // import module string moduleFilePath = Test.Data.Get("ModuleFilePath"); PowerShellAgent.ImportModule(moduleFilePath); //set the default storage context PowerShellAgent.SetStorageContext(StorageAccount.ToString(true)); random = new Random(); ContainerInitCount = blobUtil.GetExistingContainerCount(); QueueInitCount = queueUtil.GetExistingQueueCount(); TableInitCount = tableUtil.GetExistingTableCount(); } // //Use ClassCleanup to run code after all tests in a class have run [ClassCleanup()] public static void TestClassCleanup() { int count = blobUtil.GetExistingContainerCount(); string message = string.Format("there are {0} containers before running mutiple unit tests, after is {1}", ContainerInitCount, count); AssertCleanupOnStorageObject("containers", ContainerInitCount, count); count = queueUtil.GetExistingQueueCount(); AssertCleanupOnStorageObject("queues", QueueInitCount, count); count = tableUtil.GetExistingTableCount(); AssertCleanupOnStorageObject("tables", TableInitCount, count); Test.Info("Test Class Cleanup"); } private static void AssertCleanupOnStorageObject(string name, int initCount, int cleanUpCount) { string message = string.Format("there are {0} {1} before running mutiple unit tests, after is {2}", initCount, name, cleanUpCount); if (initCount == cleanUpCount) { Test.Info(message); } else { Test.Warn(message); } } /// <summary> /// Get Cloud storage account from Test.xml /// </summary> /// <param name="configKey">Config key. Will return the default storage account when it's empty.</param> /// <param name="useHttps">Use https or not</param> /// <returns>Cloud Storage Account with specified end point</returns> public static CloudStorageAccount GetCloudStorageAccountFromConfig(string configKey = "", bool useHttps = true) { string StorageAccountName = Test.Data.Get(string.Format("{0}StorageAccountName", configKey)); string StorageAccountKey = Test.Data.Get(string.Format("{0}StorageAccountKey", configKey)); string StorageEndPoint = Test.Data.Get(string.Format("{0}StorageEndPoint", configKey)); StorageCredentials credential = new StorageCredentials(StorageAccountName, StorageAccountKey); return Utility.GetStorageAccountWithEndPoint(credential, useHttps, StorageEndPoint); } /// <summary> /// on test setup /// the derived class could use it to run it owned set up settings. /// </summary> public virtual void OnTestSetup() { } /// <summary> /// on test clean up /// the derived class could use it to run it owned clean up settings. /// </summary> public virtual void OnTestCleanUp() { } /// <summary> /// test initialize /// </summary> [TestInitialize()] public void InitAgent() { agent = new PowerShellAgent(); Test.Start(TestContext.FullyQualifiedTestClassName, TestContext.TestName); OnTestSetup(); } /// <summary> /// test clean up /// </summary> [TestCleanup()] public void CleanAgent() { OnTestCleanUp(); agent = null; Test.End(TestContext.FullyQualifiedTestClassName, TestContext.TestName); } #endregion /// <summary> /// Expect returned error message is the specified error message /// </summary> /// <param name="expectErrorMessage">Expect error message</param> public void ExpectedEqualErrorMessage(string expectErrorMessage) { Test.Assert(agent.ErrorMessages.Count > 0, "Should return error message"); if (agent.ErrorMessages.Count == 0) { return; } Test.Assert(expectErrorMessage == agent.ErrorMessages[0], String.Format("Expected error message: {0}, and actually it's {1}", expectErrorMessage, agent.ErrorMessages[0])); } /// <summary> /// Expect returned error message starts with the specified error message /// </summary> /// <param name="expectErrorMessage">Expect error message</param> public void ExpectedStartsWithErrorMessage(string errorMessage) { Test.Assert(agent.ErrorMessages.Count > 0, "Should return error message"); if (agent.ErrorMessages.Count == 0) { return; } Test.Assert(agent.ErrorMessages[0].StartsWith(errorMessage), String.Format("Expected error message should start with {0}, and actualy it's {1}", errorMessage, agent.ErrorMessages[0])); } /// <summary> /// Expect returned error message contain the specified error message /// </summary> /// <param name="expectErrorMessage">Expect error message</param> public void ExpectedContainErrorMessage(string errorMessage) { Test.Assert(agent.ErrorMessages.Count > 0, "Should return error message"); if (agent.ErrorMessages.Count == 0) { return; } Test.Assert(agent.ErrorMessages[0].IndexOf(errorMessage) != -1, String.Format("Expected error message should contain {0}, and actualy it's {1}", errorMessage, agent.ErrorMessages[0])); } /// <summary> /// Expect two string are equal /// </summary> /// <param name="expect">expect string</param> /// <param name="actually">returned string</param> /// <param name="name">Compare name</param> public static void ExpectEqual(string expect, string actually, string name) { Test.Assert(expect == actually, string.Format("{0} should be {1}, and actully it's {2}", name, expect, actually)); } /// <summary> /// Expect two double are equal /// </summary> /// <param name="expect">expect double</param> /// <param name="actually">returned double</param> /// <param name="name">Compare name</param> public static void ExpectEqual(double expect, double actually, string name) { Test.Assert(expect == actually, string.Format("{0} should be {1}, and actully it's {2}", name, expect, actually)); } /// <summary> /// Expect two string are not equal /// </summary> /// <param name="expect">expect string</param> /// <param name="actually">returned string</param> /// <param name="name">Compare name</param> public static void ExpectNotEqual(string expect, string actually, string name) { Test.Assert(expect != actually, string.Format("{0} should not be {1}, and actully it's {2}", name, expect, actually)); } /// <summary> /// Expect two double are not equal /// </summary> /// <param name="expect">expect double</param> /// <param name="actually">returned double</param> /// <param name="name">Compare name</param> public static void ExpectNotEqual(double expect, double actually, string name) { Test.Assert(expect != actually, string.Format("{0} should not be {1}, and actully it's {2}", name, expect, actually)); } /// <summary> /// Generate a random small int number for test /// </summary> /// <returns>Random int</returns> public int GetRandomTestCount() { int minCount = 1; int maxCount = 10; return random.Next(minCount, maxCount); } /// <summary> /// Generate a random bool /// </summary> /// <returns>Random bool</returns> public bool GetRandomBool() { int switchKey = 0; switchKey = random.Next(0, 2); return switchKey == 0; } } }
// 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; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.CSharp.Analyzers.Maintainability.CSharpAvoidUninstantiatedInternalClasses, Microsoft.CodeQuality.CSharp.Analyzers.Maintainability.CSharpAvoidUninstantiatedInternalClassesFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.VisualBasic.Analyzers.Maintainability.BasicAvoidUninstantiatedInternalClasses, Microsoft.CodeQuality.VisualBasic.Analyzers.Maintainability.BasicAvoidUninstantiatedInternalClassesFixer>; namespace Microsoft.CodeQuality.Analyzers.Maintainability.UnitTests { public class AvoidUninstantiatedInternalClassesTests { [Fact] public async Task CA1812_CSharp_Diagnostic_UninstantiatedInternalClass() { await VerifyCS.VerifyAnalyzerAsync( @"internal class C { } ", GetCSharpResultAt(1, 16, "C")); } [Fact] public async Task CA1812_Basic_Diagnostic_UninstantiatedInternalClass() { await VerifyVB.VerifyAnalyzerAsync( @"Friend Class C End Class", GetBasicResultAt(1, 14, "C")); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_UninstantiatedInternalStruct() { await VerifyCS.VerifyAnalyzerAsync( @"internal struct CInternal { }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_UninstantiatedInternalStruct() { await VerifyVB.VerifyAnalyzerAsync( @"Friend Structure CInternal End Structure"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_UninstantiatedPublicClass() { await VerifyCS.VerifyAnalyzerAsync( @"public class C { }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_UninstantiatedPublicClass() { await VerifyVB.VerifyAnalyzerAsync( @"Public Class C End Class"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_InstantiatedInternalClass() { await VerifyCS.VerifyAnalyzerAsync( @"internal class C { } public class D { private readonly C _c = new C(); }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_InstantiatedInternalClass() { await VerifyVB.VerifyAnalyzerAsync( @"Friend Class C End Class Public Class D Private _c As New C End Class"); } [Fact] public async Task CA1812_CSharp_Diagnostic_UninstantiatedInternalClassNestedInPublicClass() { await VerifyCS.VerifyAnalyzerAsync( @"public class C { internal class D { } }", GetCSharpResultAt(3, 20, "C.D")); } [Fact] public async Task CA1812_Basic_Diagnostic_UninstantiatedInternalClassNestedInPublicClass() { await VerifyVB.VerifyAnalyzerAsync( @"Public Class C Friend Class D End Class End Class", GetBasicResultAt(2, 18, "C.D")); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_InstantiatedInternalClassNestedInPublicClass() { await VerifyCS.VerifyAnalyzerAsync( @"public class C { private readonly D _d = new D(); internal class D { } }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_InstantiatedInternalClassNestedInPublicClass() { await VerifyVB.VerifyAnalyzerAsync( @"Public Class C Private ReadOnly _d = New D Friend Class D End Class End Class"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_InternalModule() { // No static classes in VB. await VerifyVB.VerifyAnalyzerAsync( @"Friend Module M End Module"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_InternalAbstractClass() { await VerifyCS.VerifyAnalyzerAsync( @"internal abstract class A { }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_InternalAbstractClass() { await VerifyVB.VerifyAnalyzerAsync( @"Friend MustInherit Class A End Class"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_InternalDelegate() { await VerifyCS.VerifyAnalyzerAsync(@" namespace N { internal delegate void Del(); }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_InternalDelegate() { await VerifyVB.VerifyAnalyzerAsync(@" Namespace N Friend Delegate Sub Del() End Namespace"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_InternalEnum() { await VerifyCS.VerifyAnalyzerAsync( @"namespace N { internal enum E {} // C# enums don't care if there are any members. }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_InternalEnum() { await VerifyVB.VerifyAnalyzerAsync( @"Namespace N Friend Enum E None ' VB enums require at least one member. End Enum End Namespace"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_AttributeClass() { await VerifyCS.VerifyAnalyzerAsync( @"using System; internal class MyAttribute: Attribute {} internal class MyOtherAttribute: MyAttribute {}"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_AttributeClass() { await VerifyVB.VerifyAnalyzerAsync( @"Imports System Friend Class MyAttribute Inherits Attribute End Class Friend Class MyOtherAttribute Inherits MyAttribute End Class"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningVoid() { await new VerifyCS.Test { TestCode = @"internal class C { private static void Main() {} }", SolutionTransforms = { (solution, projectId) => { var compilationOptions = solution.GetProject(projectId).CompilationOptions; return solution.WithProjectCompilationOptions(projectId, compilationOptions.WithOutputKind(OutputKind.ConsoleApplication)); } } }.RunAsync(); } [Fact] public async Task CA1812_Basic_NoDiagnostic_TypeContainingAssemblyEntryPointReturningVoid() { await new VerifyVB.Test { TestCode = @"Friend Class C Public Shared Sub Main() End Sub End Class", SolutionTransforms = { (solution, projectId) => { var compilationOptions = solution.GetProject(projectId).CompilationOptions; return solution.WithProjectCompilationOptions(projectId, compilationOptions.WithOutputKind(OutputKind.ConsoleApplication)); } } }.RunAsync(); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningInt() { await new VerifyCS.Test { TestCode = @"internal class C { private static int Main() { return 1; } }", SolutionTransforms = { (solution, projectId) => { var compilationOptions = solution.GetProject(projectId).CompilationOptions; return solution.WithProjectCompilationOptions(projectId, compilationOptions.WithOutputKind(OutputKind.ConsoleApplication)); } } }.RunAsync(); } [Fact] public async Task CA1812_Basic_NoDiagnostic_TypeContainingAssemblyEntryPointReturningInt() { await new VerifyVB.Test { TestCode = @"Friend Class C Public Shared Function Main() As Integer Return 1 End Function End Class", SolutionTransforms = { (solution, projectId) => { var compilationOptions = solution.GetProject(projectId).CompilationOptions; return solution.WithProjectCompilationOptions(projectId, compilationOptions.WithOutputKind(OutputKind.ConsoleApplication)); } } }.RunAsync(); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningTask() { await new VerifyCS.Test { TestCode = @" using System.Threading.Tasks; internal static class C { private static async Task Main() { await Task.Delay(1); } }", LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp7_1, SolutionTransforms = { (solution, projectId) => { var compilationOptions = solution.GetProject(projectId).CompilationOptions; return solution.WithProjectCompilationOptions(projectId, compilationOptions.WithOutputKind(OutputKind.ConsoleApplication)); } } }.RunAsync(); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningTaskInt() { await new VerifyCS.Test { TestCode = @" using System.Threading.Tasks; internal static class C { private static async Task<int> Main() { await Task.Delay(1); return 1; } }", LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp7_1, SolutionTransforms = { (solution, projectId) => { var compilationOptions = solution.GetProject(projectId).CompilationOptions; return solution.WithProjectCompilationOptions(projectId, compilationOptions.WithOutputKind(OutputKind.ConsoleApplication)); } } }.RunAsync(); } [Fact] public async Task CA1812_CSharp_Diagnostic_MainMethodIsNotStatic() { await VerifyCS.VerifyAnalyzerAsync( @"internal class C { private void Main() {} }", GetCSharpResultAt(1, 16, "C")); } [Fact] public async Task CA1812_Basic_Diagnostic_MainMethodIsNotStatic() { await VerifyVB.VerifyAnalyzerAsync( @"Friend Class C Private Sub Main() End Sub End Class", GetBasicResultAt(1, 14, "C")); } [Fact] public async Task CA1812_Basic_NoDiagnostic_MainMethodIsDifferentlyCased() { await new VerifyVB.Test { TestCode = @"Friend Class C Private Shared Sub mAiN() End Sub End Class", SolutionTransforms = { (solution, projectId) => { var compilationOptions = solution.GetProject(projectId).CompilationOptions; return solution.WithProjectCompilationOptions(projectId, compilationOptions.WithOutputKind(OutputKind.ConsoleApplication)); } }, ExpectedDiagnostics = { // error BC30737: No accessible 'Main' method with an appropriate signature was found in 'TestProject'. DiagnosticResult.CompilerError("BC30737"), } }.RunAsync(); } // The following tests are just to ensure that the messages are formatted properly // for types within namespaces. [Fact] public async Task CA1812_CSharp_Diagnostic_UninstantiatedInternalClassInNamespace() { await VerifyCS.VerifyAnalyzerAsync( @"namespace N { internal class C { } }", GetCSharpResultAt(3, 20, "C")); } [Fact] public async Task CA1812_Basic_Diagnostic_UninstantiatedInternalClassInNamespace() { await VerifyVB.VerifyAnalyzerAsync( @"Namespace N Friend Class C End Class End Namespace", GetBasicResultAt(2, 18, "C")); } [Fact] public async Task CA1812_CSharp_Diagnostic_UninstantiatedInternalClassNestedInPublicClassInNamespace() { await VerifyCS.VerifyAnalyzerAsync( @"namespace N { public class C { internal class D { } } }", GetCSharpResultAt(5, 24, "C.D")); } [Fact] public async Task CA1812_Basic_Diagnostic_UninstantiatedInternalClassNestedInPublicClassInNamespace() { await VerifyVB.VerifyAnalyzerAsync( @"Namespace N Public Class C Friend Class D End Class End Class End Namespace", GetBasicResultAt(3, 22, "C.D")); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_UninstantiatedInternalMef1ExportedClass() { await VerifyCS.VerifyAnalyzerAsync( @"using System; using System.ComponentModel.Composition; namespace System.ComponentModel.Composition { public class ExportAttribute: Attribute { } } [Export] internal class C { }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_UninstantiatedInternalMef1ExportedClass() { await VerifyVB.VerifyAnalyzerAsync( @"Imports System Imports System.ComponentModel.Composition Namespace System.ComponentModel.Composition Public Class ExportAttribute Inherits Attribute End Class End Namespace <Export> Friend Class C End Class"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_UninstantiatedInternalMef2ExportedClass() { await VerifyCS.VerifyAnalyzerAsync( @"using System; using System.ComponentModel.Composition; namespace System.ComponentModel.Composition { public class ExportAttribute: Attribute { } } [Export] internal class C { }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_UninstantiatedInternalMef2ExportedClass() { await VerifyVB.VerifyAnalyzerAsync( @"Imports System Imports System.ComponentModel.Composition Namespace System.ComponentModel.Composition Public Class ExportAttribute Inherits Attribute End Class End Namespace <Export> Friend Class C End Class"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_ImplementsIConfigurationSectionHandler() { await VerifyCS.VerifyAnalyzerAsync( @"using System.Configuration; using System.Xml; internal class C : IConfigurationSectionHandler { public object Create(object parent, object configContext, XmlNode section) { return null; } }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_ImplementsIConfigurationSectionHandler() { await VerifyVB.VerifyAnalyzerAsync( @"Imports System.Configuration Imports System.Xml Friend Class C Implements IConfigurationSectionHandler Private Function IConfigurationSectionHandler_Create(parent As Object, configContext As Object, section As XmlNode) As Object Implements IConfigurationSectionHandler.Create Return Nothing End Function End Class"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_DerivesFromConfigurationSection() { await VerifyCS.VerifyAnalyzerAsync( @"using System.Configuration; namespace System.Configuration { public class ConfigurationSection { } } internal class C : ConfigurationSection { }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_DerivesFromConfigurationSection() { await VerifyVB.VerifyAnalyzerAsync( @"Imports System.Configuration Namespace System.Configuration Public Class ConfigurationSection End Class End Namespace Friend Class C Inherits ConfigurationSection End Class"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_DerivesFromSafeHandle() { await VerifyCS.VerifyAnalyzerAsync( @"using System; using System.Runtime.InteropServices; internal class MySafeHandle : SafeHandle { protected MySafeHandle(IntPtr invalidHandleValue, bool ownsHandle) : base(invalidHandleValue, ownsHandle) { } public override bool IsInvalid => true; protected override bool ReleaseHandle() { return true; } }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_DerivesFromSafeHandle() { await VerifyVB.VerifyAnalyzerAsync( @"Imports System Imports System.Runtime.InteropServices Friend Class MySafeHandle Inherits SafeHandle Protected Sub New(invalidHandleValue As IntPtr, ownsHandle As Boolean) MyBase.New(invalidHandleValue, ownsHandle) End Sub Public Overrides ReadOnly Property IsInvalid As Boolean Get Return True End Get End Property Protected Overrides Function ReleaseHandle() As Boolean Return True End Function End Class"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_DerivesFromTraceListener() { await VerifyCS.VerifyAnalyzerAsync( @"using System.Diagnostics; internal class MyTraceListener : TraceListener { public override void Write(string message) { } public override void WriteLine(string message) { } }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_DerivesFromTraceListener() { await VerifyVB.VerifyAnalyzerAsync( @"Imports System.Diagnostics Friend Class MyTraceListener Inherits TraceListener Public Overrides Sub Write(message As String) End Sub Public Overrides Sub WriteLine(message As String) End Sub End Class"); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_InternalNestedTypeIsInstantiated() { await VerifyCS.VerifyAnalyzerAsync( @"internal class C { internal class C2 { } } public class D { private readonly C.C2 _c2 = new C.C2(); } "); } [Fact] public async Task CA1812_Basic_NoDiagnostic_InternalNestedTypeIsInstantiated() { await VerifyVB.VerifyAnalyzerAsync( @"Friend Class C Friend Class C2 End Class End Class Public Class D Private _c2 As new C.C2 End Class"); } [Fact] public async Task CA1812_CSharp_Diagnostic_InternalNestedTypeIsNotInstantiated() { await VerifyCS.VerifyAnalyzerAsync( @"internal class C { internal class C2 { } }", GetCSharpResultAt(3, 20, "C.C2")); } [Fact] public async Task CA1812_Basic_Diagnostic_InternalNestedTypeIsNotInstantiated() { await VerifyVB.VerifyAnalyzerAsync( @"Friend Class C Friend Class C2 End Class End Class", GetBasicResultAt(2, 18, "C.C2")); } [Fact] public async Task CA1812_CSharp_Diagnostic_PrivateNestedTypeIsInstantiated() { await VerifyCS.VerifyAnalyzerAsync( @"internal class C { private readonly C2 _c2 = new C2(); private class C2 { } }", GetCSharpResultAt(1, 16, "C")); } [Fact] public async Task CA1812_Basic_Diagnostic_PrivateNestedTypeIsInstantiated() { await VerifyVB.VerifyAnalyzerAsync( @"Friend Class C Private _c2 As New C2 Private Class C2 End Class End Class", GetBasicResultAt(1, 14, "C")); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_StaticHolderClass() { await VerifyCS.VerifyAnalyzerAsync( @"internal static class C { internal static void F() { } }"); } [Fact, WorkItem(1370, "https://github.com/dotnet/roslyn-analyzers/issues/1370")] public async Task CA1812_CSharp_NoDiagnostic_ImplicitlyInstantiatedFromSubTypeConstructor() { await VerifyCS.VerifyAnalyzerAsync( @" internal class A { public A() { } } internal class B : A { public B() { } } internal class C<T> { } internal class D : C<int> { static void M() { var x = new B(); var y = new D(); } }"); } [Fact, WorkItem(1370, "https://github.com/dotnet/roslyn-analyzers/issues/1370")] public async Task CA1812_CSharp_NoDiagnostic_ExplicitlyInstantiatedFromSubTypeConstructor() { await VerifyCS.VerifyAnalyzerAsync( @" internal class A { public A(int x) { } } internal class B : A { public B(int x): base (x) { } } internal class C<T> { } internal class D : C<int> { public D(): base() { } static void M() { var x = new B(0); var y = new D(); } }"); } [Fact] public async Task CA1812_Basic_NoDiagnostic_StaticHolderClass() { await VerifyVB.VerifyAnalyzerAsync( @"Friend Module C Friend Sub F() End Sub End Module"); } [Fact] public async Task CA1812_CSharp_Diagnostic_EmptyInternalStaticClass() { // Note that this is not considered a "static holder class" // because it doesn't actually have any static members. await VerifyCS.VerifyAnalyzerAsync( @"internal static class S { }", GetCSharpResultAt(1, 23, "S")); } [Fact] public async Task CA1812_CSharp_NoDiagnostic_UninstantiatedInternalClassInFriendlyAssembly() { await VerifyCS.VerifyAnalyzerAsync( @"using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""TestProject"")] internal class C { }" ); } [Fact] public async Task CA1812_Basic_NoDiagnostic_UninstantiatedInternalClassInFriendlyAssembly() { await VerifyVB.VerifyAnalyzerAsync( @"Imports System.Runtime.CompilerServices <Assembly: InternalsVisibleToAttribute(""TestProject"")> Friend Class C End Class" ); } [Fact, WorkItem(1370, "https://github.com/dotnet/roslyn-analyzers/issues/1370")] public async Task CA1812_Basic_NoDiagnostic_ImplicitlyInstantiatedFromSubTypeConstructor() { await VerifyVB.VerifyAnalyzerAsync( @" Friend Class A Public Sub New() End Sub End Class Friend Class B Inherits A Public Sub New() End Sub End Class Friend Class C(Of T) End Class Friend Class D Inherits C(Of Integer) Private Shared Sub M() Dim x = New B() Dim y = New D() End Sub End Class"); } [Fact, WorkItem(1370, "https://github.com/dotnet/roslyn-analyzers/issues/1370")] public async Task CA1812_Basic_NoDiagnostic_ExplicitlyInstantiatedFromSubTypeConstructor() { await VerifyVB.VerifyAnalyzerAsync( @" Friend Class A Public Sub New(ByVal x As Integer) End Sub End Class Friend Class B Inherits A Public Sub New(ByVal x As Integer) MyBase.New(x) End Sub End Class Friend Class C(Of T) End Class Friend Class D Inherits C(Of Integer) Public Sub New() MyBase.New() End Sub Private Shared Sub M() Dim x = New B(0) Dim y = New D() End Sub End Class"); } [Fact, WorkItem(1154, "https://github.com/dotnet/roslyn-analyzers/issues/1154")] public async Task CA1812_CSharp_GenericInternalClass_InstanciatedNoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Collections.Generic; using System.Linq; public static class X { public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, Comparison<T> compare) { return source.OrderBy(new ComparisonComparer<T>(compare)); } public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, IComparer<T> comparer) { return source.OrderBy(t => t, comparer); } private class ComparisonComparer<T> : Comparer<T> { private readonly Comparison<T> _compare; public ComparisonComparer(Comparison<T> compare) { _compare = compare; } public override int Compare(T x, T y) { return _compare(x, y); } } } "); } [Fact, WorkItem(1154, "https://github.com/dotnet/roslyn-analyzers/issues/1154")] public async Task CA1812_Basic_GenericInternalClass_InstanciatedNoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Module M <Extension()> Public Function OrderBy(Of T)(ByVal source As IEnumerable(Of T), compare As Comparison(Of T)) As IEnumerable(Of T) Return source.OrderBy(New ComparisonCompare(Of T)(compare)) End Function <Extension()> Public Function OrderBy(Of T)(ByVal source As IEnumerable(Of T), comparer As IComparer(Of T)) As IEnumerable(Of T) Return source.OrderBy(Function(i) i, comparer) End Function Private Class ComparisonCompare(Of T) Inherits Comparer(Of T) Private _compare As Comparison(Of T) Public Sub New(compare As Comparison(Of T)) _compare = compare End Sub Public Overrides Function Compare(x As T, y As T) As Integer Throw New NotImplementedException() End Function End Class End Module "); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public async Task CA1812_CSharp_NoDiagnostic_GenericMethodWithNewConstraint() { await VerifyCS.VerifyAnalyzerAsync(@" using System; internal class InstantiatedType { } internal static class Factory { internal static T Create<T>() where T : new() { return new T(); } } internal class Program { public static void Main(string[] args) { Console.WriteLine(Factory.Create<InstantiatedType>()); } }"); } [Fact, WorkItem(1447, "https://github.com/dotnet/roslyn-analyzers/issues/1447")] public async Task CA1812_CSharp_NoDiagnostic_GenericMethodWithNewConstraintInvokedFromGenericMethod() { await VerifyCS.VerifyAnalyzerAsync(@" internal class InstantiatedClass { public InstantiatedClass() { } } internal class InstantiatedClass2 { public InstantiatedClass2() { } } internal class InstantiatedClass3 { public InstantiatedClass3() { } } internal static class C { private static T Create<T>() where T : new() { return new T(); } public static void M<T>() where T : InstantiatedClass, new() { Create<T>(); } public static void M2<T, T2>() where T : T2, new() where T2 : InstantiatedClass2 { Create<T>(); } public static void M3<T, T2, T3>() where T : T2, new() where T2 : T3 where T3: InstantiatedClass3 { Create<T>(); } public static void M3() { M<InstantiatedClass>(); M2<InstantiatedClass2, InstantiatedClass2>(); M3<InstantiatedClass3, InstantiatedClass3, InstantiatedClass3>(); } }"); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public async Task CA1812_Basic_NoDiagnostic_GenericMethodWithNewConstraint() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Module Module1 Sub Main() Console.WriteLine(Create(Of InstantiatedType)()) End Sub Friend Class InstantiatedType End Class Friend Function Create(Of T As New)() As T Return New T End Function End Module"); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public async Task CA1812_CSharp_NoDiagnostic_GenericTypeWithNewConstraint() { await VerifyCS.VerifyAnalyzerAsync(@" internal class InstantiatedType { } internal class Factory<T> where T : new() { } internal class Program { public static void Main(string[] args) { var factory = new Factory<InstantiatedType>(); } }"); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public async Task CA1812_Basic_NoDiagnostic_GenericTypeWithNewConstraint() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Module Module1 Sub Main() Console.WriteLine(New Factory(Of InstantiatedType)) End Sub Friend Class InstantiatedType End Class Friend Class Factory(Of T As New) End Class End Module"); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public async Task CA1812_CSharp_Diagnostic_NestedGenericTypeWithNoNewConstraint() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Collections.Generic; internal class InstantiatedType { } internal class Factory<T> where T : new() { } internal class Program { public static void Main(string[] args) { var list = new List<Factory<InstantiatedType>>(); } }", GetCSharpResultAt(4, 16, "InstantiatedType"), GetCSharpResultAt(8, 16, "Factory<T>")); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public async Task CA1812_Basic_Diagnostic_NestedGenericTypeWithNoNewConstraint() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Collections.Generic Module Library Friend Class InstantiatedType End Class Friend Class Factory(Of T As New) End Class Sub Main() Dim a = New List(Of Factory(Of InstantiatedType)) End Sub End Module", GetBasicResultAt(5, 18, "Library.InstantiatedType"), GetBasicResultAt(8, 18, "Library.Factory(Of T)")); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public async Task CA1812_CSharp_NoDiagnostic_NestedGenericTypeWithNewConstraint() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Collections.Generic; internal class InstantiatedType { } internal class Factory1<T> where T : new() { } internal class Factory2<T> where T : new() { } internal class Program { public static void Main(string[] args) { var factory = new Factory1<Factory2<InstantiatedType>>(); } }"); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public async Task CA1812_Basic_NoDiagnostic_NestedGenericTypeWithNewConstraint() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Collections.Generic Module Library Friend Class InstantiatedType End Class Friend Class Factory1(Of T As New) End Class Friend Class Factory2(Of T As New) End Class Sub Main() Dim a = New Factory1(Of Factory2(Of InstantiatedType)) End Sub End Module"); } [Fact, WorkItem(1739, "https://github.com/dotnet/roslyn-analyzers/issues/1739")] public async Task CA1812_CSharp_NoDiagnostic_GenericTypeWithRecursiveConstraint() { await VerifyCS.VerifyAnalyzerAsync(@" public abstract class JobStateBase<TState> where TState : JobStateBase<TState>, new() { public void SomeFunction () { new JobStateChangeHandler<TState>(); } } public class JobStateChangeHandler<TState> where TState : JobStateBase<TState>, new() { } "); } [Fact, WorkItem(2751, "https://github.com/dotnet/roslyn-analyzers/issues/2751")] public async Task CA1812_CSharp_NoDiagnostic_TypeDeclaredInCoClassAttribute() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Runtime.InteropServices; [CoClass(typeof(CSomeClass))] internal interface ISomeInterface {} internal class CSomeClass {} "); } [Fact, WorkItem(2751, "https://github.com/dotnet/roslyn-analyzers/issues/2751")] public async Task CA1812_CSharp_DontFailOnInvalidCoClassUsages() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Runtime.InteropServices; [{|CS7036:CoClass|}] internal interface ISomeInterface1 {} [CoClass({|CS0119:CSomeClass|})] internal interface ISomeInterface2 {} [{|CS1729:CoClass(typeof(CSomeClass), null)|}] internal interface ISomeInterface3 {} [CoClass(typeof(ISomeInterface3))] // This isn't a class-type internal interface ISomeInterface4 {} internal class CSomeClass {} ", // Test0.cs(16,16): warning CA1812: CSomeClass is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static members, make it static (Shared in Visual Basic). GetCSharpResultAt(16, 16, "CSomeClass")); } [Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")] public async Task CA1812_DesignerAttributeTypeName_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.ComponentModel; namespace SomeNamespace { internal class MyTextBoxDesigner { } [Designer(""SomeNamespace.MyTextBoxDesigner, TestProject"")] public class MyTextBox { } }"); } [Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")] public async Task CA1812_DesignerAttributeTypeNameWithFullAssemblyName_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.ComponentModel; namespace SomeNamespace { internal class MyTextBoxDesigner { } [Designer(""SomeNamespace.MyTextBoxDesigner, TestProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=123"")] public class MyTextBox { } }"); } [Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")] public async Task CA1812_DesignerAttributeGlobalTypeName_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.ComponentModel; internal class MyTextBoxDesigner { } [Designer(""MyTextBoxDesigner, TestProject"")] public class MyTextBox { }"); } [Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")] public async Task CA1812_DesignerAttributeType_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.ComponentModel; namespace SomeNamespace { internal class MyTextBoxDesigner { } [Designer(typeof(MyTextBoxDesigner))] public class MyTextBox { } }"); } [Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")] public async Task CA1812_DesignerAttributeTypeNameWithBaseTypeName_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.ComponentModel; namespace SomeNamespace { public class SomeBaseType { } internal class MyTextBoxDesigner { } [Designer(""SomeNamespace.MyTextBoxDesigner, TestProject"", ""SomeNamespace.SomeBaseType"")] public class MyTextBox { } }"); } [Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")] public async Task CA1812_DesignerAttributeTypeNameWithBaseType_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.ComponentModel; namespace SomeNamespace { public class SomeBaseType { } internal class MyTextBoxDesigner { } [Designer(""SomeNamespace.MyTextBoxDesigner, TestProject"", typeof(SomeBaseType))] public class MyTextBox { } }"); } [Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")] public async Task CA1812_DesignerAttributeTypeWithBaseType_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.ComponentModel; namespace SomeNamespace { public class SomeBaseType { } internal class MyTextBoxDesigner { } [Designer(typeof(SomeNamespace.MyTextBoxDesigner), typeof(SomeBaseType))] public class MyTextBox { } }"); } [Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")] public async Task CA1812_DesignerAttributeNestedTypeName_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.ComponentModel; namespace SomeNamespace { [Designer(""SomeNamespace.MyTextBox.MyTextBoxDesigner, TestProject"")] public class MyTextBox { internal class MyTextBoxDesigner { } } }", // False-Positive: when evaluating the string of the DesignerAttribute the type symbol doesn't exist yet GetCSharpResultAt(10, 24, "MyTextBox.MyTextBoxDesigner")); } [Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")] public async Task CA1812_DesignerAttributeNestedType_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.ComponentModel; namespace SomeNamespace { [Designer(typeof(SomeNamespace.MyTextBox.MyTextBoxDesigner))] public class MyTextBox { internal class MyTextBoxDesigner { } } }"); } [Fact, WorkItem(3199, "https://github.com/dotnet/roslyn-analyzers/issues/3199")] public async Task CA1812_AliasingTypeNewConstraint_NoDiagnostic() { await new VerifyCS.Test { TestState = { Sources = { @" using System; namespace SomeNamespace { public class MyAliasType<T> where T : class, new() { public static void DoSomething() {} } internal class C {} }", @" using MyAliasOfC = SomeNamespace.MyAliasType<SomeNamespace.C>; using MyAliasOfMyAliasOfC = SomeNamespace.MyAliasType<SomeNamespace.MyAliasType<SomeNamespace.C>>; public class CC { public void M() { MyAliasOfC.DoSomething(); MyAliasOfMyAliasOfC.DoSomething(); } } ", }, }, }.RunAsync(); } private static DiagnosticResult GetCSharpResultAt(int line, int column, string className) => VerifyCS.Diagnostic() .WithLocation(line, column) .WithArguments(className); private static DiagnosticResult GetBasicResultAt(int line, int column, string className) => VerifyVB.Diagnostic() .WithLocation(line, column) .WithArguments(className); } }
// 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.Diagnostics; using System.Threading.Tasks; using Xunit; namespace System.Threading.Tests { public class SemaphoreTests : RemoteExecutorTestBase { private const int FailedWaitTimeout = 30000; [Theory] [InlineData(0, 1)] [InlineData(1, 1)] [InlineData(1, 2)] [InlineData(0, int.MaxValue)] [InlineData(int.MaxValue, int.MaxValue)] public void Ctor_InitialAndMax(int initialCount, int maximumCount) { new Semaphore(initialCount, maximumCount).Dispose(); new Semaphore(initialCount, maximumCount, null).Dispose(); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void Ctor_ValidName_Windows() { string name = Guid.NewGuid().ToString("N"); new Semaphore(0, 1, name).Dispose(); bool createdNew; new Semaphore(0, 1, name, out createdNew).Dispose(); Assert.True(createdNew); } [PlatformSpecific(TestPlatforms.AnyUnix)] // named semaphores aren't supported on Unix [Fact] public void Ctor_NamesArentSupported_Unix() { string name = Guid.NewGuid().ToString("N"); Assert.Throws<PlatformNotSupportedException>(() => new Semaphore(0, 1, name)); Assert.Throws<PlatformNotSupportedException>(() => { bool createdNew; new Semaphore(0, 1, name, out createdNew).Dispose(); }); } [Fact] public void Ctor_InvalidArguments() { bool createdNew; Assert.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-1, 1)); Assert.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-2, 1)); Assert.Throws<ArgumentOutOfRangeException>("maximumCount", () => new Semaphore(0, 0)); Assert.Throws<ArgumentException>(() => new Semaphore(2, 1)); Assert.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-1, 1, null)); Assert.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-2, 1, null)); Assert.Throws<ArgumentOutOfRangeException>("maximumCount", () => new Semaphore(0, 0, null)); Assert.Throws<ArgumentException>(() => new Semaphore(2, 1, null)); Assert.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-1, 1, "CtorSemaphoreTest", out createdNew)); Assert.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-2, 1, "CtorSemaphoreTest", out createdNew)); Assert.Throws<ArgumentOutOfRangeException>("maximumCount", () => new Semaphore(0, 0, "CtorSemaphoreTest", out createdNew)); Assert.Throws<ArgumentException>(() => new Semaphore(2, 1, "CtorSemaphoreTest", out createdNew)); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void Ctor_InvalidNames() { Assert.Throws<ArgumentException>(() => new Semaphore(0, 1, new string('a', 10000))); bool createdNew; Assert.Throws<ArgumentException>(() => new Semaphore(0, 1, new string('a', 10000), out createdNew)); } [Fact] public void CanWaitWithoutBlockingUntilNoCount() { const int InitialCount = 5; using (Semaphore s = new Semaphore(InitialCount, InitialCount)) { for (int i = 0; i < InitialCount; i++) Assert.True(s.WaitOne(0)); Assert.False(s.WaitOne(0)); } } [Fact] public void CanWaitWithoutBlockingForReleasedCount() { using (Semaphore s = new Semaphore(0, Int32.MaxValue)) { for (int counts = 1; counts < 5; counts++) { Assert.False(s.WaitOne(0)); if (counts % 2 == 0) { for (int i = 0; i < counts; i++) s.Release(); } else { s.Release(counts); } for (int i = 0; i < counts; i++) { Assert.True(s.WaitOne(0)); } Assert.False(s.WaitOne(0)); } } } [Fact] public void Release() { using (Semaphore s = new Semaphore(1, 1)) { Assert.Throws<SemaphoreFullException>(() => s.Release()); } using (Semaphore s = new Semaphore(0, 10)) { Assert.Throws<SemaphoreFullException>(() => s.Release(11)); Assert.Throws<ArgumentOutOfRangeException>("releaseCount", () => s.Release(-1)); } using (Semaphore s = new Semaphore(0, 10)) { for (int i = 0; i < 10; i++) { Assert.Equal(i, s.Release()); } } } [Fact] public void AnonymousProducerConsumer() { using (Semaphore s = new Semaphore(0, Int32.MaxValue)) { const int NumItems = 5; Task.WaitAll( Task.Factory.StartNew(() => { for (int i = 0; i < NumItems; i++) Assert.True(s.WaitOne(FailedWaitTimeout)); Assert.False(s.WaitOne(0)); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default), Task.Factory.StartNew(() => { for (int i = 0; i < NumItems; i++) s.Release(); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)); } } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void NamedProducerConsumer() { string name = Guid.NewGuid().ToString("N"); const int NumItems = 5; var b = new Barrier(2); Task.WaitAll( Task.Factory.StartNew(() => { using (var s = new Semaphore(0, int.MaxValue, name)) { Assert.True(b.SignalAndWait(FailedWaitTimeout)); for (int i = 0; i < NumItems; i++) Assert.True(s.WaitOne(FailedWaitTimeout)); Assert.False(s.WaitOne(0)); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default), Task.Factory.StartNew(() => { using (var s = new Semaphore(0, int.MaxValue, name)) { Assert.True(b.SignalAndWait(FailedWaitTimeout)); for (int i = 0; i < NumItems; i++) s.Release(); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)); } [PlatformSpecific(TestPlatforms.AnyUnix)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_NotSupported_Unix() { Assert.Throws<PlatformNotSupportedException>(() => Semaphore.OpenExisting(null)); Assert.Throws<PlatformNotSupportedException>(() => Semaphore.OpenExisting(string.Empty)); Assert.Throws<PlatformNotSupportedException>(() => Semaphore.OpenExisting("anything")); Semaphore semaphore; Assert.Throws<PlatformNotSupportedException>(() => Semaphore.TryOpenExisting("anything", out semaphore)); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_InvalidNames_Windows() { Assert.Throws<ArgumentNullException>("name", () => Semaphore.OpenExisting(null)); Assert.Throws<ArgumentException>(() => Semaphore.OpenExisting(string.Empty)); Assert.Throws<ArgumentException>(() => Semaphore.OpenExisting(new string('a', 10000))); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_UnavailableName_Windows() { string name = Guid.NewGuid().ToString("N"); Assert.Throws<WaitHandleCannotBeOpenedException>(() => Semaphore.OpenExisting(name)); Semaphore ignored; Assert.False(Semaphore.TryOpenExisting(name, out ignored)); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows() { string name = Guid.NewGuid().ToString("N"); using (Mutex mtx = new Mutex(true, name)) { Assert.Throws<WaitHandleCannotBeOpenedException>(() => Semaphore.OpenExisting(name)); Semaphore ignored; Assert.False(Semaphore.TryOpenExisting(name, out ignored)); } } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_SameAsOriginal_Windows() { string name = Guid.NewGuid().ToString("N"); bool createdNew; using (Semaphore s1 = new Semaphore(0, Int32.MaxValue, name, out createdNew)) { Assert.True(createdNew); using (Semaphore s2 = Semaphore.OpenExisting(name)) { Assert.False(s1.WaitOne(0)); Assert.False(s2.WaitOne(0)); s1.Release(); Assert.True(s2.WaitOne(0)); Assert.False(s2.WaitOne(0)); s2.Release(); Assert.True(s1.WaitOne(0)); Assert.False(s1.WaitOne(0)); } Semaphore s3; Assert.True(Semaphore.TryOpenExisting(name, out s3)); using (s3) { Assert.False(s1.WaitOne(0)); Assert.False(s3.WaitOne(0)); s1.Release(); Assert.True(s3.WaitOne(0)); Assert.False(s3.WaitOne(0)); s3.Release(); Assert.True(s1.WaitOne(0)); Assert.False(s1.WaitOne(0)); } } } [PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix [Fact] public void PingPong() { // Create names for the two semaphores string outboundName = Guid.NewGuid().ToString("N"); string inboundName = Guid.NewGuid().ToString("N"); // Create the two semaphores and the other process with which to synchronize using (var inbound = new Semaphore(1, 1, inboundName)) using (var outbound = new Semaphore(0, 1, outboundName)) using (var remote = RemoteInvoke(PingPong_OtherProcess, outboundName, inboundName)) { // Repeatedly wait for count in one semaphore and then release count into the other for (int i = 0; i < 10; i++) { Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds)); outbound.Release(); } } } private static int PingPong_OtherProcess(string inboundName, string outboundName) { // Open the two semaphores using (var inbound = Semaphore.OpenExisting(inboundName)) using (var outbound = Semaphore.OpenExisting(outboundName)) { // Repeatedly wait for count in one semaphore and then release count into the other for (int i = 0; i < 10; i++) { Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds)); outbound.Release(); } } return SuccessExitCode; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.Compiler.Common; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.Tools.Compiler; namespace Microsoft.DotNet.Tools.Build { internal class DotNetProjectBuilder : ProjectBuilder { private readonly BuildCommandApp _args; private readonly IncrementalPreconditionManager _preconditionManager; private readonly CompilerIOManager _compilerIOManager; private readonly ScriptRunner _scriptRunner; private readonly DotNetCommandFactory _commandFactory; private readonly IncrementalManager _incrementalManager; public DotNetProjectBuilder(BuildCommandApp args) : base(args.ShouldSkipDependencies) { _args = args; _preconditionManager = new IncrementalPreconditionManager( args.ShouldPrintIncrementalPreconditions, args.ShouldNotUseIncrementality, args.ShouldSkipDependencies); _compilerIOManager = new CompilerIOManager( args.ConfigValue, args.OutputValue, args.BuildBasePathValue, args.GetRuntimes(), args.Workspace ); _incrementalManager = new IncrementalManager( this, _compilerIOManager, _preconditionManager, _args.ShouldSkipDependencies, _args.ConfigValue, _args.BuildBasePathValue, _args.OutputValue ); _scriptRunner = new ScriptRunner(); _commandFactory = new DotNetCommandFactory(); } private void StampProjectWithSDKVersion(ProjectContext project) { if (File.Exists(DotnetFiles.VersionFile)) { var projectVersionFile = project.GetSDKVersionFile(_args.ConfigValue, _args.BuildBasePathValue, _args.OutputValue); var parentDirectory = Path.GetDirectoryName(projectVersionFile); if (!Directory.Exists(parentDirectory)) { Directory.CreateDirectory(parentDirectory); } string content = DotnetFiles.ReadAndInterpretVersionFile(); File.WriteAllText(projectVersionFile, content); } else { Reporter.Verbose.WriteLine($"Project {project.GetDisplayName()} was not stamped with a CLI version because the version file does not exist: {DotnetFiles.VersionFile}"); } } private void PrintSummary(ProjectGraphNode projectNode, bool success) { // todo: Ideally it's the builder's responsibility for adding the time elapsed. That way we avoid cross cutting display concerns between compile and build for printing time elapsed if (success) { var preconditions = _preconditionManager.GetIncrementalPreconditions(projectNode); Reporter.Output.Write(" " + preconditions.LogMessage()); Reporter.Output.WriteLine(); } Reporter.Output.WriteLine(); } private void CopyCompilationOutput(OutputPaths outputPaths) { var dest = outputPaths.RuntimeOutputPath; var source = outputPaths.CompilationOutputPath; // No need to copy if dest and source are the same if (string.Equals(dest, source, StringComparison.OrdinalIgnoreCase)) { return; } foreach (var file in outputPaths.CompilationFiles.All()) { var destFileName = file.Replace(source, dest); var directoryName = Path.GetDirectoryName(destFileName); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } File.Copy(file, destFileName, true); } } private void MakeRunnable(ProjectGraphNode graphNode) { try { var runtimeContext = graphNode.ProjectContext.ProjectFile.HasRuntimeOutput(_args.ConfigValue) ? _args.Workspace.GetRuntimeContext(graphNode.ProjectContext, _args.GetRuntimes()) : graphNode.ProjectContext; var outputPaths = runtimeContext.GetOutputPaths(_args.ConfigValue, _args.BuildBasePathValue, _args.OutputValue); var libraryExporter = runtimeContext.CreateExporter(_args.ConfigValue, _args.BuildBasePathValue); CopyCompilationOutput(outputPaths); var executable = new Executable(runtimeContext, outputPaths, libraryExporter, _args.ConfigValue); executable.MakeCompilationOutputRunnable(); } catch (Exception e) { throw new Exception($"Failed to make the following project runnable: {graphNode.ProjectContext.GetDisplayName()} reason: {e.Message}", e); } } protected override CompilationResult Build(ProjectGraphNode projectNode) { var result = base.Build(projectNode); AfterRootBuild(projectNode, result); return result; } protected void AfterRootBuild(ProjectGraphNode projectNode, CompilationResult result) { if (result != CompilationResult.IncrementalSkip && projectNode.IsRoot) { var success = result == CompilationResult.Success; if (success) { MakeRunnable(projectNode); } PrintSummary(projectNode, success); } } protected override CompilationResult RunCompile(ProjectGraphNode projectNode) { try { var managedCompiler = new ManagedCompiler(_scriptRunner, _commandFactory); var success = managedCompiler.Compile(projectNode.ProjectContext, _args); return success ? CompilationResult.Success : CompilationResult.Failure; } finally { StampProjectWithSDKVersion(projectNode.ProjectContext); _incrementalManager.CacheIncrementalState(projectNode); } } protected override void ProjectSkiped(ProjectGraphNode projectNode) { StampProjectWithSDKVersion(projectNode.ProjectContext); _incrementalManager.CacheIncrementalState(projectNode); } protected override bool NeedsRebuilding(ProjectGraphNode graphNode) { var result = _incrementalManager.NeedsRebuilding(graphNode); PrintIncrementalResult(graphNode.ProjectContext.GetDisplayName(), result); return result.NeedsRebuilding; } private void PrintIncrementalResult(string projectName, IncrementalResult result) { if (result.NeedsRebuilding) { Reporter.Output.WriteLine($"Project {projectName} will be compiled because {result.Reason}"); PrintIncrementalItems(result); } else { Reporter.Output.WriteLine($"Project {projectName} was previously compiled. Skipping compilation."); } } private static void PrintIncrementalItems(IncrementalResult result) { if (Reporter.IsVerbose) { foreach (var item in result.Items) { Reporter.Verbose.WriteLine($"\t{item}"); } } } } }
// // DateRangeDialog.cs // // Author: // Stephane Delcroix <[email protected]> // Bengt Thuree <[email protected]> // // Copyright (C) 2007-2009 Novell, Inc. // Copyright (C) 2007-2009 Stephane Delcroix // Copyright (C) 2007 Bengt Thuree // // 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 Gtk; using System; using Mono.Unix; using FSpot.Query; using FSpot.Widgets; namespace FSpot.UI.Dialog { public class DateRangeDialog : BuilderDialog { [GtkBeans.Builder.Object] Frame startframe; [GtkBeans.Builder.Object] Frame endframe; [GtkBeans.Builder.Object] ComboBox period_combobox; DateEdit start_dateedit; DateEdit end_dateedit; TreeStore rangestore; static string [] ranges = { "today", "yesterday", "last7days", "last30days", "last90days", "last360days", "currentweek", "previousweek", "thismonth", "previousmonth", "thisyear", "previousyear", "alldates", "customizedrange" }; public DateRangeDialog (DateRange query_range, Gtk.Window parent_window) : base ("DateRangeDialog.ui", "date_range_dialog") { TransientFor = parent_window; DefaultResponse = ResponseType.Ok; (startframe.Child as Bin).Child = start_dateedit = new DateEdit (); start_dateedit.Show (); (endframe.Child as Bin).Child = end_dateedit = new DateEdit (); end_dateedit.Show (); var cell_renderer = new CellRendererText (); // Build the combo box with years and month names period_combobox.Model = rangestore = new TreeStore (typeof (string)); period_combobox.PackStart (cell_renderer, true); period_combobox.SetCellDataFunc (cell_renderer, new CellLayoutDataFunc (RangeCellFunc)); foreach (string range in ranges) rangestore.AppendValues (GetString(range)); period_combobox.Changed += HandlePeriodComboboxChanged; period_combobox.Active = System.Array.IndexOf(ranges, "last7days"); // Default to Last 7 days if (query_range != null) { start_dateedit.DateTimeOffset = query_range.Start; end_dateedit.DateTimeOffset = query_range.End; } } void RangeCellFunc (CellLayout cell_layout, CellRenderer cell, TreeModel tree_model, TreeIter iter) { string name = (string)tree_model.GetValue (iter, 0); (cell as CellRendererText).Text = name; } private string GetString(string rangename) { System.DateTime today = System.DateTime.Today; switch (rangename) { case "today": return Catalog.GetString("Today"); case "yesterday": return Catalog.GetString("Yesterday"); case "last7days": return Catalog.GetString("Last 7 days"); case "last30days": return Catalog.GetString("Last 30 days"); case "last90days": return Catalog.GetString("Last 90 days"); case "last360days": return Catalog.GetString("Last 360 days"); case "currentweek": return Catalog.GetString("Current Week (Mon-Sun)"); case "previousweek": return Catalog.GetString("Previous Week (Mon-Sun)"); case "thismonth": if (today.Year == (today.AddMonths(-1)).Year) // Same year for current and previous month. Present only MONTH return today.ToString("MMMM"); else // Different year for current and previous month. Present both MONTH, and YEAR return today.ToString("MMMM, yyyy"); case "previousmonth": if (today.Year == (today.AddMonths(-1)).Year) // Same year for current and previous month. Present only MONTH return (today.AddMonths(-1)).ToString("MMMM"); else // Different year for current and previous month. Present both MONTH, and YEAR return (today.AddMonths(-1)).ToString("MMMM, yyyy"); case "thisyear": return today.ToString("yyyy"); case "previousyear": return today.AddYears(-1).ToString("yyyy"); case "alldates": return Catalog.GetString("All Images"); case "customizedrange": return Catalog.GetString("Customized Range"); default: return rangename; } } public DateRange Range { get { return QueryRange (period_combobox.Active); } } private DateRange QueryRange (int index) { return QueryRange ( ranges [index]); } private DateRange QueryRange (string rangename) { System.DateTime today = System.DateTime.Today; System.DateTime startdate = today; System.DateTime enddate = today; bool clear = false; switch (rangename) { case "today": startdate = today; enddate = today; break; case "yesterday": startdate = today.AddDays (-1); enddate = today.AddDays (-1); break; case "last7days": startdate = today.AddDays (-6); enddate = today; break; case "last30days": startdate = today.AddDays (-29); enddate = today; break; case "last90days": startdate = today.AddDays (-89); enddate = today; break; case "last360days": startdate = today.AddDays (-359); enddate = today; break; case "currentweek": startdate = today.AddDays (System.DayOfWeek.Sunday - today.DayOfWeek); // Gets to Sunday startdate = startdate.AddDays (1); // Advance to Monday according to ISO 8601 enddate = today; break; case "previousweek": startdate = today.AddDays (System.DayOfWeek.Sunday - today.DayOfWeek); // Gets to Sunday startdate = startdate.AddDays (1); // Advance to Monday according to ISO 8601 startdate = startdate.AddDays(-7); // Back 7 days enddate = startdate.AddDays (6); break; case "thismonth": startdate = new System.DateTime(today.Year, today.Month, 1); // the first of the month enddate = today; // we don't have pictures in the future break; case "previousmonth": startdate = new System.DateTime((today.AddMonths(-1)).Year, (today.AddMonths(-1)).Month, 1); enddate = new System.DateTime((today.AddMonths(-1)).Year, (today.AddMonths(-1)).Month, System.DateTime.DaysInMonth((today.AddMonths(-1)).Year,(today.AddMonths(-1)).Month)); break; case "thisyear": startdate = new System.DateTime(today.Year, 1, 1); // Jan 1st of this year enddate = today; break; case "previousyear": startdate = new System.DateTime((today.AddYears(-1)).Year, 1, 1); // Jan 1st of prev year enddate = new System.DateTime((today.AddYears(-1)).Year, 12, 31); // Dec, 31 of prev year break; case "alldates": clear = true; break; case "customizedrange": startdate = start_dateedit.DateTimeOffset.Date; enddate = end_dateedit.DateTimeOffset.Date; break; default: clear = true; break; } if (!clear) return new DateRange (startdate, enddate.Add (new System.TimeSpan(23,59,59))); else return null; } void HandleDateEditChanged (object o, EventArgs args) { period_combobox.Changed -= HandlePeriodComboboxChanged; period_combobox.Active = System.Array.IndexOf (ranges, "customizedrange"); period_combobox.Changed += HandlePeriodComboboxChanged; } void HandlePeriodComboboxChanged (object o, EventArgs args) { start_dateedit.DateChanged -= HandleDateEditChanged; ((Gtk.Entry) start_dateedit.Children [0] as Gtk.Entry).Changed -= HandleDateEditChanged; end_dateedit.DateChanged -= HandleDateEditChanged; ((Gtk.Entry) end_dateedit.Children [0] as Gtk.Entry).Changed -= HandleDateEditChanged; ComboBox combo = o as ComboBox; if (o == null) return; start_dateedit.Sensitive = (combo.Active != System.Array.IndexOf (ranges, "alldates")); end_dateedit.Sensitive = (combo.Active != System.Array.IndexOf (ranges, "alldates")); DateRange range = QueryRange (period_combobox.Active); if (range != null) { start_dateedit.DateTimeOffset = range.Start; end_dateedit.DateTimeOffset = range.End; } start_dateedit.DateChanged += HandleDateEditChanged; ((Gtk.Entry) start_dateedit.Children [0] as Gtk.Entry).Changed += HandleDateEditChanged; end_dateedit.DateChanged += HandleDateEditChanged; ((Gtk.Entry) end_dateedit.Children [0] as Gtk.Entry).Changed += HandleDateEditChanged; } } }
// 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 System.Runtime.InteropServices; using Xunit; namespace System.Reflection.Emit.Tests { [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public class BoolAllAttribute : Attribute { private bool _s; public BoolAllAttribute(bool s) { _s = s; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class IntClassAttribute : Attribute { public int i; public IntClassAttribute(int i) { this.i = i; } } public class AssemblyTests { public static IEnumerable<object[]> DefineDynamicAssembly_TestData() { foreach (AssemblyBuilderAccess access in new AssemblyBuilderAccess[] { AssemblyBuilderAccess.Run, AssemblyBuilderAccess.RunAndCollect }) { yield return new object[] { new AssemblyName("TestName") { Version = new Version(0, 0, 0, 0) }, access }; yield return new object[] { new AssemblyName("testname") { Version = new Version(1, 2, 3, 4) }, access }; yield return new object[] { new AssemblyName("class") { Version = new Version(0, 0, 0, 0) }, access }; yield return new object[] { new AssemblyName("\uD800\uDC00") { Version = new Version(0, 0, 0, 0) }, access }; } } [Theory] [MemberData(nameof(DefineDynamicAssembly_TestData))] public void DefineDynamicAssembly_AssemblyName_AssemblyBuilderAccess(AssemblyName name, AssemblyBuilderAccess access) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, access); VerifyAssemblyBuilder(assembly, name, new CustomAttributeBuilder[0]); } public static IEnumerable<object[]> DefineDynamicAssembly_CustomAttributes_TestData() { foreach (object[] data in DefineDynamicAssembly_TestData()) { yield return new object[] { data[0], data[1], null }; yield return new object[] { data[0], data[1], new CustomAttributeBuilder[0] }; ConstructorInfo constructor = typeof(IntClassAttribute).GetConstructor(new Type[] { typeof(int) }); yield return new object[] { data[0], data[1], new CustomAttributeBuilder[] { new CustomAttributeBuilder(constructor, new object[] { 10 }) } }; } } [Theory] [MemberData(nameof(DefineDynamicAssembly_CustomAttributes_TestData))] public void DefineDynamicAssembly_AssemblyName_AssemblyBuilderAccess_CustomAttributeBuilder(AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> attributes) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, access, attributes); VerifyAssemblyBuilder(assembly, name, attributes); } [Fact] public void DefineDynamicAssembly_NullName_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("name", () => AssemblyBuilder.DefineDynamicAssembly(null, AssemblyBuilderAccess.Run)); AssertExtensions.Throws<ArgumentNullException>("name", () => AssemblyBuilder.DefineDynamicAssembly(null, AssemblyBuilderAccess.Run, new CustomAttributeBuilder[0])); } [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The coreclr doesn't support Save or ReflectionOnly AssemblyBuilders.")] [InlineData((AssemblyBuilderAccess)2)] // Save (not supported) [InlineData((AssemblyBuilderAccess)2 | AssemblyBuilderAccess.Run)] // RunAndSave (not supported) [InlineData((AssemblyBuilderAccess)6)] // ReflectionOnly (not supported) public void DefineDynamicAssembly_CoreclrNotSupportedAccess_ThrowsArgumentException(AssemblyBuilderAccess access) { DefineDynamicAssembly_InvalidAccess_ThrowsArgumentException(access); } [Theory] [InlineData((AssemblyBuilderAccess)(-1))] [InlineData((AssemblyBuilderAccess)0)] [InlineData((AssemblyBuilderAccess)10)] [InlineData((AssemblyBuilderAccess)int.MaxValue)] public void DefineDynamicAssembly_InvalidAccess_ThrowsArgumentException(AssemblyBuilderAccess access) { AssertExtensions.Throws<ArgumentException>("access", () => AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), access)); AssertExtensions.Throws<ArgumentException>("access", () => AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), access, new CustomAttributeBuilder[0])); } [Fact] public void DefineDynamicAssembly_NameIsCopy() { AssemblyName name = new AssemblyName("Name") { Version = new Version(0, 0, 0, 0) }; AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); Assert.StartsWith(name.ToString(), assembly.FullName); name.Name = "NewName"; Assert.False(assembly.FullName.StartsWith(name.ToString())); } public static IEnumerable<object[]> DefineDynamicModule_TestData() { yield return new object[] { "Module" }; yield return new object[] { "module" }; yield return new object[] { "class" }; yield return new object[] { "\uD800\uDC00" }; yield return new object[] { new string('a', 259) }; } [Theory] [MemberData(nameof(DefineDynamicModule_TestData))] public void DefineDynamicModule(string name) { AssemblyBuilder assembly = Helpers.DynamicAssembly(); ModuleBuilder module = assembly.DefineDynamicModule(name); Assert.Equal(assembly, module.Assembly); Assert.Empty(module.CustomAttributes); Assert.Equal("<In Memory Module>", module.Name); // The coreclr ignores the name passed to AssemblyBuilder.DefineDynamicModule if (PlatformDetection.IsFullFramework) { Assert.Equal(name, module.FullyQualifiedName); } else { Assert.Equal("RefEmit_InMemoryManifestModule", module.FullyQualifiedName); } Assert.Equal(module, assembly.GetDynamicModule(module.FullyQualifiedName)); } [Fact] public void DefineDynamicModule_NullName_ThrowsArgumentNullException() { AssemblyBuilder assembly = Helpers.DynamicAssembly(); AssertExtensions.Throws<ArgumentNullException>("name", () => assembly.DefineDynamicModule(null)); } [Theory] [InlineData("")] [InlineData("\0test")] public void DefineDynamicModule_InvalidName_ThrowsArgumentException(string name) { AssemblyBuilder assembly = Helpers.DynamicAssembly(); AssertExtensions.Throws<ArgumentException>("name", () => assembly.DefineDynamicModule(name)); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The coreclr only supports AssemblyBuilders with one module.")] public void DefineDynamicModule_NetFxModuleAlreadyDefined_ThrowsInvalidOperationException() { AssemblyBuilder assembly = Helpers.DynamicAssembly(); assembly.DefineDynamicModule("module1"); assembly.DefineDynamicModule("module2"); AssertExtensions.Throws<ArgumentException>(null, () => assembly.DefineDynamicModule("module1")); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The coreclr only supports AssemblyBuilders with one module.")] public void DefineDynamicModule_CoreFxModuleAlreadyDefined_ThrowsInvalidOperationException() { AssemblyBuilder assembly = Helpers.DynamicAssembly(); assembly.DefineDynamicModule("module1"); Assert.Throws<InvalidOperationException>(() => assembly.DefineDynamicModule("module1")); Assert.Throws<InvalidOperationException>(() => assembly.DefineDynamicModule("module2")); } [Fact] public void GetManifestResourceNames_ThrowsNotSupportedException() { AssemblyBuilder assembly = Helpers.DynamicAssembly(); Assert.Throws<NotSupportedException>(() => assembly.GetManifestResourceNames()); } [Fact] public void GetManifestResourceStream_ThrowsNotSupportedException() { AssemblyBuilder assembly = Helpers.DynamicAssembly(); Assert.Throws<NotSupportedException>(() => assembly.GetManifestResourceStream("")); } [Fact] public void GetManifestResourceInfo_ThrowsNotSupportedException() { AssemblyBuilder assembly = Helpers.DynamicAssembly(); Assert.Throws<NotSupportedException>(() => assembly.GetManifestResourceInfo("")); } [Fact] public void ExportedTypes_ThrowsNotSupportedException() { AssemblyBuilder assembly = Helpers.DynamicAssembly(); Assert.Throws<NotSupportedException>(() => assembly.ExportedTypes); Assert.Throws<NotSupportedException>(() => assembly.GetExportedTypes()); } [Theory] [InlineData("testmodule")] [InlineData("\0test")] public void GetDynamicModule_NoSuchModule_ReturnsNull(string name) { AssemblyBuilder assembly = Helpers.DynamicAssembly(); assembly.DefineDynamicModule("TestModule"); Assert.Null(assembly.GetDynamicModule(name)); } [Fact] public void GetDynamicModule_InvalidName_ThrowsArgumentException() { AssemblyBuilder assembly = Helpers.DynamicAssembly(); AssertExtensions.Throws<ArgumentNullException>("name", () => assembly.GetDynamicModule(null)); AssertExtensions.Throws<ArgumentException>("name", () => assembly.GetDynamicModule("")); } [Theory] [InlineData(AssemblyBuilderAccess.Run)] [InlineData(AssemblyBuilderAccess.RunAndCollect)] public void SetCustomAttribute_ConstructorBuidler_ByteArray(AssemblyBuilderAccess access) { AssemblyBuilder assembly = Helpers.DynamicAssembly(access: access); ConstructorInfo constructor = typeof(BoolAllAttribute).GetConstructor(new Type[] { typeof(bool) }); assembly.SetCustomAttribute(constructor, new byte[] { 1, 0, 1 }); IEnumerable<Attribute> attributes = assembly.GetCustomAttributes(); Assert.IsType<BoolAllAttribute>(attributes.First()); } [Fact] public void SetCustomAttribute_ConstructorBuidler_ByteArray_NullConstructorBuilder_ThrowsArgumentNullException() { AssemblyBuilder assembly = Helpers.DynamicAssembly(); AssertExtensions.Throws<ArgumentNullException>("con", () => assembly.SetCustomAttribute(null, new byte[0])); } [Fact] public void SetCustomAttribute_ConstructorBuidler_ByteArray_NullByteArray_ThrowsArgumentNullException() { AssemblyBuilder assembly = Helpers.DynamicAssembly(); ConstructorInfo constructor = typeof(IntAllAttribute).GetConstructor(new Type[] { typeof(int) }); AssertExtensions.Throws<ArgumentNullException>("binaryAttribute", () => assembly.SetCustomAttribute(constructor, null)); } [Theory] [InlineData(AssemblyBuilderAccess.Run)] [InlineData(AssemblyBuilderAccess.RunAndCollect)] public void SetCustomAttribute_CustomAttributeBuilder(AssemblyBuilderAccess access) { AssemblyBuilder assembly = Helpers.DynamicAssembly(access: access); ConstructorInfo constructor = typeof(IntClassAttribute).GetConstructor(new Type[] { typeof(int) }); CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(constructor, new object[] { 5 }); assembly.SetCustomAttribute(attributeBuilder); IEnumerable<Attribute> attributes = assembly.GetCustomAttributes(); Assert.IsType<IntClassAttribute>(attributes.First()); } [Fact] public void SetCustomAttribute_CustomAttributeBuilder_NullAttributeBuilder_ThrowsArgumentNullException() { AssemblyBuilder assembly = Helpers.DynamicAssembly(); AssertExtensions.Throws<ArgumentNullException>("customBuilder", () => assembly.SetCustomAttribute(null)); } public static IEnumerable<object[]> Equals_TestData() { AssemblyBuilder assembly = Helpers.DynamicAssembly(name: "Name1"); yield return new object[] { assembly, assembly, true }; yield return new object[] { assembly, Helpers.DynamicAssembly("Name1"), false }; yield return new object[] { assembly, Helpers.DynamicAssembly("Name2"), false }; yield return new object[] { assembly, Helpers.DynamicAssembly("Name1", access: AssemblyBuilderAccess.RunAndCollect), false }; yield return new object[] { assembly, new object(), false }; yield return new object[] { assembly, null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals(AssemblyBuilder assembly, object obj, bool expected) { Assert.Equal(expected, assembly.Equals(obj)); if (obj is AssemblyBuilder) { Assert.Equal(expected, assembly.GetHashCode().Equals(obj.GetHashCode())); } } public static void VerifyAssemblyBuilder(AssemblyBuilder assembly, AssemblyName name, IEnumerable<CustomAttributeBuilder> attributes) { Assert.StartsWith(name.ToString(), assembly.FullName); Assert.StartsWith(name.ToString(), assembly.GetName().ToString()); Assert.True(assembly.IsDynamic); Assert.Equal(attributes?.Count() ?? 0, assembly.CustomAttributes.Count()); Assert.Equal(1, assembly.Modules.Count()); Module module = assembly.Modules.First(); Assert.NotEmpty(module.Name); Assert.Equal(assembly.Modules, assembly.GetModules()); Assert.Empty(assembly.DefinedTypes); Assert.Empty(assembly.GetTypes()); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.VR.WSA.Input; public enum ControllerState { Idle = 0, Rotate = 1, Resize = 2, Positioning = 3 } public class ObjectController : MonoBehaviour { [Header("Object")] public GameObject ObjectToControl = null; [Header("Lines")] public float LineWidth = 0.001f; public Color LineColor = Color.white; [Header("Controllers")] public Vector3 ControllerSize = new Vector3(.1f, .1f, .1f); public Shader lineShader = null; public int ControllerLayer = 16; public float OutboundOfObject = .1f; [Header("Rotation")] public float RotationSensitivity = 10.0f; [Header("Sizing")] public float ResizeSensitivity = .5f; public Vector3 MinimalSize = new Vector3(.1f, .1f, .1f); public Vector3 MaxiumSize = new Vector3(1f, 1f, 1f); [Header("Positioning")] public int PositionLayer = 0; public float PositionHitdistance = .25f; public float PositionDistance = 2.5f; private const string ActionRotate = "rotate"; private const string ActionResize = "resize"; private const string ActionPosition = "position"; /// <summary> /// Top-left-back /// Top-right-back /// Top-right-front /// Top-left-front /// Bottom-left-back /// Bottom-right-back /// Bottom-right-front /// Bottom-left-front /// Middle-left-back /// Middle-right-back /// Middle-right-front /// Middle-left-front /// </summary> private GameObject[] controllers = new GameObject[12]; private string[] controllerActions = new string[12]; private LineRenderer[] lines = new LineRenderer[6]; private GameObject positioner = null; private Renderer objectRenderer = null; private GameObject focusedController = null; private GestureRecognizer navigationRecognizer = null; private Vector3 NavigationPosition = Vector3.zero; private ControllerState state = ControllerState.Idle; private Vector3 previousObjectPosition = Vector3.zero; private Quaternion previousObjectQuaterion = new Quaternion(); private Vector3 originalObjectSize = Vector3.zero; // Use this for initialization void Start () { float scaleFactor = 10f; BoxCollider collider; objectRenderer = ObjectToControl.GetComponent<Renderer>(); originalObjectSize = ObjectToControl.transform.localScale; for (int index = 0; index < controllers.Length; index++) { controllers[index] = GameObject.CreatePrimitive(PrimitiveType.Cube); controllers[index].transform.SetParent(gameObject.transform); controllers[index].transform.localScale = ControllerSize; // after localScale is set than you can adjust the collider collider = controllers[index].GetComponent<BoxCollider>(); collider.size = new Vector3(ControllerSize.x * 2f * scaleFactor, ControllerSize.y * 2f * scaleFactor, ControllerSize.z * 2f * scaleFactor); controllers[index].layer = ControllerLayer; if (index < 8) { controllerActions[index] = ActionResize; } else { controllerActions[index] = ActionRotate; } } for (int index = 0; index < lines.Length; index++) { GameObject line = new GameObject(); line.transform.SetParent(gameObject.transform); lines[index] = line.AddComponent<LineRenderer>(); } positioner = GameObject.CreatePrimitive(PrimitiveType.Sphere); positioner.transform.localScale = ControllerSize; positioner.transform.SetParent(gameObject.transform); positioner.layer = ControllerLayer; SphereCollider positionCollider = positioner.GetComponent<SphereCollider>(); Destroy(positionCollider); collider = positioner.AddComponent<BoxCollider>(); collider.size = new Vector3(ControllerSize.x * 2f * scaleFactor, ControllerSize.y * 2f * scaleFactor, ControllerSize.z * 2f * scaleFactor); InitControllers(); InitPositioner(); EnableNavigationGestures(); } // Update is called once per frame void Update () { switch (state) { case ControllerState.Idle: var headPosition = Camera.main.transform.position; var gazeDirection = Camera.main.transform.forward; RaycastHit hitInfo; if (Physics.Raycast(headPosition, gazeDirection, out hitInfo, 30.0f, 1 << ControllerLayer, QueryTriggerInteraction.Collide)) { ResetControllers(); focusedController = hitInfo.collider.gameObject; focusedController.transform.localScale = new Vector3(.15f, .15f, .15f); } else { if (focusedController != null) { focusedController.transform.localScale = ControllerSize; focusedController = null; } } break; case ControllerState.Rotate: PerformRotation(); break; case ControllerState.Resize: PerformResize(); break; case ControllerState.Positioning: PerformPosition(); break; } if (ObjectToControl != null && objectRenderer != null) { if (previousObjectPosition != ObjectToControl.transform.position) { previousObjectPosition = ObjectToControl.transform.position; // when the parent moves to another position, the controllers already move with the parent // the lines do not move so they need to be redrawn UpdateLines(); } if (previousObjectQuaterion != ObjectToControl.transform.rotation) { previousObjectQuaterion = ObjectToControl.transform.rotation; // when the parent has rotation, the controllers already move with the parent // the lines do not move so they need to be redrawn UpdateLines(); } } } private void ResetControllers() { foreach(GameObject controller in controllers) { controller.transform.localScale = ControllerSize; } positioner.transform.localScale = ControllerSize; } private void InitPositioner() { Vector3 size = objectRenderer.bounds.size; Vector3 position = objectRenderer.bounds.center; // the absolute center of the object positioner.transform.position = new Vector3(position.x, position.y + (size.y / 2) + OutboundOfObject * 2f, position.z); } private void InitControllers() { Vector3 size = objectRenderer.bounds.size; Vector3 position = objectRenderer.bounds.center; // the absolute center of the object float divX = (size.x / 2f) + OutboundOfObject; float divY = (size.y / 2f) + OutboundOfObject; float divZ = (size.z / 2f) + OutboundOfObject; controllers[0].transform.position = new Vector3(position.x - divX, position.y + divY, position.z + divZ); controllers[1].transform.position = new Vector3(position.x + divX, position.y + divY, position.z + divZ); controllers[2].transform.position = new Vector3(position.x + divX, position.y + divY, position.z - divZ); controllers[3].transform.position = new Vector3(position.x - divX, position.y + divY, position.z - divZ); controllers[4].transform.position = new Vector3(position.x - divX, position.y - divY, position.z + divZ); controllers[5].transform.position = new Vector3(position.x + divX, position.y - divY, position.z + divZ); controllers[6].transform.position = new Vector3(position.x + divX, position.y - divY, position.z - divZ); controllers[7].transform.position = new Vector3(position.x - divX, position.y - divY, position.z - divZ); controllers[8].transform.position = new Vector3(position.x - divX, position.y, position.z + divZ); controllers[9].transform.position = new Vector3(position.x + divX, position.y, position.z + divZ); controllers[10].transform.position = new Vector3(position.x + divX, position.y, position.z - divZ); controllers[11].transform.position = new Vector3(position.x - divX, position.y, position.z - divZ); } private void UpdateLines() { Vector3[] lineTop = new Vector3[5] { controllers[0].transform.position, controllers[1].transform.position, controllers[2].transform.position, controllers[3].transform.position, controllers[0].transform.position }; Vector3[] lineBottom = new Vector3[5] { controllers[4].transform.position, controllers[5].transform.position, controllers[6].transform.position, controllers[7].transform.position, controllers[4].transform.position }; Vector3[] lineLeftBack = new Vector3[2] { controllers[0].transform.position, controllers[4].transform.position }; Vector3[] lineRightBack = new Vector3[2] { controllers[1].transform.position, controllers[5].transform.position }; Vector3[] lineLeftFront = new Vector3[2] { controllers[2].transform.position, controllers[6].transform.position }; Vector3[] lineRightFront = new Vector3[2] { controllers[3].transform.position, controllers[7].transform.position }; foreach (LineRenderer line in lines) { line.startWidth = LineWidth; line.endWidth = LineWidth; line.startColor = LineColor; line.endColor = LineColor; // The shader is needed to change to the color specified if (lineShader != null) { line.material = new Material(lineShader); } } lines[0].positionCount = 5; lines[0].SetPositions(lineTop); lines[1].positionCount = 5; lines[1].SetPositions(lineBottom); lines[2].positionCount = 2; lines[2].SetPositions(lineLeftBack); lines[3].positionCount = 2; lines[3].SetPositions(lineRightBack); lines[4].positionCount = 2; lines[4].SetPositions(lineLeftFront); lines[5].positionCount = 2; lines[5].SetPositions(lineRightFront); } private string GetControllerAction(GameObject controller) { string action = ""; if (controller == positioner) { return ActionPosition; } for(int index = 0; index < controllers.Length; index++) { if (controllers[index] == controller) { action = controllerActions[index]; break; } } return action; } private void EnableNavigationGestures() { // Set up a GestureRecognizer to detect Select gestures. navigationRecognizer = new GestureRecognizer(); navigationRecognizer.NavigationStartedEvent += (source, normalizedOffset, headRay) => { if (state == ControllerState.Idle) { if (focusedController != null) { string action = GetControllerAction(focusedController); if (action == ActionRotate) { state = ControllerState.Rotate; } else if (action == ActionResize) { state = ControllerState.Resize; } ResetControllers(); } NavigationPosition = normalizedOffset; } }; navigationRecognizer.NavigationUpdatedEvent += (source, normalizedOffset, headRay) => { NavigationPosition = normalizedOffset; }; navigationRecognizer.NavigationCompletedEvent += (source, normalizedOffset, headRay) => { state = ControllerState.Idle; }; navigationRecognizer.TappedEvent += (source, tapCount, ray) => { switch(state) { case ControllerState.Idle: if (focusedController == positioner) { state = ControllerState.Positioning; } break; case ControllerState.Positioning: state = ControllerState.Idle; break; } }; navigationRecognizer.StartCapturingGestures(); } public void PerformRotation() { float rotationFactor = NavigationPosition.x * RotationSensitivity; ObjectToControl.transform.Rotate(new Vector3(0, -1 * rotationFactor, 0)); } public void PerformPosition() { var headPosition = Camera.main.transform.position; var gazeDirection = Camera.main.transform.forward; RaycastHit hitInfo; if (PositionLayer == 0) { if (Physics.Raycast(headPosition, gazeDirection, out hitInfo, 30.0f)) { ObjectToControl.transform.position = new Vector3(hitInfo.point.x, hitInfo.point.y, hitInfo.point.z - PositionHitdistance); } else { ObjectToControl.transform.position = headPosition + (gazeDirection.normalized * PositionDistance); } } else { if (Physics.Raycast(headPosition, gazeDirection, out hitInfo, 30.0f, 1 << PositionLayer, QueryTriggerInteraction.Collide)) { ObjectToControl.transform.position = new Vector3(hitInfo.point.x, hitInfo.point.y, hitInfo.point.z - PositionHitdistance); } else { ObjectToControl.transform.position = headPosition + (gazeDirection.normalized * PositionDistance); } } } public void PerformResize() { float resizeFactor = NavigationPosition.x * ResizeSensitivity; ObjectToControl.transform.localScale = originalObjectSize + new Vector3(-1 * resizeFactor, -1 * resizeFactor, -1 * resizeFactor); if (ObjectToControl.transform.localScale.x < MinimalSize.x || ObjectToControl.transform.localScale.y < MinimalSize.y || ObjectToControl.transform.localScale.z < MinimalSize.z) { ObjectToControl.transform.localScale = MinimalSize; } if (ObjectToControl.transform.localScale.x > MaxiumSize.x || ObjectToControl.transform.localScale.y > MaxiumSize.y || ObjectToControl.transform.localScale.z > MaxiumSize.z) { ObjectToControl.transform.localScale = MaxiumSize; } UpdateLines(); } }
namespace EIDSS.Reports.Document.Veterinary.LivestockInvestigation { partial class HerdReport { /// <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(HerdReport)); DevExpress.XtraReports.UI.XRSummary xrSummary1 = new DevExpress.XtraReports.UI.XRSummary(); DevExpress.XtraReports.UI.XRSummary xrSummary2 = new DevExpress.XtraReports.UI.XRSummary(); DevExpress.XtraReports.UI.XRSummary xrSummary3 = new DevExpress.XtraReports.UI.XRSummary(); this.Detail = new DevExpress.XtraReports.UI.DetailBand(); this.DetailTable = new DevExpress.XtraReports.UI.XRTable(); this.DetailTableRow = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell(); this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand(); this.HeaderTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand(); this.m_DataSet = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.HerdDataSet(); this.m_Adapter = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.HerdDataSetTableAdapters.spRepVetHerdDetailsTableAdapter(); this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel(); this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand(); this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand(); this.GroupHeader1 = new DevExpress.XtraReports.UI.GroupHeaderBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.GroupFooter1 = new DevExpress.XtraReports.UI.GroupFooterBand(); ((System.ComponentModel.ISupportInitialize)(this.DetailTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // Detail // this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.DetailTable}); resources.ApplyResources(this.Detail, "Detail"); this.Detail.Name = "Detail"; this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UseTextAlignment = false; // // DetailTable // this.DetailTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.DetailTable, "DetailTable"); this.DetailTable.Name = "DetailTable"; this.DetailTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.DetailTableRow}); this.DetailTable.StylePriority.UseBorders = false; this.DetailTable.StylePriority.UseFont = false; // // DetailTableRow // this.DetailTableRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell23, this.xrTableCell4, this.xrTableCell5, this.xrTableCell24, this.xrTableCell6, this.xrTableCell10, this.xrTableCell25}); this.DetailTableRow.Name = "DetailTableRow"; this.DetailTableRow.StylePriority.UseBorders = false; resources.ApplyResources(this.DetailTableRow, "DetailTableRow"); // // xrTableCell23 // this.xrTableCell23.Name = "xrTableCell23"; resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); // // xrTableCell4 // this.xrTableCell4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.SpeciesID")}); this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); // // xrTableCell5 // this.xrTableCell5.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.Total")}); this.xrTableCell5.Name = "xrTableCell5"; resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); // // xrTableCell24 // this.xrTableCell24.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.Dead")}); this.xrTableCell24.Name = "xrTableCell24"; resources.ApplyResources(this.xrTableCell24, "xrTableCell24"); // // xrTableCell6 // this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.Sick")}); this.xrTableCell6.Name = "xrTableCell6"; resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); // // xrTableCell10 // this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.strNote")}); this.xrTableCell10.Name = "xrTableCell10"; resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); // // xrTableCell25 // this.xrTableCell25.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.SignsDate", "{0:dd/MM/yyyy}")}); this.xrTableCell25.Name = "xrTableCell25"; resources.ApplyResources(this.xrTableCell25, "xrTableCell25"); // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.Name = "PageHeader"; this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UseTextAlignment = false; // // HeaderTable // this.HeaderTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.HeaderTable, "HeaderTable"); this.HeaderTable.Name = "HeaderTable"; this.HeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1}); this.HeaderTable.StylePriority.UseBorders = false; this.HeaderTable.StylePriority.UseFont = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell19, this.xrTableCell1, this.xrTableCell2, this.xrTableCell16, this.xrTableCell3, this.xrTableCell9, this.xrTableCell18}); this.xrTableRow1.Name = "xrTableRow1"; resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); // // xrTableCell19 // this.xrTableCell19.Name = "xrTableCell19"; resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); // // xrTableCell1 // this.xrTableCell1.Name = "xrTableCell1"; resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); // // xrTableCell2 // this.xrTableCell2.Name = "xrTableCell2"; resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); // // xrTableCell16 // this.xrTableCell16.Name = "xrTableCell16"; resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); // // xrTableCell3 // this.xrTableCell3.Name = "xrTableCell3"; resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); // // xrTableCell9 // this.xrTableCell9.Name = "xrTableCell9"; resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); // // xrTableCell18 // this.xrTableCell18.Name = "xrTableCell18"; resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.Name = "PageFooter"; this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // m_DataSet // this.m_DataSet.DataSetName = "HerdDataSet"; this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // m_Adapter // this.m_Adapter.ClearBeforeFill = true; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLabel1, this.HeaderTable}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Name = "ReportHeader"; this.ReportHeader.StylePriority.UseFont = false; this.ReportHeader.StylePriority.UseTextAlignment = false; // // xrLabel1 // this.xrLabel1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.xrLabel1, "xrLabel1"); this.xrLabel1.Name = "xrLabel1"; this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel1.StylePriority.UseBorders = false; this.xrLabel1.StylePriority.UseFont = false; this.xrLabel1.StylePriority.UseTextAlignment = false; // // topMarginBand1 // resources.ApplyResources(this.topMarginBand1, "topMarginBand1"); this.topMarginBand1.Name = "topMarginBand1"; // // bottomMarginBand1 // resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1"); this.bottomMarginBand1.Name = "bottomMarginBand1"; // // GroupHeader1 // this.GroupHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1}); this.GroupHeader1.GroupFields.AddRange(new DevExpress.XtraReports.UI.GroupField[] { new DevExpress.XtraReports.UI.GroupField("HerdCode", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)}); resources.ApplyResources(this.GroupHeader1, "GroupHeader1"); this.GroupHeader1.Name = "GroupHeader1"; this.GroupHeader1.StylePriority.UseTextAlignment = false; // // xrTable1 // this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow2}); this.xrTable1.StylePriority.UseBorders = false; this.xrTable1.StylePriority.UseFont = false; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell20, this.xrTableCell13, this.xrTableCell12, this.xrTableCell21, this.xrTableCell15, this.xrTableCell17, this.xrTableCell22}); this.xrTableRow2.Name = "xrTableRow2"; this.xrTableRow2.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); // // xrTableCell20 // this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.HerdCode")}); this.xrTableCell20.Name = "xrTableCell20"; resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); // // xrTableCell13 // this.xrTableCell13.Name = "xrTableCell13"; resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); // // xrTableCell12 // this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.Total")}); this.xrTableCell12.Name = "xrTableCell12"; xrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Group; this.xrTableCell12.Summary = xrSummary1; resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); // // xrTableCell21 // this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.Dead")}); this.xrTableCell21.Name = "xrTableCell21"; xrSummary2.Running = DevExpress.XtraReports.UI.SummaryRunning.Group; this.xrTableCell21.Summary = xrSummary2; resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); // // xrTableCell15 // this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.Sick")}); this.xrTableCell15.Name = "xrTableCell15"; xrSummary3.Running = DevExpress.XtraReports.UI.SummaryRunning.Group; this.xrTableCell15.Summary = xrSummary3; resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); // // xrTableCell17 // this.xrTableCell17.Name = "xrTableCell17"; resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); // // xrTableCell22 // this.xrTableCell22.Name = "xrTableCell22"; resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); // // GroupFooter1 // resources.ApplyResources(this.GroupFooter1, "GroupFooter1"); this.GroupFooter1.Name = "GroupFooter1"; this.GroupFooter1.StylePriority.UseTextAlignment = false; // // HerdReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.topMarginBand1, this.bottomMarginBand1, this.GroupHeader1, this.GroupFooter1}); this.DataAdapter = this.m_Adapter; this.DataMember = "spRepVetHerdDetails"; this.DataSource = this.m_DataSet; resources.ApplyResources(this, "$this"); this.Version = "14.1"; ((System.ComponentModel.ISupportInitialize)(this.DetailTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailBand Detail; private DevExpress.XtraReports.UI.PageHeaderBand PageHeader; private DevExpress.XtraReports.UI.PageFooterBand PageFooter; private HerdDataSet m_DataSet; private EIDSS.Reports.Document.Veterinary.LivestockInvestigation.HerdDataSetTableAdapters.spRepVetHerdDetailsTableAdapter m_Adapter; private DevExpress.XtraReports.UI.XRTable HeaderTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader; private DevExpress.XtraReports.UI.XRTable DetailTable; private DevExpress.XtraReports.UI.XRTableRow DetailTableRow; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRLabel xrLabel1; private DevExpress.XtraReports.UI.TopMarginBand topMarginBand1; private DevExpress.XtraReports.UI.BottomMarginBand bottomMarginBand1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeader1; private DevExpress.XtraReports.UI.GroupFooterBand GroupFooter1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.XRTableCell xrTableCell24; private DevExpress.XtraReports.UI.XRTableCell xrTableCell25; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class FormHandlingTests : DriverTestFixture { [Test] public void ShouldClickOnSubmitInputElements() { driver.Url = formsPage; driver.FindElement(By.Id("submitButton")).Click(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ClickingOnUnclickableElementsDoesNothing() { driver.Url = formsPage; driver.FindElement(By.XPath("//body")).Click(); } [Test] public void ShouldBeAbleToClickImageButtons() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Click(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldBeAbleToSubmitForms() { driver.Url = formsPage; driver.FindElement(By.Name("login")).Submit(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldSubmitAFormWhenAnyInputElementWithinThatFormIsSubmitted() { driver.Url = formsPage; driver.FindElement(By.Id("checky")).Submit(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldSubmitAFormWhenAnyElementWithinThatFormIsSubmitted() { driver.Url = formsPage; driver.FindElement(By.XPath("//form/p")).Submit(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [IgnoreBrowser(Browser.Android)] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.IPhone)] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.PhantomJS)] [IgnoreBrowser(Browser.Safari)] [ExpectedException(typeof(NoSuchElementException))] public void ShouldNotBeAbleToSubmitAFormThatDoesNotExist() { driver.Url = formsPage; driver.FindElement(By.Name("SearchableText")).Submit(); } [Test] public void ShouldBeAbleToEnterTextIntoATextAreaBySettingItsValue() { driver.Url = javascriptPage; IWebElement textarea = driver.FindElement(By.Id("keyUpArea")); string cheesey = "Brie and cheddar"; textarea.SendKeys(cheesey); Assert.AreEqual(textarea.GetAttribute("value"), cheesey); } [Test] public void SendKeysKeepsCapitalization() { driver.Url = javascriptPage; IWebElement textarea = driver.FindElement(By.Id("keyUpArea")); string cheesey = "BrIe And CheDdar"; textarea.SendKeys(cheesey); Assert.AreEqual(textarea.GetAttribute("value"), cheesey); } [Test] public void ShouldSubmitAFormUsingTheNewlineLiteral() { driver.Url = formsPage; IWebElement nestedForm = driver.FindElement(By.Id("nested_form")); IWebElement input = nestedForm.FindElement(By.Name("x")); input.SendKeys("\n"); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual("We Arrive Here", driver.Title); Assert.IsTrue(driver.Url.EndsWith("?x=name")); } [Test] public void ShouldSubmitAFormUsingTheEnterKey() { driver.Url = formsPage; IWebElement nestedForm = driver.FindElement(By.Id("nested_form")); IWebElement input = nestedForm.FindElement(By.Name("x")); input.SendKeys(Keys.Enter); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual("We Arrive Here", driver.Title); Assert.IsTrue(driver.Url.EndsWith("?x=name")); } [Test] public void ShouldEnterDataIntoFormFields() { driver.Url = xhtmlTestPage; IWebElement element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']")); String originalValue = element.GetAttribute("value"); Assert.AreEqual(originalValue, "change"); element.Clear(); element.SendKeys("some text"); element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']")); String newFormValue = element.GetAttribute("value"); Assert.AreEqual(newFormValue, "some text"); } [Test] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] [IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")] public void ShouldBeAbleToAlterTheContentsOfAFileUploadInputElement() { driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt"); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value")); Assert.AreEqual(inputFile.Name, outputFile.Name); inputFile.Delete(); } [Test] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] [IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")] public void ShouldBeAbleToSendKeysToAFileUploadInputElementInAnXhtmlDocument() { // IE before 9 doesn't handle pages served with an XHTML content type, and just prompts for to // download it if (TestUtilities.IsOldIE(driver)) { return; } driver.Url = xhtmlFormPage; IWebElement uploadElement = driver.FindElement(By.Id("file")); Assert.AreEqual(string.Empty, uploadElement.GetAttribute("value")); System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt"); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value")); Assert.AreEqual(inputFile.Name, outputFile.Name); inputFile.Delete(); } [Test] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] [IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")] public void ShouldBeAbleToUploadTheSameFileTwice() { System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt"); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); uploadElement.SendKeys(inputFile.FullName); uploadElement.Submit(); driver.Url = formsPage; uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); uploadElement.SendKeys(inputFile.FullName); uploadElement.Submit(); // If we get this far, then we're all good. } [Test] public void SendingKeyboardEventsShouldAppendTextInInputs() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); element.SendKeys("Some"); String value = element.GetAttribute("value"); Assert.AreEqual(value, "Some"); element.SendKeys(" text"); value = element.GetAttribute("value"); Assert.AreEqual(value, "Some text"); } [Test] public void SendingKeyboardEventsShouldAppendTextInInputsWithExistingValue() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("inputWithText")); element.SendKeys(". Some text"); string value = element.GetAttribute("value"); Assert.AreEqual("Example text. Some text", value); } [Test] [IgnoreBrowser(Browser.HtmlUnit, "Not implemented going to the end of the line first")] public void SendingKeyboardEventsShouldAppendTextInTextAreas() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("withText")); element.SendKeys(". Some text"); String value = element.GetAttribute("value"); Assert.AreEqual(value, "Example text. Some text"); } [Test] public void ShouldBeAbleToClearTextFromInputElements() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); element.SendKeys("Some text"); String value = element.GetAttribute("value"); Assert.IsTrue(value.Length > 0); element.Clear(); value = element.GetAttribute("value"); Assert.AreEqual(value.Length, 0); } [Test] public void EmptyTextBoxesShouldReturnAnEmptyStringNotNull() { driver.Url = formsPage; IWebElement emptyTextBox = driver.FindElement(By.Id("working")); Assert.AreEqual(emptyTextBox.GetAttribute("value"), ""); IWebElement emptyTextArea = driver.FindElement(By.Id("emptyTextArea")); Assert.AreEqual(emptyTextBox.GetAttribute("value"), ""); } [Test] public void ShouldBeAbleToClearTextFromTextAreas() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("withText")); element.SendKeys("Some text"); String value = element.GetAttribute("value"); Assert.IsTrue(value.Length > 0); element.Clear(); value = element.GetAttribute("value"); Assert.AreEqual(value.Length, 0); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.HtmlUnit, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] [IgnoreBrowser(Browser.Opera, "Untested")] [IgnoreBrowser(Browser.PhantomJS, "Untested")] [IgnoreBrowser(Browser.Safari, "Untested")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support alert handling")] public void HandleFormWithJavascriptAction() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("form_handling_js_submit.html"); driver.Url = url; IWebElement element = driver.FindElement(By.Id("theForm")); element.Submit(); IAlert alert = driver.SwitchTo().Alert(); string text = alert.Text; alert.Dismiss(); Assert.AreEqual("Tasty cheese", text); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] [IgnoreBrowser(Browser.Safari, "Untested")] public void CanClickOnASubmitButton() { CheckSubmitButton("internal_explicit_submit"); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] [IgnoreBrowser(Browser.Safari, "Untested")] public void CanClickOnAnImplicitSubmitButton() { CheckSubmitButton("internal_implicit_submit"); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] [IgnoreBrowser(Browser.Safari, "Untested")] [IgnoreBrowser(Browser.HtmlUnit, "Fails on HtmlUnit")] [IgnoreBrowser(Browser.IE, "Fails on IE")] public void CanClickOnAnExternalSubmitButton() { CheckSubmitButton("external_explicit_submit"); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] [IgnoreBrowser(Browser.Safari, "Untested")] [IgnoreBrowser(Browser.HtmlUnit, "Fails on HtmlUnit")] [IgnoreBrowser(Browser.IE, "Fails on IE")] public void CanClickOnAnExternalImplicitSubmitButton() { CheckSubmitButton("external_implicit_submit"); } private void CheckSubmitButton(string buttonId) { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/html5_submit_buttons.html"); string name = "Gromit"; driver.FindElement(By.Id("name")).SendKeys(name); driver.FindElement(By.Id(buttonId)).Click(); WaitFor(TitleToBe("Submitted Successfully!"), "Browser title is not 'Submitted Successfully!'"); Assert.That(driver.Url.Contains("name=" + name), "URL does not contain 'name=" + name + "'. Actual URL:" + driver.Url); } private Func<bool> TitleToBe(string desiredTitle) { return () => { return driver.Title == desiredTitle; }; } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace HWD.DetailsControls { public class Process : System.Windows.Forms.UserControl { private Crownwood.DotNetMagic.Controls.ButtonWithStyle button12; private Crownwood.DotNetMagic.Controls.ButtonWithStyle button13; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.ListView lstPro; private System.Windows.Forms.ColumnHeader columnHeader25; private System.Windows.Forms.ColumnHeader columnHeader22; private System.Windows.Forms.ColumnHeader columnHeader9; private System.ComponentModel.Container components = null; private ListViewItem ProcessItem; private string ProcessID; private string insys = HWD.Details.insys; public delegate void Status(string e); public event Status ChangeStatus; private System.Resources.ResourceManager m_ResourceManager; public System.Resources.ResourceManager rsxmgr { set { this.m_ResourceManager = value; } } public Process() { InitializeComponent(); } protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button12 = new Crownwood.DotNetMagic.Controls.ButtonWithStyle(); this.button13 = new Crownwood.DotNetMagic.Controls.ButtonWithStyle(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.lstPro = new System.Windows.Forms.ListView(); this.columnHeader25 = new System.Windows.Forms.ColumnHeader(); this.columnHeader22 = new System.Windows.Forms.ColumnHeader(); this.columnHeader9 = new System.Windows.Forms.ColumnHeader(); this.SuspendLayout(); // // button12 // this.button12.Location = new System.Drawing.Point(512, 4); this.button12.Name = "button12"; this.button12.Size = new System.Drawing.Size(96, 32); this.button12.TabIndex = 33; this.button12.Text = "Get Processes"; this.button12.Click += new System.EventHandler(this.button12_Click); // // button13 // this.button13.Location = new System.Drawing.Point(224, 4); this.button13.Name = "button13"; this.button13.Size = new System.Drawing.Size(96, 32); this.button13.TabIndex = 32; this.button13.Text = "Create"; this.button13.Click += new System.EventHandler(this.button13_Click); // // textBox1 // this.textBox1.BackColor = System.Drawing.Color.White; this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.textBox1.Location = new System.Drawing.Point(88, 12); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(128, 20); this.textBox1.TabIndex = 31; this.textBox1.Text = ""; // // label2 // this.label2.Location = new System.Drawing.Point(8, 12); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(80, 16); this.label2.TabIndex = 30; this.label2.Text = "New Process:"; // // lstPro // this.lstPro.BackColor = System.Drawing.Color.White; this.lstPro.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lstPro.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader25, this.columnHeader22, this.columnHeader9}); this.lstPro.Dock = System.Windows.Forms.DockStyle.Bottom; this.lstPro.FullRowSelect = true; this.lstPro.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.lstPro.Location = new System.Drawing.Point(0, 49); this.lstPro.Name = "lstPro"; this.lstPro.Size = new System.Drawing.Size(614, 240); this.lstPro.Sorting = System.Windows.Forms.SortOrder.Ascending; this.lstPro.TabIndex = 29; this.lstPro.View = System.Windows.Forms.View.Details; this.lstPro.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lstPro_MouseDown); // // columnHeader25 // this.columnHeader25.Text = "ID"; this.columnHeader25.Width = 74; // // columnHeader22 // this.columnHeader22.Text = "Process"; this.columnHeader22.Width = 189; // // columnHeader9 // this.columnHeader9.Text = "User"; this.columnHeader9.Width = 150; // // Process // this.Controls.Add(this.button12); this.Controls.Add(this.button13); this.Controls.Add(this.textBox1); this.Controls.Add(this.label2); this.Controls.Add(this.lstPro); this.Name = "Process"; this.Size = new System.Drawing.Size(614, 289); this.ResumeLayout(false); } #endregion private void changeStatus(string stringStatus) { if (ChangeStatus != null) ChangeStatus(stringStatus); } private void button13_Click(object sender, System.EventArgs e) { System.Management.ManagementOperationObserver observer = new System.Management.ManagementOperationObserver(); Handler completionHandlerObj = new Handler(); observer.ObjectReady += new System.Management.ObjectReadyEventHandler(completionHandlerObj.Done); System.Management.ConnectionOptions co = new System.Management.ConnectionOptions(); if (HWD.Details.anotherLogin && HWD.Details.username.Length > 0) { co.Username = HWD.Details.username; co.Password = HWD.Details.password; } System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\" + this.insys + "\\root\\cimv2", co); System.Management.ManagementPath path = new System.Management.ManagementPath( "Win32_Process"); System.Management.ManagementClass processClass = new System.Management.ManagementClass(ms,path,null); object[] methodArgs = {this.textBox1.Text, null, null, 0}; processClass.InvokeMethod (observer, "Create", methodArgs); int intCount = 0; while (!completionHandlerObj.IsComplete) { if (intCount > 10) { MessageBox.Show("Create process timed out.", "Terminate Process Status"); break; } System.Threading.Thread.Sleep(500); intCount++; } if (intCount != 10) { if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0") { this.Refresh(); } else { MessageBox.Show("Error creating new process.", "Create New Process"); } } this.Update(); } private void button12_Click(object sender, System.EventArgs e) { this.changeStatus("Getting process table..."); System.Management.ManagementOperationObserver observer = new System.Management.ManagementOperationObserver(); Handler completionHandlerObj = new Handler(); observer.ObjectReady += new System.Management.ObjectReadyEventHandler(completionHandlerObj.Done); this.Cursor = Cursors.WaitCursor; string [] sitems = new string[3]; try { foreach(System.Management.ManagementObject mo in HWD.Details.Consulta("SELECT * FROM Win32_Process")) { sitems[0] = mo["ProcessID"].ToString(); sitems[1] = mo["Name"].ToString(); mo.InvokeMethod(observer,"GetOwner", null); while (!completionHandlerObj.IsComplete) { System.Threading.Thread.Sleep(500); } if (completionHandlerObj.ReturnObject["returnValue"].ToString() == "0") { sitems[2] = completionHandlerObj.ReturnObject.Properties["User"].Value.ToString(); } else { sitems[2] = "-"; } ListViewItem lvItem = new ListViewItem(sitems,0); this.lstPro.Items.Add(lvItem); } } catch { this.Cursor = Cursors.Default; } this.button12.Enabled = false; this.changeStatus("Online"); this.Cursor = Cursors.Default; } private void lstPro_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { System.Windows.Forms.ListView listViewObject = (System.Windows.Forms.ListView) sender; ContextMenu mnuContextMenu = new ContextMenu(); MenuItem menuItem; if (e.Button == System.Windows.Forms.MouseButtons.Right) { ProcessItem = listViewObject.GetItemAt(e.X,e.Y); this.lstPro.ContextMenu = mnuContextMenu; try { ProcessID = ProcessItem.SubItems[0].Text; menuItem = new MenuItem(); menuItem.Text = "Terminate Process"; mnuContextMenu.MenuItems.Add(menuItem); menuItem.Click += new System.EventHandler(this.menuItemTerminate_Click); } catch { } } } private void menuItemTerminate_Click(object sender, System.EventArgs e) { ListViewItem lvItem; System.Management.ManagementOperationObserver observer = new System.Management.ManagementOperationObserver(); Handler completionHandlerObj = new Handler(); observer.ObjectReady += new System.Management.ObjectReadyEventHandler(completionHandlerObj.Done); foreach (System.Management.ManagementObject mo in HWD.Details.Consulta("Select * from Win32_Process Where ProcessID = '" + ProcessID + "'")) { mo.InvokeMethod(observer, "Terminate", null); } int intCount = 0; while (!completionHandlerObj.IsComplete) { if (intCount == 10) { MessageBox.Show("Terminate process timed out.", "Terminate Process Status"); break; } System.Threading.Thread.Sleep(500); intCount++; } if (intCount != 10) { if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0") { lvItem = ProcessItem; lvItem.Remove(); } else { MessageBox.Show("Error terminating process.", "Terminate Process"); } } ProcessID = ""; ProcessItem = null; this.Update(); } } }
using System; using System.Diagnostics; using System.Drawing; using System.IO; using Alchemi.Core.Owner; using System.Text; using System.Threading; using System.Net; namespace Alchemi.Examples.Renderer { /// <summary> /// Summary description for RenderThread. /// </summary> [Serializable] public class RenderThread : GThread { private int _startRowPixel; private int _startColPixel; private int _endRowPixel; private int _endColPixel; private string _inputFile; private string _megaPOV_Options; private int _imageWidth; private int _imageHeight; private int _segWidth; private int _segHeight; private int _col; //column of the big image private int _row; //row of the big image private Bitmap crop; [NonSerialized]private StringBuilder output; [NonSerialized]private StringBuilder error; [NonSerialized] private Process megapov = null; private string _stdout; private string _stderr; private string _basePath; public int Row { get { return _row; } set { _row = value; } } public int Col { get { return _col; } set { _col = value; } } public string BasePath { get { return Environment.ExpandEnvironmentVariables(_basePath); } set { _basePath = value; } } public string Stdout { get { return _stdout; } } public string Stderr { get { return _stderr; } } public Bitmap RenderedImageSegment { get { return crop; } } public RenderThread(string InputFile, int ImageWidth, int ImageHeight, int SegmentWidth, int SegmentHeight, int StartRow, int EndRow, int StartCol, int EndCol, string MegaPOV_Options) { this._inputFile = InputFile; this._imageWidth = ImageWidth; this._imageHeight = ImageHeight; this._segWidth = SegmentWidth; this._segHeight = SegmentHeight; this._startRowPixel = StartRow; this._endRowPixel = EndRow; this._startColPixel = StartCol; this._endColPixel = EndCol; this._megaPOV_Options = MegaPOV_Options; } public override void Start() { //do all the rendering by calling the povray stuff, and then crop it and send it back. //first call megapov, and render the scence. //direct it to save to some filename. string outfilename = null; try { outfilename = string.Format("{0}_{1}_tempPOV.png", Col, Row); string cmd = "cmd"; string args = "/C " + Path.Combine(BasePath, @"bin\megapov.exe") + string.Format(" +I{0} +O{1} +H{2} +W{3} +SR{4} +ER{5} +SC{6} +EC{7} +FN16 {8}", Environment.ExpandEnvironmentVariables(_inputFile), outfilename, _imageHeight, _imageWidth, _startRowPixel, _endRowPixel, _startColPixel, _endColPixel, _megaPOV_Options ); output = new StringBuilder(); error = new StringBuilder(); //no need to lock output here, since so far there won't be more than one thread //using it. output.AppendLine("**** BasePath is " + BasePath); output.AppendLine("**** Working dir is " + WorkingDirectory); output.AppendLine("**** Cmd for process is :" + cmd); output.AppendLine("**** Args for process is :" + args); megapov = new Process(); megapov.StartInfo.FileName = cmd; megapov.StartInfo.Arguments = args; megapov.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; megapov.StartInfo.UseShellExecute = false; //false, since we dont want WorkingDir to be used to find the exe megapov.StartInfo.WorkingDirectory = WorkingDirectory; megapov.StartInfo.CreateNoWindow = true; megapov.EnableRaisingEvents = true; megapov.StartInfo.RedirectStandardError = true; megapov.StartInfo.RedirectStandardOutput = true; megapov.OutputDataReceived += new DataReceivedEventHandler(megapov_OutputDataReceived); megapov.ErrorDataReceived += new DataReceivedEventHandler(megapov_ErrorDataReceived); megapov.Exited += new EventHandler(megapov_Exited); megapov.Start(); megapov.BeginErrorReadLine(); megapov.BeginOutputReadLine(); while (!megapov.HasExited) { //since we are getting notified async. megapov.WaitForExit(1000); } if (megapov.HasExited) { LogOutput( string.Format("******** MegaPov Out of wait loop... time: {0}, exit code: {1}", Environment.TickCount, megapov.ExitCode) ); } } catch (Exception ex) { LogError(ex.ToString()); } finally { CloseProcess(); try { CropImage(Path.Combine(WorkingDirectory, outfilename)); } catch (Exception ex) { LogError(ex.ToString()); } _stdout = output.ToString(); _stderr = error.ToString(); } } private void CloseProcess() { try { if (megapov != null) { //time to kill! if (!megapov.HasExited) { megapov.Kill(); } megapov.Close(); megapov.Dispose(); megapov = null; } } catch { } } private void CropImage(string imageFile) { Bitmap im = null; try { //then crop the image produced by megapov, and get it back. int x = (Col - 1) * _segWidth; im = new Bitmap(imageFile); crop = new Bitmap(_segWidth, _segHeight); using (Graphics g = Graphics.FromImage(crop)) { Rectangle sourceRectangle = new Rectangle(x, 0, _segWidth, _segHeight); Rectangle destRectangle = new Rectangle(0, 0, _segWidth, _segHeight); g.DrawImage(im, destRectangle, sourceRectangle, GraphicsUnit.Pixel); } LogOutput(string.Format("Cropped ImageFile : {0}", imageFile)); } catch (Exception ex) { LogError("Error cropping file : " + imageFile + "\n" + ex.ToString()); } finally { try { if (im != null) { im.Dispose(); } } catch { } } } private string GetIPAddressString() { StringBuilder ip = new StringBuilder(); try { ip.AppendLine(string.Format("Host : {0}", Dns.GetHostName())); IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress ipaddr in addresses) { ip.AppendLine(string.Format(", IP : {0}", ipaddr.ToString())); } } catch { } return ip.ToString(); } //Thread-safe error-logging. private void LogError(string e) { if (error != null) { lock (error) { error.AppendLine(e); } } } //Thread-safe output-logging. private void LogOutput(string o) { if (output != null) { lock (output) { output.AppendLine(o); } } } #region MegaPov Process Events void megapov_Exited(object sender, EventArgs e) { try { LogOutput(string.Format("********** Megapov process has exited at {0}, on {1}", Environment.TickCount, GetIPAddressString())); } catch { } } void megapov_ErrorDataReceived(object sender, DataReceivedEventArgs e) { LogError(e.Data); } void megapov_OutputDataReceived(object sender, DataReceivedEventArgs e) { LogOutput(e.Data); } #endregion } }
using System; using QuantConnect.Indicators; using QuantConnect.Data; using QuantConnect.Data.Market; using System.Linq; namespace GeneticTree.Signal { /// <summary> /// This class keeps track of an oscillator respect to its thresholds and updates an <see cref="OscillatorSignal" /> /// for each given state. /// </summary> /// <seealso cref="QuantConnect.Algorithm.CSharp.ITechnicalIndicatorSignal" /> public class OscillatorSignal : SignalBase { private decimal _previousIndicatorValue; private ThresholdState _previousSignal; private int[] _thresholds; protected Direction _direction; static int[] defaultThresholds = new int[2] { 20, 80 }; /// <summary> /// Possibles states of an oscillator respect to its thresholds. /// </summary> public enum ThresholdState { CrossLowerFromAbove = -3, BelowLower = -2, CrossLowerFromBelow = -1, InBetween = 0, CrossUpperFromBelow = 3, AboveUpper = 2, CrossUpperFromAbove = 1 } /// <summary> /// Initializes a new instance of the <see cref="OscillatorSignal" /> class. /// </summary> /// <param name="indicator">The indicator.</param> /// <param name="thresholds">The thresholds.</param> /// <param name="direction"> /// The trade rule direction. Only used if the instance will be part of a /// <see cref="Rule" /> class /// </param> /// <remarks>The oscillator must be registered BEFORE being used by this constructor.</remarks> public OscillatorSignal(dynamic indicator, int[] thresholds, Direction direction, int survivalPeriod = 1) { Initialize(indicator, thresholds, direction, survivalPeriod); } /// <summary> /// Initializes a new instance of the <see cref="OscillatorSignal" /> class. /// </summary> /// <param name="indicator">The indicator.</param> /// <param name="thresholds">The thresholds.</param> /// <remarks>The oscillator must be registered BEFORE being used by this constructor.</remarks> public OscillatorSignal(dynamic indicator, int[] thresholds, int survivalPeriod = 1) { Initialize(indicator, thresholds, Direction.LongOnly, survivalPeriod); } public OscillatorSignal(dynamic indicator, Direction direction, int survivalPeriod = 1) { Initialize(indicator, defaultThresholds, direction, survivalPeriod); } /// <summary> /// Initializes a new instance of the <see cref="OscillatorSignal" /> class. /// </summary> /// <param name="indicator">The indicator.</param> /// <remarks>The oscillator must be registered BEFORE being used by this constructor.</remarks> public OscillatorSignal(dynamic indicator, int survivalPeriod = 1) { Initialize(indicator, defaultThresholds, Direction.LongOnly, survivalPeriod); } /// <summary> /// The underlying indicator, must be an oscillator. /// </summary> public dynamic Indicator { get; private set; } /// <summary> /// Gets the actual state of the oscillator. /// </summary> public ThresholdState Signal { get; private set; } /// <summary> /// Gets a value indicating whether this instance is ready. /// </summary> /// <value> /// <c>true</c> if this instance is ready; otherwise, <c>false</c>. /// </value> public override bool IsReady { get { return Indicator.IsReady; } } public override decimal Value { get { return Indicator.Current.Value; } } /// <summary> /// Gets the signal. Only used if the instance will be part of a <see cref="Rule" /> class. /// </summary> /// <returns> /// <c>true</c> if the actual <see cref="Signal" /> correspond with the instance <see cref="Direction" />. /// <c>false</c> /// otherwise. /// </returns> public override bool IsTrue() { var signal = false; if (IsReady) { switch (_direction) { case Direction.LongOnly: foreach (ThresholdState state in SurvivalWindow) { signal = state == ThresholdState.CrossLowerFromBelow; if (signal) break; } break; case Direction.ShortOnly: foreach (ThresholdState state in SurvivalWindow) { signal = state == ThresholdState.CrossUpperFromAbove; if (signal) break; } break; } } return signal; } /// <summary> /// Updates the <see cref="Signal" /> status. /// </summary> protected virtual void Indicator_Updated(object sender, IndicatorDataPoint updated) { var actualPositionSignal = GetThresholdState(updated); ProcessThresholdStateChange(actualPositionSignal, updated); } protected void ProcessThresholdStateChange(ThresholdState actualPositionSignal, IndicatorDataPoint updated) { if (!Indicator.IsReady) { _previousIndicatorValue = updated.Value; _previousSignal = actualPositionSignal; Signal = _previousSignal; return; } var actualSignal = GetActualSignal(_previousSignal, actualPositionSignal); Signal = actualSignal; _previousIndicatorValue = updated.Value; SurvivalWindow.Add((int)Signal); _previousSignal = actualSignal; } /// <summary> /// Gets the actual position respect to the thresholds. /// </summary> /// <param name="indicatorCurrentValue">The indicator current value.</param> /// <returns></returns> protected virtual ThresholdState GetThresholdState(decimal indicatorCurrentValue) { var positionSignal = ThresholdState.InBetween; if (indicatorCurrentValue > _thresholds[1]) { positionSignal = ThresholdState.AboveUpper; } else if (indicatorCurrentValue < _thresholds[0]) { positionSignal = ThresholdState.BelowLower; } return positionSignal; } /// <summary> /// Gets the actual signal from the actual position respect to the thresholds and the last signal. /// </summary> /// <param name="previousSignal">The previous signal.</param> /// <param name="actualPositionSignal">The actual position signal.</param> /// <returns></returns> private ThresholdState GetActualSignal(ThresholdState previousSignal, ThresholdState actualPositionSignal) { ThresholdState actualSignal; var previous = (int)previousSignal; var current = (int)actualPositionSignal; if (current == 0) { if (Math.Abs(previous) > 1) { actualSignal = (ThresholdState)Math.Sign(previous); } else { actualSignal = ThresholdState.InBetween; } } else { if (previous * current <= 0 || Math.Abs(previous + current) == 3) { actualSignal = (ThresholdState)(Math.Sign(current) * 3); } else { actualSignal = (ThresholdState)(Math.Sign(current) * 2); } } return actualSignal; } /// <summary> /// Sets up class. /// </summary> /// <param name="indicator">The indicator.</param> /// <param name="thresholds">The thresholds.</param> /// <param name="direction">The trade rule direction.</param> private void Initialize(dynamic indicator, int[] thresholds, Direction direction, int survivalPeriod = 1) { _thresholds = thresholds; Indicator = indicator; indicator.Updated += new IndicatorUpdatedHandler(Indicator_Updated); _direction = direction; SurvivalWindow = new RollingWindow<int>(survivalPeriod); } /// <summary> /// Exposes a means to update underlying indicator /// </summary> /// <param name="data"></param> public override void Update(BaseData data) { if (Indicator.GetType().IsSubclassOf(typeof(IndicatorBase<IBaseDataBar>))) { if (data.GetType().GetInterfaces().Contains(typeof(IBaseDataBar))) { Indicator.Update((IBaseDataBar)data); } else if (data.GetType() == typeof(Tick)) { var tick = (Tick)data; Indicator.Update(new TradeBar { High = tick.AskPrice, Low = tick.BidPrice, Value = tick.Value, Time = tick.Time, Symbol = tick.Symbol }); } } else if (Indicator.GetType().IsSubclassOf(typeof(IndicatorBase<IndicatorDataPoint>))) { Indicator.Update(new IndicatorDataPoint(data.Time, data.Value)); } else { Indicator.Update(data); } base.Update(data); } } }
using System; namespace Godot { public struct Color : IEquatable<Color> { public float r; public float g; public float b; public float a; public int r8 { get { return (int)(r * 255.0f); } } public int g8 { get { return (int)(g * 255.0f); } } public int b8 { get { return (int)(b * 255.0f); } } public int a8 { get { return (int)(a * 255.0f); } } public float h { get { float max = Math.Max(r, Math.Max(g, b)); float min = Math.Min(r, Math.Min(g, b)); float delta = max - min; if (delta == 0) return 0; float h; if (r == max) h = (g - b) / delta; // Between yellow & magenta else if (g == max) h = 2 + (b - r) / delta; // Between cyan & yellow else h = 4 + (r - g) / delta; // Between magenta & cyan h /= 6.0f; if (h < 0) h += 1.0f; return h; } set { this = FromHsv(value, s, v); } } public float s { get { float max = Math.Max(r, Math.Max(g, b)); float min = Math.Min(r, Math.Min(g, b)); float delta = max - min; return max != 0 ? delta / max : 0; } set { this = FromHsv(h, value, v); } } public float v { get { return Math.Max(r, Math.Max(g, b)); } set { this = FromHsv(h, s, value); } } public static Color ColorN(string name, float alpha = 1f) { name = name.Replace(" ", String.Empty); name = name.Replace("-", String.Empty); name = name.Replace("_", String.Empty); name = name.Replace("'", String.Empty); name = name.Replace(".", String.Empty); name = name.ToLower(); if (!Colors.namedColors.ContainsKey(name)) { throw new ArgumentOutOfRangeException($"Invalid Color Name: {name}"); } Color color = Colors.namedColors[name]; color.a = alpha; return color; } public float this[int index] { get { switch (index) { case 0: return r; case 1: return g; case 2: return b; case 3: return a; default: throw new IndexOutOfRangeException(); } } set { switch (index) { case 0: r = value; return; case 1: g = value; return; case 2: b = value; return; case 3: a = value; return; default: throw new IndexOutOfRangeException(); } } } public static void ToHsv(Color color, out float hue, out float saturation, out float value) { int max = Mathf.Max(color.r8, Mathf.Max(color.g8, color.b8)); int min = Mathf.Min(color.r8, Mathf.Min(color.g8, color.b8)); float delta = max - min; if (delta == 0) { hue = 0; } else { if (color.r == max) hue = (color.g - color.b) / delta; // Between yellow & magenta else if (color.g == max) hue = 2 + (color.b - color.r) / delta; // Between cyan & yellow else hue = 4 + (color.r - color.g) / delta; // Between magenta & cyan hue /= 6.0f; if (hue < 0) hue += 1.0f; } saturation = max == 0 ? 0 : 1f - 1f * min / max; value = max / 255f; } public static Color FromHsv(float hue, float saturation, float value, float alpha = 1.0f) { if (saturation == 0) { // acp_hromatic (grey) return new Color(value, value, value, alpha); } int i; float f, p, q, t; hue *= 6.0f; hue %= 6f; i = (int)hue; f = hue - i; p = value * (1 - saturation); q = value * (1 - saturation * f); t = value * (1 - saturation * (1 - f)); switch (i) { case 0: // Red is the dominant color return new Color(value, t, p, alpha); case 1: // Green is the dominant color return new Color(q, value, p, alpha); case 2: return new Color(p, value, t, alpha); case 3: // Blue is the dominant color return new Color(p, q, value, alpha); case 4: return new Color(t, p, value, alpha); default: // (5) Red is the dominant color return new Color(value, p, q, alpha); } } public Color Blend(Color over) { Color res; float sa = 1.0f - over.a; res.a = a * sa + over.a; if (res.a == 0) { return new Color(0, 0, 0, 0); } res.r = (r * a * sa + over.r * over.a) / res.a; res.g = (g * a * sa + over.g * over.a) / res.a; res.b = (b * a * sa + over.b * over.a) / res.a; return res; } public Color Contrasted() { return new Color( (r + 0.5f) % 1.0f, (g + 0.5f) % 1.0f, (b + 0.5f) % 1.0f ); } public Color Darkened(float amount) { Color res = this; res.r = res.r * (1.0f - amount); res.g = res.g * (1.0f - amount); res.b = res.b * (1.0f - amount); return res; } public Color Inverted() { return new Color( 1.0f - r, 1.0f - g, 1.0f - b ); } public Color Lightened(float amount) { Color res = this; res.r = res.r + (1.0f - res.r) * amount; res.g = res.g + (1.0f - res.g) * amount; res.b = res.b + (1.0f - res.b) * amount; return res; } public Color LinearInterpolate(Color c, float t) { var res = this; res.r += t * (c.r - r); res.g += t * (c.g - g); res.b += t * (c.b - b); res.a += t * (c.a - a); return res; } public int ToAbgr32() { int c = (byte)Math.Round(a * 255); c <<= 8; c |= (byte)Math.Round(b * 255); c <<= 8; c |= (byte)Math.Round(g * 255); c <<= 8; c |= (byte)Math.Round(r * 255); return c; } public long ToAbgr64() { long c = (ushort)Math.Round(a * 65535); c <<= 16; c |= (ushort)Math.Round(b * 65535); c <<= 16; c |= (ushort)Math.Round(g * 65535); c <<= 16; c |= (ushort)Math.Round(r * 65535); return c; } public int ToArgb32() { int c = (byte)Math.Round(a * 255); c <<= 8; c |= (byte)Math.Round(r * 255); c <<= 8; c |= (byte)Math.Round(g * 255); c <<= 8; c |= (byte)Math.Round(b * 255); return c; } public long ToArgb64() { long c = (ushort)Math.Round(a * 65535); c <<= 16; c |= (ushort)Math.Round(r * 65535); c <<= 16; c |= (ushort)Math.Round(g * 65535); c <<= 16; c |= (ushort)Math.Round(b * 65535); return c; } public int ToRgba32() { int c = (byte)Math.Round(r * 255); c <<= 8; c |= (byte)Math.Round(g * 255); c <<= 8; c |= (byte)Math.Round(b * 255); c <<= 8; c |= (byte)Math.Round(a * 255); return c; } public long ToRgba64() { long c = (ushort)Math.Round(r * 65535); c <<= 16; c |= (ushort)Math.Round(g * 65535); c <<= 16; c |= (ushort)Math.Round(b * 65535); c <<= 16; c |= (ushort)Math.Round(a * 65535); return c; } public string ToHtml(bool include_alpha = true) { var txt = string.Empty; txt += ToHex32(r); txt += ToHex32(g); txt += ToHex32(b); if (include_alpha) txt = ToHex32(a) + txt; return txt; } // Constructors public Color(float r, float g, float b, float a = 1.0f) { this.r = r; this.g = g; this.b = b; this.a = a; } public Color(int rgba) { a = (rgba & 0xFF) / 255.0f; rgba >>= 8; b = (rgba & 0xFF) / 255.0f; rgba >>= 8; g = (rgba & 0xFF) / 255.0f; rgba >>= 8; r = (rgba & 0xFF) / 255.0f; } public Color(long rgba) { a = (rgba & 0xFFFF) / 65535.0f; rgba >>= 16; b = (rgba & 0xFFFF) / 65535.0f; rgba >>= 16; g = (rgba & 0xFFFF) / 65535.0f; rgba >>= 16; r = (rgba & 0xFFFF) / 65535.0f; } private static int ParseCol8(string str, int ofs) { int ig = 0; for (int i = 0; i < 2; i++) { int c = str[i + ofs]; int v; if (c >= '0' && c <= '9') { v = c - '0'; } else if (c >= 'a' && c <= 'f') { v = c - 'a'; v += 10; } else if (c >= 'A' && c <= 'F') { v = c - 'A'; v += 10; } else { return -1; } if (i == 0) ig += v * 16; else ig += v; } return ig; } private String ToHex32(float val) { int v = Mathf.RoundToInt(Mathf.Clamp(val * 255, 0, 255)); var ret = string.Empty; for (int i = 0; i < 2; i++) { char[] c = { (char)0, (char)0 }; int lv = v & 0xF; if (lv < 10) c[0] = (char)('0' + lv); else c[0] = (char)('a' + lv - 10); v >>= 4; ret = c + ret; } return ret; } internal static bool HtmlIsValid(string color) { if (color.Length == 0) return false; if (color[0] == '#') color = color.Substring(1, color.Length - 1); bool alpha; if (color.Length == 8) alpha = true; else if (color.Length == 6) alpha = false; else return false; if (alpha) { if (ParseCol8(color, 0) < 0) return false; } int from = alpha ? 2 : 0; if (ParseCol8(color, from + 0) < 0) return false; if (ParseCol8(color, from + 2) < 0) return false; if (ParseCol8(color, from + 4) < 0) return false; return true; } public static Color Color8(byte r8, byte g8, byte b8, byte a8) { return new Color(r8 / 255f, g8 / 255f, b8 / 255f, a8 / 255f); } public Color(string rgba) { if (rgba.Length == 0) { r = 0f; g = 0f; b = 0f; a = 1.0f; return; } if (rgba[0] == '#') rgba = rgba.Substring(1); bool alpha; if (rgba.Length == 8) { alpha = true; } else if (rgba.Length == 6) { alpha = false; } else { throw new ArgumentOutOfRangeException("Invalid color code. Length is " + rgba.Length + " but a length of 6 or 8 is expected: " + rgba); } if (alpha) { a = ParseCol8(rgba, 0) / 255f; if (a < 0) throw new ArgumentOutOfRangeException("Invalid color code. Alpha part is not valid hexadecimal: " + rgba); } else { a = 1.0f; } int from = alpha ? 2 : 0; r = ParseCol8(rgba, from + 0) / 255f; if (r < 0) throw new ArgumentOutOfRangeException("Invalid color code. Red part is not valid hexadecimal: " + rgba); g = ParseCol8(rgba, from + 2) / 255f; if (g < 0) throw new ArgumentOutOfRangeException("Invalid color code. Green part is not valid hexadecimal: " + rgba); b = ParseCol8(rgba, from + 4) / 255f; if (b < 0) throw new ArgumentOutOfRangeException("Invalid color code. Blue part is not valid hexadecimal: " + rgba); } public static bool operator ==(Color left, Color right) { return left.Equals(right); } public static bool operator !=(Color left, Color right) { return !left.Equals(right); } public static bool operator <(Color left, Color right) { if (left.r == right.r) { if (left.g == right.g) { if (left.b == right.b) return left.a < right.a; return left.b < right.b; } return left.g < right.g; } return left.r < right.r; } public static bool operator >(Color left, Color right) { if (left.r == right.r) { if (left.g == right.g) { if (left.b == right.b) return left.a > right.a; return left.b > right.b; } return left.g > right.g; } return left.r > right.r; } public override bool Equals(object obj) { if (obj is Color) { return Equals((Color)obj); } return false; } public bool Equals(Color other) { return r == other.r && g == other.g && b == other.b && a == other.a; } public override int GetHashCode() { return r.GetHashCode() ^ g.GetHashCode() ^ b.GetHashCode() ^ a.GetHashCode(); } public override string ToString() { return String.Format("{0},{1},{2},{3}", r.ToString(), g.ToString(), b.ToString(), a.ToString()); } public string ToString(string format) { return String.Format("{0},{1},{2},{3}", r.ToString(format), g.ToString(format), b.ToString(format), a.ToString(format)); } } }
using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent (typeof(Camera))] [AddComponentMenu ("Image Effects/Camera/Camera Motion Blur") ] public class CameraMotionBlur : PostEffectsBase { // make sure to match this to MAX_RADIUS in shader ('k' in paper) static float MAX_RADIUS = 10.0f; public enum MotionBlurFilter { CameraMotion = 0, // global screen blur based on cam motion LocalBlur = 1, // cheap blur, no dilation or scattering Reconstruction = 2, // advanced filter (simulates scattering) as in plausible motion blur paper ReconstructionDX11 = 3, // advanced filter (simulates scattering) as in plausible motion blur paper ReconstructionDisc = 4, // advanced filter using scaled poisson disc sampling } // settings public MotionBlurFilter filterType = MotionBlurFilter.Reconstruction; public bool preview = false; // show how blur would look like in action ... public Vector3 previewScale = Vector3.one; // ... given this movement vector // params public float movementScale = 0.0f; public float rotationScale = 1.0f; public float maxVelocity = 8.0f; // maximum velocity in pixels public float minVelocity = 0.1f; // minimum velocity in pixels public float velocityScale = 0.375f; // global velocity scale public float softZDistance = 0.005f; // for z overlap check softness (reconstruction filter only) public int velocityDownsample = 1; // low resolution velocity buffer? (optimization) public LayerMask excludeLayers = 0; private GameObject tmpCam = null; // resources public Shader shader; public Shader dx11MotionBlurShader; public Shader replacementClear; private Material motionBlurMaterial = null; private Material dx11MotionBlurMaterial = null; public Texture2D noiseTexture = null; public float jitter = 0.05f; // (internal) debug public bool showVelocity = false; public float showVelocityScale = 1.0f; // camera transforms private Matrix4x4 currentViewProjMat; private Matrix4x4 prevViewProjMat; private int prevFrameCount; private bool wasActive; // shortcuts to calculate global blur direction when using 'CameraMotion' private Vector3 prevFrameForward = Vector3.forward; private Vector3 prevFrameUp = Vector3.up; private Vector3 prevFramePos = Vector3.zero; private Camera _camera; private void CalculateViewProjection () { Matrix4x4 viewMat = _camera.worldToCameraMatrix; Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true); currentViewProjMat = projMat * viewMat; } new void Start () { CheckResources (); if (_camera == null) _camera = GetComponent<Camera>(); wasActive = gameObject.activeInHierarchy; CalculateViewProjection (); Remember (); wasActive = false; // hack to fake position/rotation update and prevent bad blurs } void OnEnable () { if (_camera == null) _camera = GetComponent<Camera>(); _camera.depthTextureMode |= DepthTextureMode.Depth; } void OnDisable () { if (null != motionBlurMaterial) { DestroyImmediate (motionBlurMaterial); motionBlurMaterial = null; } if (null != dx11MotionBlurMaterial) { DestroyImmediate (dx11MotionBlurMaterial); dx11MotionBlurMaterial = null; } if (null != tmpCam) { DestroyImmediate (tmpCam); tmpCam = null; } } public override bool CheckResources () { CheckSupport (true, true); // depth & hdr needed motionBlurMaterial = CheckShaderAndCreateMaterial (shader, motionBlurMaterial); if (supportDX11 && filterType == MotionBlurFilter.ReconstructionDX11) { dx11MotionBlurMaterial = CheckShaderAndCreateMaterial (dx11MotionBlurShader, dx11MotionBlurMaterial); } if (!isSupported) ReportAutoDisable (); return isSupported; } void OnRenderImage (RenderTexture source, RenderTexture destination) { if (false == CheckResources ()) { Graphics.Blit (source, destination); return; } if (filterType == MotionBlurFilter.CameraMotion) StartFrame (); // use if possible new RG format ... fallback to half otherwise var rtFormat= SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf; // get temp textures RenderTexture velBuffer = RenderTexture.GetTemporary (divRoundUp (source.width, velocityDownsample), divRoundUp (source.height, velocityDownsample), 0, rtFormat); int tileWidth = 1; int tileHeight = 1; maxVelocity = Mathf.Max (2.0f, maxVelocity); float _maxVelocity = maxVelocity; // calculate 'k' // note: 's' is hardcoded in shaders except for DX11 path // auto DX11 fallback! bool fallbackFromDX11 = filterType == MotionBlurFilter.ReconstructionDX11 && dx11MotionBlurMaterial == null; if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11 || filterType == MotionBlurFilter.ReconstructionDisc) { maxVelocity = Mathf.Min (maxVelocity, MAX_RADIUS); tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity); tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity); _maxVelocity = velBuffer.width/tileWidth; } else { tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity); tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity); _maxVelocity = velBuffer.width/tileWidth; } RenderTexture tileMax = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat); RenderTexture neighbourMax = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat); velBuffer.filterMode = FilterMode.Point; tileMax.filterMode = FilterMode.Point; neighbourMax.filterMode = FilterMode.Point; if (noiseTexture) noiseTexture.filterMode = FilterMode.Point; source.wrapMode = TextureWrapMode.Clamp; velBuffer.wrapMode = TextureWrapMode.Clamp; neighbourMax.wrapMode = TextureWrapMode.Clamp; tileMax.wrapMode = TextureWrapMode.Clamp; // calc correct viewprj matrix CalculateViewProjection (); // just started up? if (gameObject.activeInHierarchy && !wasActive) { Remember (); } wasActive = gameObject.activeInHierarchy; // matrices Matrix4x4 invViewPrj = Matrix4x4.Inverse (currentViewProjMat); motionBlurMaterial.SetMatrix ("_InvViewProj", invViewPrj); motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat); motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj); motionBlurMaterial.SetFloat ("_MaxVelocity", _maxVelocity); motionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity); motionBlurMaterial.SetFloat ("_MinVelocity", minVelocity); motionBlurMaterial.SetFloat ("_VelocityScale", velocityScale); motionBlurMaterial.SetFloat ("_Jitter", jitter); // texture samplers motionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture); motionBlurMaterial.SetTexture ("_VelTex", velBuffer); motionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax); motionBlurMaterial.SetTexture ("_TileTexDebug", tileMax); if (preview) { // generate an artifical 'previous' matrix to simulate blur look Matrix4x4 viewMat = _camera.worldToCameraMatrix; Matrix4x4 offset = Matrix4x4.identity; offset.SetTRS(previewScale * 0.3333f, Quaternion.identity, Vector3.one); // using only translation Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true); prevViewProjMat = projMat * offset * viewMat; motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat); motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj); } if (filterType == MotionBlurFilter.CameraMotion) { // build blur vector to be used in shader to create a global blur direction Vector4 blurVector = Vector4.zero; float lookUpDown = Vector3.Dot (transform.up, Vector3.up); Vector3 distanceVector = prevFramePos-transform.position; float distMag = distanceVector.magnitude; float farHeur = 1.0f; // pitch (vertical) farHeur = (Vector3.Angle (transform.up, prevFrameUp) / _camera.fieldOfView) * (source.width * 0.75f); blurVector.x = rotationScale * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.up, prevFrameUp))); // yaw #1 (horizontal, faded by pitch) farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f); blurVector.y = rotationScale * lookUpDown * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward))); // yaw #2 (when looking down, faded by 1-pitch) farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f); blurVector.z = rotationScale * (1.0f- lookUpDown) * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward))); if (distMag > Mathf.Epsilon && movementScale > Mathf.Epsilon) { // forward (probably most important) blurVector.w = movementScale * (Vector3.Dot (transform.forward, distanceVector) ) * (source.width * 0.5f); // jump (maybe scale down further) blurVector.x += movementScale * (Vector3.Dot (transform.up, distanceVector) ) * (source.width * 0.5f); // strafe (maybe scale down further) blurVector.y += movementScale * (Vector3.Dot (transform.right, distanceVector) ) * (source.width * 0.5f); } if (preview) // crude approximation motionBlurMaterial.SetVector ("_BlurDirectionPacked", new Vector4 (previewScale.y, previewScale.x, 0.0f, previewScale.z) * 0.5f * _camera.fieldOfView); else motionBlurMaterial.SetVector ("_BlurDirectionPacked", blurVector); } else { // generate velocity buffer Graphics.Blit (source, velBuffer, motionBlurMaterial, 0); // patch up velocity buffer: // exclude certain layers (e.g. skinned objects as we cant really support that atm) Camera cam = null; if (excludeLayers.value != 0)// || dynamicLayers.value) cam = GetTmpCam (); if (cam && excludeLayers.value != 0 && replacementClear && replacementClear.isSupported) { cam.targetTexture = velBuffer; cam.cullingMask = excludeLayers; cam.RenderWithShader (replacementClear, ""); } } if (!preview && Time.frameCount != prevFrameCount) { // remember current transformation data for next frame prevFrameCount = Time.frameCount; Remember (); } source.filterMode = FilterMode.Bilinear; // debug vel buffer: if (showVelocity) { // generate tile max and neighbour max //Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); //Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); motionBlurMaterial.SetFloat ("_DisplayVelocityScale", showVelocityScale); Graphics.Blit (velBuffer, destination, motionBlurMaterial, 1); } else { if (filterType == MotionBlurFilter.ReconstructionDX11 && !fallbackFromDX11) { // need to reset some parameters for dx11 shader dx11MotionBlurMaterial.SetFloat ("_MinVelocity", minVelocity); dx11MotionBlurMaterial.SetFloat ("_VelocityScale", velocityScale); dx11MotionBlurMaterial.SetFloat ("_Jitter", jitter); // texture samplers dx11MotionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture); dx11MotionBlurMaterial.SetTexture ("_VelTex", velBuffer); dx11MotionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax); dx11MotionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); dx11MotionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity); // generate tile max and neighbour max Graphics.Blit (velBuffer, tileMax, dx11MotionBlurMaterial, 0); Graphics.Blit (tileMax, neighbourMax, dx11MotionBlurMaterial, 1); // final blur Graphics.Blit (source, destination, dx11MotionBlurMaterial, 2); } else if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11) { // 'reconstructing' properly integrated color motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); // generate tile max and neighbour max Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); // final blur Graphics.Blit (source, destination, motionBlurMaterial, 4); } else if (filterType == MotionBlurFilter.CameraMotion) { // orange box style motion blur Graphics.Blit (source, destination, motionBlurMaterial, 6); } else if (filterType == MotionBlurFilter.ReconstructionDisc) { // dof style motion blur defocuing and ellipse around the princical blur direction // 'reconstructing' properly integrated color motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); // generate tile max and neighbour max Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); Graphics.Blit (source, destination, motionBlurMaterial, 7); } else { // simple & fast blur (low quality): just blurring along velocity Graphics.Blit (source, destination, motionBlurMaterial, 5); } } // cleanup RenderTexture.ReleaseTemporary (velBuffer); RenderTexture.ReleaseTemporary (tileMax); RenderTexture.ReleaseTemporary (neighbourMax); } void Remember () { prevViewProjMat = currentViewProjMat; prevFrameForward = transform.forward; prevFrameUp = transform.up; prevFramePos = transform.position; } Camera GetTmpCam () { if (tmpCam == null) { string name = "_" + _camera.name + "_MotionBlurTmpCam"; GameObject go = GameObject.Find (name); if (null == go) // couldn't find, recreate tmpCam = new GameObject (name, typeof (Camera)); else tmpCam = go; } tmpCam.hideFlags = HideFlags.DontSave; tmpCam.transform.position = _camera.transform.position; tmpCam.transform.rotation = _camera.transform.rotation; tmpCam.transform.localScale = _camera.transform.localScale; tmpCam.GetComponent<Camera>().CopyFrom(_camera); tmpCam.GetComponent<Camera>().enabled = false; tmpCam.GetComponent<Camera>().depthTextureMode = DepthTextureMode.None; tmpCam.GetComponent<Camera>().clearFlags = CameraClearFlags.Nothing; return tmpCam.GetComponent<Camera>(); } void StartFrame () { // take only x% of positional changes into account (camera motion) // TODO: possibly do the same for rotational part prevFramePos = Vector3.Slerp(prevFramePos, transform.position, 0.75f); } static int divRoundUp (int x, int d) { return (x + d - 1) / d; } } }
using Signum.Engine.Basics; using Signum.Engine.Operations.Internal; using Signum.Entities.Basics; namespace Signum.Engine.Operations; public delegate F Overrider<F>(F baseFunc); public class Graph<T> where T : class, IEntity { public class Construct : _Construct<T>, IConstructOperation { protected readonly OperationSymbol operationSymbol; OperationSymbol IOperation.OperationSymbol { get { return operationSymbol; } } Type IOperation.OverridenType { get { return typeof(T); } } OperationType IOperation.OperationType { get { return OperationType.Constructor; } } bool IOperation.Returns { get { return true; } } Type? IOperation.ReturnType { get { return typeof(T); } } IEnumerable<Enum>? IOperation.UntypedFromStates { get { return null; } } IEnumerable<Enum>? IOperation.UntypedToStates { get { return Enumerable.Empty<Enum>(); } } Type? IOperation.StateType { get { return null; } } public bool LogAlsoIfNotSaved { get; set; } //public Func<object[]?, T> Construct { get; set; } (inherited) public bool Lite { get { return false; } } public Construct(ConstructSymbol<T>.Simple symbol) { if (symbol == null) throw AutoInitAttribute.ArgumentNullException(typeof(ConstructSymbol<T>.Simple), nameof(symbol)); this.operationSymbol = symbol.Symbol; } protected Construct(OperationSymbol operationSymbol) { this.operationSymbol = operationSymbol ?? throw new ArgumentNullException(nameof(operationSymbol)); } public static Construct Untyped<B>(ConstructSymbol<B>.Simple symbol) where B: class, IEntity { return new Construct(symbol.Symbol); } public void OverrideConstruct(Overrider<Func<object?[]?, T?>> overrider) { this.Construct = overrider(this.Construct); } IEntity IConstructOperation.Construct(params object?[]? args) { using (HeavyProfiler.Log("Construct", () => operationSymbol.Key)) { OperationLogic.AssertOperationAllowed(operationSymbol, typeof(T), inUserInterface: false); OperationLogEntity? log = new OperationLogEntity { Operation = operationSymbol, Start = Clock.Now, User = UserHolder.Current?.ToLite()!, }; try { using (var tr = new Transaction()) { T? result = null; using (OperationLogic.AllowSave<T>()) OperationLogic.OnSuroundOperation(this, log, null, args).EndUsing(_ => { result = Construct(args); if (result != null) AssertEntity(result); if ((result != null && !result.IsNew) || LogAlsoIfNotSaved) { log.SetTarget(result); log.End = Clock.Now; } else log = null; }); if (log != null) log.SaveLog(); return tr.Commit(result!); } } catch (Exception ex) { OperationLogic.SetExceptionData(ex, operationSymbol, null, args); if (LogAlsoIfNotSaved) { if (Transaction.InTestTransaction) throw; var exLog = ex.LogException(); using (var tr2 = Transaction.ForceNew()) { log!.Exception = exLog.ToLite(); log.SaveLog(); tr2.Commit(); } } throw; } } } protected virtual void AssertEntity(T entity) { } public virtual void AssertIsValid() { if (Construct == null) throw new InvalidOperationException("Operation {0} does not have Constructor initialized".FormatWith(operationSymbol)); } public override string ToString() { return "{0} Construct {1}".FormatWith(operationSymbol, typeof(T)); } } public class ConstructFrom<F> : IConstructorFromOperation where F : class, IEntity { protected readonly OperationSymbol operationSymbol; OperationSymbol IOperation.OperationSymbol { get { return operationSymbol; } } Type IOperation.OverridenType { get { return typeof(F); } } OperationType IOperation.OperationType { get { return OperationType.ConstructorFrom; } } IEnumerable<Enum>? IOperation.UntypedFromStates { get { return null; } } IEnumerable<Enum>? IOperation.UntypedToStates { get { return Enumerable.Empty<Enum>(); } } Type? IOperation.StateType { get { return null; } } public bool CanBeModified { get; set; } public bool LogAlsoIfNotSaved { get; set; } bool IOperation.Returns { get { return true; } } Type? IOperation.ReturnType { get { return typeof(T); } } protected readonly Type baseType; Type IEntityOperation.BaseType { get { return baseType; } } bool IEntityOperation.HasCanExecute { get { return CanConstruct != null; } } public bool CanBeNew { get; set; } public Func<F, string?>? CanConstruct { get; set; } public ConstructFrom<F> OverrideCanConstruct(Overrider<Func<F, string?>> overrider) { this.CanConstruct = overrider(this.CanConstruct ?? (f => null)); return this; } public Func<F, object?[]?, T?> Construct { get; set; } = null!; public void OverrideConstruct(Overrider<Func<F, object?[]?, T?>> overrider) { this.Construct = overrider(this.Construct); } public ConstructFrom(ConstructSymbol<T>.From<F> symbol) { if (symbol == null) throw AutoInitAttribute.ArgumentNullException(typeof(ConstructSymbol<T>.From<F>), nameof(symbol)); this.operationSymbol = symbol.Symbol; this.baseType = symbol.BaseType; } protected ConstructFrom(OperationSymbol operationSymbol, Type baseType) { this.operationSymbol = operationSymbol ?? throw new ArgumentNullException(nameof(operationSymbol)); this.baseType = baseType ?? throw new ArgumentNullException(nameof(baseType)); } public static ConstructFrom<F> Untyped<B>(ConstructSymbol<B>.From<F> symbol) where B : class, IEntity { return new ConstructFrom<F>(symbol.Symbol, symbol.BaseType); } string? IEntityOperation.CanExecute(IEntity entity) { return OnCanConstruct(entity); } string? OnCanConstruct(IEntity entity) { if (entity.IsNew && !CanBeNew) return EngineMessage.TheEntity0IsNew.NiceToString().FormatWith(entity); if (CanConstruct != null) return CanConstruct((F)entity); return null; } IEntity IConstructorFromOperation.Construct(IEntity origin, params object?[]? args) { using (HeavyProfiler.Log("ConstructFrom", () => operationSymbol.Key)) { OperationLogic.AssertOperationAllowed(operationSymbol, origin.GetType(), inUserInterface: false); string? error = OnCanConstruct(origin); if (error != null) throw new ApplicationException(error); OperationLogEntity? log = new OperationLogEntity { Operation = operationSymbol, Start = Clock.Now, User = UserHolder.Current?.ToLite()!, Origin = origin.ToLite(origin.IsNew), }; try { using (var tr = new Transaction()) { T? result = null; using (OperationLogic.AllowSave(origin.GetType())) using (OperationLogic.AllowSave<T>()) OperationLogic.OnSuroundOperation(this, log, origin, args).EndUsing(_ => { result = Construct((F)origin, args); if (result != null) AssertEntity(result); if ((result != null && !result.IsNew) || LogAlsoIfNotSaved) { log.End = Clock.Now; log.SetTarget(result); } else { log = null; } }); if (log != null) log.SaveLog(); return tr.Commit(result!); } } catch (Exception ex) { OperationLogic.SetExceptionData(ex, operationSymbol, (Entity)origin, args); if (LogAlsoIfNotSaved) { if (Transaction.InTestTransaction) throw; var exLog = ex.LogException(); using (var tr2 = Transaction.ForceNew()) { log!.Exception = exLog.ToLite(); log.SaveLog(); tr2.Commit(); } } throw; } } } protected virtual void AssertEntity(T entity) { } public virtual void AssertIsValid() { if (Construct == null) throw new InvalidOperationException("Operation {0} does not hace Construct initialized".FormatWith(operationSymbol)); } public override string ToString() { return "{0} ConstructFrom {1} -> {2}".FormatWith(operationSymbol, typeof(F), typeof(T)); } } public class ConstructFromMany<F> : IConstructorFromManyOperation where F : class, IEntity { protected readonly OperationSymbol operationSymbol; OperationSymbol IOperation.OperationSymbol { get { return operationSymbol; } } Type IOperation.OverridenType { get { return typeof(F); } } OperationType IOperation.OperationType { get { return OperationType.ConstructorFromMany; } } bool IOperation.Returns { get { return true; } } Type? IOperation.ReturnType { get { return typeof(T); } } protected readonly Type baseType; Type IConstructorFromManyOperation.BaseType { get { return baseType; } } IEnumerable<Enum>? IOperation.UntypedFromStates { get { return null; } } IEnumerable<Enum>? IOperation.UntypedToStates { get { return Enumerable.Empty<Enum>(); } } Type? IOperation.StateType { get { return null; } } public bool LogAlsoIfNotSaved { get; set; } public Func<List<Lite<F>>, object?[]?, T?> Construct { get; set; } = null!; public void OverrideConstruct(Overrider<Func<List<Lite<F>>, object?[]?, T?>> overrider) { this.Construct = overrider(this.Construct); } public ConstructFromMany(ConstructSymbol<T>.FromMany<F> symbol) { if (symbol == null) throw AutoInitAttribute.ArgumentNullException(typeof(ConstructSymbol<T>.FromMany<F>), nameof(symbol)); this.operationSymbol = symbol.Symbol; this.baseType = symbol.BaseType; } protected ConstructFromMany(OperationSymbol operationSymbol, Type baseType) { this.operationSymbol = operationSymbol ?? throw new ArgumentNullException(nameof(operationSymbol)); this.baseType = baseType ?? throw new ArgumentNullException(nameof(baseType)); } public static ConstructFromMany<F> Untyped<B>(ConstructSymbol<B>.FromMany<F> symbol) where B : class, IEntity { return new ConstructFromMany<F>(symbol.Symbol, symbol.BaseType); } IEntity IConstructorFromManyOperation.Construct(IEnumerable<Lite<IEntity>> lites, params object?[]? args) { using (HeavyProfiler.Log("ConstructFromMany", () => operationSymbol.Key)) { foreach (var type in lites.Select(a => a.EntityType).Distinct()) { OperationLogic.AssertOperationAllowed(operationSymbol, type, inUserInterface: false); } OperationLogEntity? log = new OperationLogEntity { Operation = operationSymbol, Start = Clock.Now, User = UserHolder.Current?.ToLite()! }; try { using (var tr = new Transaction()) { T? result = null; using (OperationLogic.AllowSave<F>()) using (OperationLogic.AllowSave<T>()) OperationLogic.OnSuroundOperation(this, log, null, args).EndUsing(_ => { result = OnConstruct(lites.Cast<Lite<F>>().ToList(), args); if (result != null) AssertEntity(result); if ((result != null && !result.IsNew) || LogAlsoIfNotSaved) { log.End = Clock.Now; log.SetTarget(result); } else { log = null; } }); if (log != null) log.SaveLog(); return tr.Commit(result!); } } catch (Exception ex) { OperationLogic.SetExceptionData(ex, operationSymbol, null, args); if (LogAlsoIfNotSaved) { if (Transaction.InTestTransaction) throw; var exLog = ex.LogException(); using (var tr2 = Transaction.ForceNew()) { log!.Exception = exLog.ToLite(); log.SaveLog(); tr2.Commit(); } } throw; } } } protected virtual T? OnConstruct(List<Lite<F>> lites, object?[]? args) { return Construct(lites, args); } protected virtual void AssertEntity(T entity) { } public virtual void AssertIsValid() { if (Construct == null) throw new InvalidOperationException("Operation {0} Constructor initialized".FormatWith(operationSymbol)); } public override string ToString() { return "{0} ConstructFromMany {1} -> {2}".FormatWith(operationSymbol, typeof(F), typeof(T)); } } public class Execute : _Execute<T>, IExecuteOperation { protected readonly ExecuteSymbol<T> Symbol; OperationSymbol IOperation.OperationSymbol { get { return Symbol.Symbol; } } Type IOperation.OverridenType { get { return typeof(T); } } OperationType IOperation.OperationType { get { return OperationType.Execute; } } public bool CanBeModified { get; set; } bool IOperation.Returns { get { return true; } } Type? IOperation.ReturnType { get { return null; } } Type? IOperation.StateType { get { return null; } } public bool AvoidImplicitSave { get; set; } Type IEntityOperation.BaseType { get { return Symbol.BaseType; } } bool IEntityOperation.HasCanExecute { get { return CanExecute != null; } } IEnumerable<Enum>? IOperation.UntypedFromStates { get { return Enumerable.Empty<Enum>(); } } IEnumerable<Enum>? IOperation.UntypedToStates { get { return Enumerable.Empty<Enum>(); } } public bool CanBeNew { get; set; } //public Action<T, object[]?> Execute { get; set; } (inherited) public Func<T, string?>? CanExecute { get; set; } public Execute OverrideCanExecute(Overrider<Func<T, string?>> overrider) { this.CanExecute = overrider(this.CanExecute ?? (t => null)); return this; } public void OverrideExecute(Overrider<Action<T, object?[]?>> overrider) { this.Execute = overrider(this.Execute); } public Execute(ExecuteSymbol<T> symbol) { this.Symbol = symbol ?? throw AutoInitAttribute.ArgumentNullException(typeof(ExecuteSymbol<T>), nameof(symbol)); } string? IEntityOperation.CanExecute(IEntity entity) { return OnCanExecute((T)entity); } protected virtual string? OnCanExecute(T entity) { if (entity.IsNew && !CanBeNew) return EngineMessage.TheEntity0IsNew.NiceToString().FormatWith(entity); if (CanExecute != null) return CanExecute(entity); return null; } void IExecuteOperation.Execute(IEntity entity, params object?[]? args) { using (HeavyProfiler.Log("Execute", () => Symbol.Symbol.Key)) { OperationLogic.AssertOperationAllowed(Symbol.Symbol, entity.GetType(), inUserInterface: false); string? error = OnCanExecute((T)entity); if (error != null) throw new ApplicationException(error); OperationLogEntity log = new OperationLogEntity { Operation = Symbol.Symbol, Start = Clock.Now, User = UserHolder.Current?.ToLite()! }; try { using (var tr = new Transaction()) { using (OperationLogic.AllowSave(entity.GetType())) OperationLogic.OnSuroundOperation(this, log, entity, args).EndUsing(_ => { Execute((T)entity, args); AssertEntity((T)entity); if (!AvoidImplicitSave) entity.Save(); //Nothing happens if already saved log.SetTarget(entity); log.End = Clock.Now; }); log.SaveLog(); tr.Commit(); } } catch (Exception ex) { OperationLogic.SetExceptionData(ex, Symbol.Symbol, (Entity)entity, args); if (Transaction.InTestTransaction) throw; var exLog = ex.LogException(); using (var tr2 = Transaction.ForceNew()) { OperationLogEntity newLog = new OperationLogEntity //Transaction chould have been rollbacked just before commiting { Operation = log.Operation, Start = log.Start, User = log.User, Target = entity.IsNew ? null : entity.ToLite(), Exception = exLog.ToLite(), }; newLog.SaveLog(); tr2.Commit(); } throw; } } } protected virtual void AssertEntity(T entity) { } public virtual void AssertIsValid() { if (Execute == null) throw new InvalidOperationException("Operation {0} does not have Execute initialized".FormatWith(Symbol)); } public override string ToString() { return "{0} Execute on {1}".FormatWith(Symbol, typeof(T)); } } public class Delete : _Delete<T>, IDeleteOperation { protected readonly DeleteSymbol<T> Symbol; OperationSymbol IOperation.OperationSymbol { get { return Symbol.Symbol; } } Type IOperation.OverridenType { get { return typeof(T); } } OperationType IOperation.OperationType { get { return OperationType.Delete; } } public bool CanBeModified { get; set; } bool IOperation.Returns { get { return false; } } Type? IOperation.ReturnType { get { return null; } } IEnumerable<Enum>? IOperation.UntypedFromStates { get { return Enumerable.Empty<Enum>(); } } IEnumerable<Enum>? IOperation.UntypedToStates { get { return null; } } Type? IOperation.StateType { get { return null; } } public bool CanBeNew { get { return false; } } Type IEntityOperation.BaseType { get { return Symbol.BaseType; } } bool IEntityOperation.HasCanExecute { get { return CanDelete != null; } } //public Action<T, object[]?> Delete { get; set; } (inherited) public Func<T, string?>? CanDelete { get; set; } public Delete OverrideCanDelete(Overrider<Func<T, string?>> overrider) { this.CanDelete = overrider(this.CanDelete ?? (t => null)); return this; } public void OverrideDelete(Overrider<Action<T, object?[]?>> overrider) { this.Delete = overrider(this.Delete); } public Delete(DeleteSymbol<T> symbol) { this.Symbol = symbol ?? throw AutoInitAttribute.ArgumentNullException(typeof(DeleteSymbol<T>), nameof(symbol)); } string? IEntityOperation.CanExecute(IEntity entity) { return OnCanDelete((T)entity); } protected virtual string? OnCanDelete(T entity) { if (entity.IsNew) return EngineMessage.TheEntity0IsNew.NiceToString().FormatWith(entity); if (CanDelete != null) return CanDelete(entity); return null; } void IDeleteOperation.Delete(IEntity entity, params object?[]? args) { using (HeavyProfiler.Log("Delete", () => Symbol.Symbol.Key)) { OperationLogic.AssertOperationAllowed(Symbol.Symbol, entity.GetType(), inUserInterface: false); string? error = OnCanDelete((T)entity); if (error != null) throw new ApplicationException(error); OperationLogEntity log = new OperationLogEntity { Operation = Symbol.Symbol, Start = Clock.Now, User = UserHolder.Current?.ToLite()!, }; using (OperationLogic.AllowSave(entity.GetType())) OperationLogic.OnSuroundOperation(this, log, entity, args).EndUsing(_ => { try { using (var tr = new Transaction()) { OnDelete((T)entity, args); log.SetTarget(entity); log.End = Clock.Now; log.SaveLog(); tr.Commit(); } } catch (Exception ex) { OperationLogic.SetExceptionData(ex, Symbol.Symbol, (Entity)entity, args); if (Transaction.InTestTransaction) throw; var exLog = ex.LogException(); using (var tr2 = Transaction.ForceNew()) { log.Target = entity.ToLite(); log.Exception = exLog.ToLite(); log.SaveLog(); tr2.Commit(); } throw; } }); } } protected virtual void OnDelete(T entity, object?[]? args) { Delete(entity, args); } public virtual void AssertIsValid() { if (Delete == null) throw new InvalidOperationException("Operation {0} does not have Delete initialized".FormatWith(Symbol.Symbol)); } public override string ToString() { return "{0} Delete {1}".FormatWith(Symbol.Symbol, typeof(T)); } } }
/** * This source file is a part of the Dictionariosaur application. * For full copyright and license information, please view the LICENSE file * which should be distributed with this source code. * * @license MIT License * @copyright Copyright (c) 2013, Steven Velozo */ using System; using MutiUtility; namespace MutiNetworking { #region Telnet Server Event Arguments and Delegates /// <summary> /// This is the Incoming Command event argument for the Telnet Server /// </summary> public class TelnetServerCommandEventArgs : EventArgs { private string _Command; private SocketClientBuffer _Socket; /// <summary> /// This takes the incoming data byte stream, converts it to a string and /// allows the clients to do whatever they need with it. /// </summary> /// <param name="IncomingData">The incoming byte buffer.</param> /// <param name="IncomingDataLength">The length of said byte buffer.</param> public TelnetServerCommandEventArgs(string pCommand, SocketClientBuffer pSocket) { //Set the IP this._Command = pCommand; //Set the socket. this._Socket = pSocket; } // Exposed Properties. public string Command { get { return this._Command; } } public SocketClientBuffer Socket { get { return this._Socket; } } } public delegate void TelnetServerCommandEventHandler(object pSender, TelnetServerCommandEventArgs pEventArgs); #endregion /// <summary> /// The Telnet Server Class /// </summary> public class TelnetServer { private SocketServer _SocketServer; //Standard server communication strings private string _TelnetPrompt; private string _TelnetGreeting; private string _NewLine = "\r\n"; //Some server settings private bool _RemoteEcho; #region Data Access public long BytesSent { get { return this._SocketServer.TotalBytesSent; } } public long BytesReceived { get { return this._SocketServer.TotalBytesReceived; } } public bool Running { get { return this._SocketServer.IsRunning; } } #endregion #region Server Control public TelnetServer(int pTcpPort) { this._SocketServer = new SocketServer (pTcpPort); //Add the event handlers for the server this._SocketServer.WriteLog += new WriteLogEventHandler(ChainedWriteLog); this._SocketServer._ClientConnected += new SocketServerClientEventHandler (ServerClientConnected); this._SocketServer._DataRecieved += new SocketServerDataEventHandler(ServerDataRecieved); this._SocketServer._LineRecieved += new SocketServerDataEventHandler(ServerLineRecieved); this._SocketServer._NewLineRecieved += new SocketServerDataEventHandler(NewLineRecieved); //Set the default settings this.Prompt = "Telnet"; this.Greeting = "Welcome to this unconfigured telnet server!"; this._RemoteEcho = true; } ~TelnetServer() { this._SocketServer = null; } public string Prompt { set { this._TelnetPrompt = string.Concat("[", value, "]:"); } } public string Greeting { set {this._TelnetGreeting = value; } } public void Start() { if (!this._SocketServer.IsRunning) { this.WriteToLog(string.Concat("Starting Telnet Server On Port # ", this._SocketServer.Port), 1); this._SocketServer.Start(); } } public void Stop() { if (this._SocketServer.IsRunning) { this.WriteToLog(string.Concat("Halting Telnet Server"), 1); this._SocketServer.Stop(); } } #endregion #region Server Communication and Event Functions public event TelnetServerCommandEventHandler CommandRecieved; //Event firing functions private void CommandIsRecieved (string pCommand, SocketClientBuffer pSocket) { TelnetServerCommandEventArgs tmpEventArgs = new TelnetServerCommandEventArgs (pCommand, pSocket); OnCommandRecieved (tmpEventArgs); } protected virtual void OnCommandRecieved(TelnetServerCommandEventArgs tmpEventArgs) { if (CommandRecieved != null) //Invoke the event delegate CommandRecieved (this, tmpEventArgs); } private void NewLineRecieved (object pSender, SocketServerDataEventArgs pEventArgs) { try { //Send the prompt. this.SendPrompt (pEventArgs.Socket); } catch { } } private void ServerLineRecieved (object pSender, SocketServerDataEventArgs pEventArgs) { //Some data is recieved (a line of it, in fact) .. Send it to the master control to parse it. CommandIsRecieved (pEventArgs.IncomingDataString, pEventArgs.Socket); } private void ServerDataRecieved (object pSender, SocketServerDataEventArgs pEventArgs) { //Some data is recieved -- echo it back. if (this._RemoteEcho) { //Don't echo it if it is a backspace and there is no buffer if (!((pEventArgs.Socket._LineBuffer.Length < 1) && (pEventArgs.IncomingDataBytes[0] == 127))) _SocketServer.SendData (pEventArgs.IncomingDataBytes, pEventArgs.Socket); } } private void ServerClientConnected (object pSender, SocketServerClientEventArgs pEventArgs) { //A client has connected. Send the greeting and a prompt. _SocketServer.SendData (string.Concat(this._TelnetGreeting, this._NewLine), pEventArgs.Socket); this.SendPrompt (pEventArgs.Socket); } public void SendPrompt (SocketClientBuffer pSocket) { _SocketServer.SendData (string.Concat(this._NewLine, this._TelnetPrompt), pSocket); } public void SendAllPrompt () { _SocketServer.SendAllDataPlusBuffer (string.Concat(this._NewLine, this._TelnetPrompt)); } public void SendLineFeed (SocketClientBuffer pSocket) { _SocketServer.SendData (string.Concat(this._NewLine), pSocket); } public void SendData (string pData, SocketClientBuffer pSocket) { //Send some data back to the server _SocketServer.SendData (pData, pSocket); } public void SendAllData (string pData) { //Send some data back to the server _SocketServer.SendAllData (pData); } #endregion #region Log File Interface public event WriteLogEventHandler WriteLog; /// <summary> /// Write to the log file/display. /// </summary> /// <param name="pLogText">The text to be written.</param> /// <param name="pLogLevel">The numeric level of the log text. In general, 0 is screen, 1 is both, 2 is file only.</param> private void WriteToLog(string pLogText, int pLogLevel) { WriteLogEventArgs tmpEventArgs = new WriteLogEventArgs(pLogText, pLogLevel); OnWriteLog (tmpEventArgs); } protected virtual void OnWriteLog(WriteLogEventArgs pEventArgs) { if (WriteLog != null) //Invoke the event delegate WriteLog (this, pEventArgs); } private void ChainedWriteLog(object pSender, WriteLogEventArgs pEventArgs) { //A shim function to chain log events from objects here to the main application's events. WriteLogEventArgs tmpEventArgs = new WriteLogEventArgs(string.Concat ("Telnet ", pEventArgs.LogText), pEventArgs.LogLevel); //Append some useful server information to the logged events OnWriteLog(tmpEventArgs); } #endregion } }
// // TextEntryBackend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // 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 AppKit; using CoreGraphics; using Foundation; using ObjCRuntime; using Xwt.Backends; namespace Xwt.Mac { public class TextEntryBackend: ViewBackend<NSView,ITextEntryEventSink>, ITextEntryBackend { int cacheSelectionStart, cacheSelectionLength; bool checkMouseSelection; public TextEntryBackend () { } internal TextEntryBackend (MacComboBox field) { ViewObject = field; } public override void Initialize () { base.Initialize (); if (ViewObject is MacComboBox) { ((MacComboBox)ViewObject).SetEntryEventSink (EventSink); } else if (ViewObject == null) { var view = new CustomTextField (EventSink, ApplicationContext); ViewObject = new CustomAlignedContainer (EventSink, ApplicationContext, (NSView)view) { DrawsBackground = false }; Container.ExpandVertically = true; MultiLine = false; } Widget.StringValue = string.Empty; canGetFocus = Widget.AcceptsFirstResponder (); Frontend.MouseEntered += delegate { checkMouseSelection = true; }; Frontend.MouseExited += delegate { checkMouseSelection = false; HandleSelectionChanged (); }; Frontend.MouseMoved += delegate { if (checkMouseSelection) HandleSelectionChanged (); }; } protected override void OnSizeToFit () { Container.SizeToFit (); } CustomAlignedContainer Container { get { return base.Widget as CustomAlignedContainer; } } public new NSTextField Widget { get { return (ViewObject is MacComboBox) ? (NSTextField)ViewObject : (NSTextField) Container.Child; } } protected override Size GetNaturalSize () { var s = base.GetNaturalSize (); return new Size (EventSink.GetDefaultNaturalSize ().Width, s.Height); } #region ITextEntryBackend implementation public string Text { get { return Widget.StringValue; } set { Widget.StringValue = value ?? string.Empty; } } public Alignment TextAlignment { get { return Widget.Alignment.ToAlignment (); } set { Widget.Alignment = value.ToNSTextAlignment (); } } public bool ReadOnly { get { return !Widget.Editable; } set { Widget.Editable = !value; if (value) Widget.AbortEditing (); } } public bool ShowFrame { get { return Widget.Bordered; } set { Widget.Bordered = value; } } public string PlaceholderText { get { return ((NSTextFieldCell) Widget.Cell).PlaceholderString; } set { ((NSTextFieldCell) Widget.Cell).PlaceholderString = value; } } public bool MultiLine { get { if (Widget is MacComboBox) return false; return !Widget.Cell.UsesSingleLineMode; } set { if (Widget is MacComboBox) return; if (value) { Widget.Cell.UsesSingleLineMode = false; Widget.Cell.Scrollable = false; Widget.Cell.Wraps = true; } else { Widget.Cell.UsesSingleLineMode = true; Widget.Cell.Scrollable = true; Widget.Cell.Wraps = false; } } } public int CursorPosition { get { if (Widget.CurrentEditor == null) return 0; return (int)Widget.CurrentEditor.SelectedRange.Location; } set { Widget.CurrentEditor.SelectedRange = new NSRange (value, SelectionLength); HandleSelectionChanged (); } } public int SelectionStart { get { if (Widget.CurrentEditor == null) return 0; return (int)Widget.CurrentEditor.SelectedRange.Location; } set { Widget.CurrentEditor.SelectedRange = new NSRange (value, SelectionLength); HandleSelectionChanged (); } } public int SelectionLength { get { if (Widget.CurrentEditor == null) return 0; return (int)Widget.CurrentEditor.SelectedRange.Length; } set { Widget.CurrentEditor.SelectedRange = new NSRange (SelectionStart, value); HandleSelectionChanged (); } } public string SelectedText { get { if (Widget.CurrentEditor == null) return String.Empty; int start = SelectionStart; int end = start + SelectionLength; if (start == end) return String.Empty; try { return Text.Substring (start, end - start); } catch { return String.Empty; } } set { int cacheSelStart = SelectionStart; int pos = cacheSelStart; if (SelectionLength > 0) { Text = Text.Remove (pos, SelectionLength).Insert (pos, value); } SelectionStart = pos; SelectionLength = value.Length; HandleSelectionChanged (); } } void HandleSelectionChanged () { if (cacheSelectionStart != SelectionStart || cacheSelectionLength != SelectionLength) { cacheSelectionStart = SelectionStart; cacheSelectionLength = SelectionLength; ApplicationContext.InvokeUserCode (EventSink.OnSelectionChanged); } } public bool HasCompletions { get { return false; } } public void SetCompletions (string[] completions) { } public void SetCompletionMatchFunc (Func<string, string, bool> matchFunc) { } #endregion #region Gross Hack // The 'Widget' property is not virtual and the one on the base class holds // the 'CustomAlignedContainer' object and *not* the NSTextField object. As // such everything that uses the 'Widget' property in the base class might be // working on the wrong object. The focus methods definitely need to work on // the NSTextField directly, so i've overridden those and made them interact // with the NSTextField instead of the CustomAlignedContainer. bool canGetFocus = true; public override bool CanGetFocus { get { return canGetFocus; } set { canGetFocus = value && Widget.AcceptsFirstResponder (); } } public override void SetFocus () { if (Widget.Window != null && CanGetFocus) Widget.Window.MakeFirstResponder (Widget); } public override bool HasFocus { get { return Widget.Window != null && Widget.Window.FirstResponder == Widget; } } #endregion public override Drawing.Color BackgroundColor { get { return Widget.BackgroundColor.ToXwtColor (); } set { Widget.BackgroundColor = value.ToNSColor (); Widget.Cell.DrawsBackground = true; Widget.Cell.BackgroundColor = value.ToNSColor (); } } } class CustomTextField: NSTextField, IViewObject { ITextEntryEventSink eventSink; ApplicationContext context; #pragma warning disable CS0414 // The private field is assigned but its value is never used CustomCell cell; #pragma warning disable CS0414 public CustomTextField (ITextEntryEventSink eventSink, ApplicationContext context) { this.context = context; this.eventSink = eventSink; this.Cell = cell = new CustomCell { BezelStyle = NSTextFieldBezelStyle.Square, Bezeled = true, Editable = true, EventSink = eventSink, Context = context, }; } public NSView View { get { return this; } } public ViewBackend Backend { get; set; } public override void DidChange (NSNotification notification) { base.DidChange (notification); context.InvokeUserCode (delegate { eventSink.OnChanged (); eventSink.OnSelectionChanged (); }); } public override string StringValue { get { return base.StringValue; } set { if (base.StringValue != value) { base.StringValue = value; context.InvokeUserCode (delegate { eventSink.OnChanged (); eventSink.OnSelectionChanged (); }); } } } class CustomCell : NSTextFieldCell { NSTextView editor; NSObject selChangeObserver; public ApplicationContext Context { get; set; } public ITextEntryEventSink EventSink { get; set; } public CustomCell () { } protected CustomCell(NativeHandle ptr) : base(ptr) { } /// <summary> /// Like what happens for the ios designer, AppKit can sometimes clone the native `NSTextFieldCell` using the Copy (NSZone) /// method. We *need* to ensure we can create a new managed wrapper for the cloned native object so we need the IntPtr /// constructor. NOTE: By keeping this override in managed we ensure the new wrapper C# object is created ~immediately, /// which makes it easier to debug issues. /// </summary> /// <returns>The copy.</returns> /// <param name="zone">Zone.</param> public override NSObject Copy(NSZone zone) { // Don't remove this override because the comment on this explains why we need this! var newCell = (CustomCell)base.Copy(zone); newCell.editor = editor; newCell.selChangeObserver = selChangeObserver; newCell.Context = Context; newCell.EventSink = EventSink; return newCell; } public override NSTextView FieldEditorForView (NSView aControlView) { if (editor == null) { editor = new CustomTextFieldCellEditor { Context = this.Context, EventSink = this.EventSink, FieldEditor = true, Editable = true, }; using (var key = new NSString("NSTextViewDidChangeSelectionNotification")) selChangeObserver = NSNotificationCenter.DefaultCenter.AddObserver (key, HandleSelectionDidChange, editor); } return editor; } void HandleSelectionDidChange (NSNotification notif) { Context.InvokeUserCode (EventSink.OnSelectionChanged); } public override void DrawInteriorWithFrame (CGRect cellFrame, NSView inView) { base.DrawInteriorWithFrame (VerticalCenteredRectForBounds(cellFrame), inView); } public override void EditWithFrame (CGRect aRect, NSView inView, NSText editor, NSObject delegateObject, NSEvent theEvent) { base.EditWithFrame (VerticalCenteredRectForBounds(aRect), inView, editor, delegateObject, theEvent); } public override void SelectWithFrame (CGRect aRect, NSView inView, NSText editor, NSObject delegateObject, nint selStart, nint selLength) { base.SelectWithFrame (VerticalCenteredRectForBounds(aRect), inView, editor, delegateObject, selStart, selLength); } CGRect VerticalCenteredRectForBounds (CGRect aRect) { // multiline entries should always align on top if (!UsesSingleLineMode) return aRect; var textHeight = CellSizeForBounds (aRect).Height; var offset = (aRect.Height - textHeight) / 2; if (offset <= 0) // do nothing if the frame is too small return aRect; var rect = new Rectangle (aRect.X, aRect.Y, aRect.Width, aRect.Height).Inflate (0.0, -offset); return rect.ToCGRect (); } } } class CustomTextFieldCellEditor : NSTextView { public ApplicationContext Context { get; set; } public ITextEntryEventSink EventSink { get; set; } public override void KeyDown(NSEvent theEvent) { Context.InvokeUserCode(delegate { EventSink.OnKeyPressed(theEvent.ToXwtKeyEventArgs()); }); base.KeyDown(theEvent); } nint cachedCursorPosition; public override void KeyUp(NSEvent theEvent) { if (cachedCursorPosition != SelectedRange.Location) { cachedCursorPosition = SelectedRange.Location; Context.InvokeUserCode(delegate { EventSink.OnSelectionChanged(); EventSink.OnKeyReleased(theEvent.ToXwtKeyEventArgs()); }); } base.KeyUp(theEvent); } public override bool BecomeFirstResponder() { var result = base.BecomeFirstResponder(); if (result) { Context.InvokeUserCode(() => { EventSink.OnGotFocus(); }); } return result; } public override bool ResignFirstResponder() { var result = base.ResignFirstResponder(); if (result) { Context.InvokeUserCode(() => { EventSink.OnLostFocus(); }); } return result; } } }
namespace DeepEqual { using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.CSharp.RuntimeBinder; using Binder = Microsoft.CSharp.RuntimeBinder.Binder; public static class ReflectionCache { private static readonly ConcurrentDictionary<Type, Type> EnumerationTypeCache = new ConcurrentDictionary<Type, Type>(); private static readonly ConcurrentDictionary<Type, bool> IsListCache = new ConcurrentDictionary<Type, bool>(); private static readonly ConcurrentDictionary<Type, bool> IsSetCache = new ConcurrentDictionary<Type, bool>(); private static readonly ConcurrentDictionary<Type, bool> IsDictionaryCache = new ConcurrentDictionary<Type, bool>(); private static readonly ConcurrentDictionary<Type, PropertyReader[]> PropertyCache = new ConcurrentDictionary<Type, PropertyReader[]>(); public static void ClearCache() { EnumerationTypeCache.Clear(); IsListCache.Clear(); IsSetCache.Clear(); IsDictionaryCache.Clear(); PropertyCache.Clear(); } internal static Type GetEnumerationType(Type type) { return EnumerationTypeCache.GetOrAdd(type, GetEnumerationTypeImpl); } private static Type GetEnumerationTypeImpl(Type type) { if (type.IsArray) { return type.GetElementType(); } var implements = type .GetInterfaces() .Union(new[] {type}) .FirstOrDefault( t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof (IEnumerable<>) ); if (implements == null) { return typeof (object); } return implements.GetGenericArguments()[0]; } internal static bool IsListType(Type type) { return IsListCache.GetOrAdd(type, IsListTypeImpl); } private static bool IsListTypeImpl(Type type) { var equals = type == typeof(IEnumerable); var inherits = type.GetInterface("IEnumerable") == typeof(IEnumerable); return equals || inherits; } internal static bool IsSetType(Type type) { return IsSetCache.GetOrAdd(type, IsSetTypeImpl); } private static bool IsSetTypeImpl(Type type) { bool isSet(Type t) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ISet<>); var equals = isSet(type); var inherits = type.GetInterfaces().Any(isSet); return equals || inherits; } internal static bool IsDictionaryType(Type type) { return IsDictionaryCache.GetOrAdd(type, IsDictionaryTypeImpl); } private static bool IsDictionaryTypeImpl(Type type) { var equals = type == typeof(IDictionary); var inherits = type.GetInterface("IDictionary") == typeof(IDictionary); return equals || inherits; } internal static bool IsValueType(Type type) { return type.IsValueType || type == typeof (string); } public static void CachePrivatePropertiesOfTypes(IEnumerable<Type> types) { PropertyReader[] GetAllProperties(Type t) => GetPropertiesAndFields(t, CacheBehaviour.IncludePrivate); foreach (var type in types) { PropertyCache.AddOrUpdate(type, GetAllProperties, (t, value) => GetAllProperties(t)); } } public static PropertyReader[] GetProperties(object obj) { // Dont cache dynamic properties if (obj is IDynamicMetaObjectProvider dyn) { return GetDynamicProperties(dyn); } var type = obj.GetType(); PropertyReader[] getPublicProperties(Type t) => GetPropertiesAndFields(t, CacheBehaviour.PublicOnly); return PropertyCache.GetOrAdd(type, getPublicProperties); } private static PropertyReader[] GetDynamicProperties(IDynamicMetaObjectProvider provider) { var metaObject = provider.GetMetaObject(Expression.Constant(provider)); // may return property names as well as method names, etc. var memberNames = metaObject.GetDynamicMemberNames(); var result = new List<PropertyReader>(); foreach (var name in memberNames) { try { var argumentInfo = new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }; var binder = Binder.GetMember( CSharpBinderFlags.None, name, provider.GetType(), argumentInfo); var site = CallSite<Func<CallSite, object, object>>.Create(binder); // will throw if no valid property getter var value = site.Target(site, provider); result.Add(new PropertyReader { Name = name, DeclaringType = provider.GetType(), Read = o => value }); } catch (RuntimeBinderException) { } } return result.ToArray(); } private static PropertyReader[] GetPropertiesAndFields(Type type, CacheBehaviour behaviour) { return GetProperties(type, behaviour) .Concat(GetFields(type, behaviour)) .ToArray(); } private static IEnumerable<PropertyReader> GetProperties(Type type, CacheBehaviour behaviour) { var bindingFlags = GetBindingFlags(behaviour); var properties = type.GetProperties(bindingFlags).AsEnumerable(); properties = RemoveHiddenProperties(properties); properties = ExcludeIndexProperties(properties); properties = ExcludeSetOnlyProperties(properties); return properties .Select( x => new PropertyReader { Name = x.Name, DeclaringType = type, Read = o => x.GetValue(o, null) }); } private static IEnumerable<PropertyInfo> RemoveHiddenProperties(IEnumerable<PropertyInfo> properties) { return properties .ToLookup(x => x.Name) .Select(x => x.First()); } private static IEnumerable<PropertyInfo> ExcludeIndexProperties(IEnumerable<PropertyInfo> properties) { return properties .Where(x => !x.GetIndexParameters().Any()); } private static IEnumerable<PropertyInfo> ExcludeSetOnlyProperties(IEnumerable<PropertyInfo> properties) { return properties .Where(x => x.GetMethod != null); } private static IEnumerable<PropertyReader> GetFields(Type type, CacheBehaviour behaviour) { var bindingFlags = GetBindingFlags(behaviour); var fields = type.GetFields(bindingFlags).AsEnumerable(); fields = RemoveHiddenFields(fields); return fields .Select( x => new PropertyReader { Name = x.Name, DeclaringType = type, Read = o => x.GetValue(o) }); } private static IEnumerable<FieldInfo> RemoveHiddenFields(IEnumerable<FieldInfo> properties) { return properties .ToLookup(x => x.Name) .Select(x => x.First()); } private static BindingFlags GetBindingFlags(CacheBehaviour behaviour) { var result = BindingFlags.Instance | BindingFlags.Public; if (behaviour == CacheBehaviour.IncludePrivate) { result |= BindingFlags.NonPublic; } return result; } } internal enum CacheBehaviour { PublicOnly, IncludePrivate } }
#pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.ui { public class SwitchableList : global::haxe.lang.HxObject, global::pony.IWards { public SwitchableList(global::haxe.lang.EmptyObject empty) { unchecked { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" { } } #line default } public SwitchableList(global::Array<object> a, global::haxe.lang.Null<int> def, global::haxe.lang.Null<int> swto) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" global::pony.ui.SwitchableList.__hx_ctor_pony_ui_SwitchableList(this, a, def, swto); } #line default } public static void __hx_ctor_pony_ui_SwitchableList(global::pony.ui.SwitchableList __temp_me118, global::Array<object> a, global::haxe.lang.Null<int> def, global::haxe.lang.Null<int> swto) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" int __temp_swto117 = ( (global::haxe.lang.Runtime.eq((swto).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (2) )) : (swto.@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" int __temp_def116 = ( (global::haxe.lang.Runtime.eq((def).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (0) )) : (def.@value) ); __temp_me118.swto = __temp_swto117; __temp_me118.currentPos = __temp_def116; __temp_me118.change = __temp_me118.@select = new global::pony.events.Signal(((object) (__temp_me118) )); __temp_me118.list = a; { #line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" int _g1 = 0; #line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" int _g = a.length; #line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" while (( _g1 < _g )) { #line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" int i = _g1++; if (( i == __temp_def116 )) { #line 52 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" ((global::pony.ui.ButtonCore) (a[i]) )._set_mode(__temp_swto117); } { #line 192 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" global::pony.events.Signal s = ((global::pony.ui.ButtonCore) (a[i]) ).click.subArgs(new global::Array<object>(new object[]{new global::Array<object>(new object[]{0}), new global::Array<object>(new object[]{i})})); #line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" global::pony.events.Signal _this = __temp_me118.@select; #line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" s.@add(global::pony.events._Listener.Listener_Impl_._fromFunction(global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (_this) ), global::haxe.lang.Runtime.toString("dispatchEvent"), ((int) (1181009664) ))) ), 1), true), default(global::haxe.lang.Null<int>)); #line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" global::pony.events.Signal __temp_expr565 = _this; } } } #line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" object __temp_stmt566 = default(object); #line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" { #line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (__temp_me118) ), global::haxe.lang.Runtime.toString("setState"), ((int) (306175759) ))) ), 1); #line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" __temp_stmt566 = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false); } #line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" __temp_me118.@select.@add(__temp_stmt566, new global::haxe.lang.Null<int>(-1, true)); } #line default } public static new object __hx_createEmpty() { unchecked { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return new global::pony.ui.SwitchableList(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return new global::pony.ui.SwitchableList(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (arr[0]) ))) ), global::haxe.lang.Null<object>.ofDynamic<int>(arr[1]), global::haxe.lang.Null<object>.ofDynamic<int>(arr[2])); } #line default } public global::pony.events.Signal change; public int currentPos; public global::Array<object> list; public global::pony.events.Signal @select; public int swto; public virtual void setState(int n) { unchecked { #line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" ((global::pony.ui.ButtonCore) (this.list[this.currentPos]) )._set_mode(0); ((global::pony.ui.ButtonCore) (this.list[n]) )._set_mode(this.swto); this.currentPos = n; } #line default } public virtual void next() { unchecked { #line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" if (( ( this.currentPos + 1 ) < this.list.length )) { #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" global::pony.events.Signal _this = this.@select; #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" _this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{( this.currentPos + 1 )})) ), ((object) (_this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) ))); #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" global::pony.events.Signal __temp_expr563 = _this; } } #line default } public virtual void prev() { unchecked { #line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" if (( ( this.currentPos - 1 ) >= 0 )) { #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" global::pony.events.Signal _this = this.@select; #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" _this.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<object>(new object[]{( this.currentPos - 1 )})) ), ((object) (_this.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) ))); #line 134 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Signal.hx" global::pony.events.Signal __temp_expr564 = _this; } } #line default } public int _get_state() { unchecked { #line 72 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return this.currentPos; } #line default } public int _set_state(int v) { unchecked { #line 73 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return this.currentPos = v; } #line default } public override double __hx_setField_f(string field, int hash, double @value, bool handleProperties) { unchecked { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" switch (hash) { case 1281243935: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this.swto = ((int) (@value) ); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return @value; } case 67859985: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this._set_state(((int) (@value) )); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return @value; } case 1194336987: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this.currentPos = ((int) (@value) ); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return @value; } default: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return base.__hx_setField_f(field, hash, @value, handleProperties); } } } #line default } public override object __hx_setField(string field, int hash, object @value, bool handleProperties) { unchecked { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" switch (hash) { case 1281243935: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this.swto = ((int) (global::haxe.lang.Runtime.toInt(@value)) ); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return @value; } case 1781734140: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this.@select = ((global::pony.events.Signal) (@value) ); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return @value; } case 67859985: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this._set_state(((int) (global::haxe.lang.Runtime.toInt(@value)) )); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return @value; } case 1202920542: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this.list = ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (@value) ))) ); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return @value; } case 1194336987: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this.currentPos = ((int) (global::haxe.lang.Runtime.toInt(@value)) ); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return @value; } case 930255216: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this.change = ((global::pony.events.Signal) (@value) ); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return @value; } default: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return base.__hx_setField(field, hash, @value, handleProperties); } } } #line default } public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties) { unchecked { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" switch (hash) { case 721796724: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("set_state"), ((int) (721796724) ))) ); } case 1203032680: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("get_state"), ((int) (1203032680) ))) ); } case 1247723251: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("prev"), ((int) (1247723251) ))) ); } case 1224901875: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("next"), ((int) (1224901875) ))) ); } case 306175759: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("setState"), ((int) (306175759) ))) ); } case 1281243935: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return this.swto; } case 1781734140: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return this.@select; } case 67859985: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return this._get_state(); } case 1202920542: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return this.list; } case 1194336987: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return this.currentPos; } case 930255216: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return this.change; } default: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties); } } } #line default } public override double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties) { unchecked { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" switch (hash) { case 1281243935: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return ((double) (this.swto) ); } case 67859985: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return ((double) (this._get_state()) ); } case 1194336987: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return ((double) (this.currentPos) ); } default: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return base.__hx_getField_f(field, hash, throwErrors, handleProperties); } } } #line default } public override object __hx_invokeField(string field, int hash, global::Array dynargs) { unchecked { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" switch (hash) { case 721796724: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return this._set_state(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) )); } case 1203032680: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return this._get_state(); } case 1247723251: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this.prev(); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" break; } case 1224901875: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this.next(); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" break; } case 306175759: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" this.setState(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) )); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" break; } default: { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return base.__hx_invokeField(field, hash, dynargs); } } #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" return default(object); } #line default } public override void __hx_getFields(global::Array<object> baseArr) { unchecked { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" baseArr.push("swto"); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" baseArr.push("select"); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" baseArr.push("state"); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" baseArr.push("list"); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" baseArr.push("currentPos"); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" baseArr.push("change"); #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" { #line 36 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/ui/SwitchableList.hx" base.__hx_getFields(baseArr); } } #line default } public int state { get { return _get_state(); } set { _set_state(value); } } } }
using System; using System.Diagnostics; using System.Text; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; using sqlite3_int64 = System.Int64; namespace Community.CsharpSqlite { using sqlite3_stmt = Sqlite3.Vdbe; public partial class Sqlite3 { /* ** 2005 May 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the implementation of the sqlite3_prepare() ** interface, and routines that contribute to loading the database schema ** from disk. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-03-09 19:31:43 4ae453ea7be69018d8c16eb8dabe05617397dc4d ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" /* ** Fill the InitData structure with an error message that indicates ** that the database is corrupt. */ static void corruptSchema( InitData pData, /* Initialization context */ string zObj, /* Object being parsed at the point of error */ string zExtra /* Error information */ ) { sqlite3 db = pData.db; if ( /* 0 == db.mallocFailed && */ (db.flags & SQLITE_RecoveryMode) == 0) { { if (zObj == null) zObj = "?"; sqlite3SetString(ref pData.pzErrMsg, db, "malformed database schema (%s)", zObj); if (!String.IsNullOrEmpty(zExtra)) { pData.pzErrMsg = sqlite3MAppendf(db, pData.pzErrMsg , "%s - %s", pData.pzErrMsg, zExtra); } } pData.rc = //db.mallocFailed != 0 ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT(); } } /* ** This is the callback routine for the code that initializes the ** database. See sqlite3Init() below for additional information. ** This routine is also called from the OP_ParseSchema opcode of the VDBE. ** ** Each callback contains the following information: ** ** argv[0] = name of thing being created ** argv[1] = root page number for table or index. 0 for trigger or view. ** argv[2] = SQL text for the CREATE statement. ** */ static int sqlite3InitCallback(object pInit, sqlite3_int64 argc, object p2, object NotUsed) { string[] argv = (string[])p2; InitData pData = (InitData)pInit; sqlite3 db = pData.db; int iDb = pData.iDb; Debug.Assert(argc == 3); UNUSED_PARAMETER2(NotUsed, argc); Debug.Assert(sqlite3_mutex_held(db.mutex)); DbClearProperty(db, iDb, DB_Empty); //if ( db.mallocFailed != 0 ) //{ // corruptSchema( pData, argv[0], "" ); // return 1; //} Debug.Assert(iDb >= 0 && iDb < db.nDb); if (argv == null) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ if (argv[1] == null) { corruptSchema(pData, argv[0], ""); } else if (!String.IsNullOrEmpty(argv[2])) { /* Call the parser to process a CREATE TABLE, INDEX or VIEW. ** But because db.init.busy is set to 1, no VDBE code is generated ** or executed. All the parser does is build the internal data ** structures that describe the table, index, or view. */ string zErr = ""; int rc; Debug.Assert(db.init.busy != 0); db.init.iDb = iDb; db.init.newTnum = atoi(argv[1]); db.init.orphanTrigger = 0; rc = sqlite3_exec(db, argv[2], null, null, ref zErr); db.init.iDb = 0; Debug.Assert(rc != SQLITE_OK || zErr == ""); if (SQLITE_OK != rc) { if (db.init.orphanTrigger != 0) { Debug.Assert(iDb == 1); } else { pData.rc = rc; if (rc == SQLITE_NOMEM) { // db.mallocFailed = 1; } else if (rc != SQLITE_INTERRUPT && rc != SQLITE_LOCKED) { corruptSchema(pData, argv[0], zErr); } } sqlite3DbFree(db, ref zErr); } } else if (argv[0] == null || argv[0] == "") { corruptSchema(pData, null, null); } else { /* If the SQL column is blank it means this is an index that ** was created to be the PRIMARY KEY or to fulfill a UNIQUE ** constraint for a CREATE TABLE. The index should have already ** been created when we processed the CREATE TABLE. All we have ** to do here is record the root page number for that index. */ Index pIndex; pIndex = sqlite3FindIndex(db, argv[0], db.aDb[iDb].zName); if (pIndex == null) { /* This can occur if there exists an index on a TEMP table which ** has the same name as another index on a permanent index. Since ** the permanent table is hidden by the TEMP table, we can also ** safely ignore the index on the permanent table. */ /* Do Nothing */ ; } else if (sqlite3GetInt32(argv[1], ref pIndex.tnum) == false) { corruptSchema(pData, argv[0], "invalid rootpage"); } } return 0; } /* ** Attempt to read the database schema and initialize internal ** data structures for a single database file. The index of the ** database file is given by iDb. iDb==0 is used for the main ** database. iDb==1 should never be used. iDb>=2 is used for ** auxiliary databases. Return one of the SQLITE_ error codes to ** indicate success or failure. */ static int sqlite3InitOne(sqlite3 db, int iDb, ref string pzErrMsg) { int rc; int i; int size; Table pTab; Db pDb; string[] azArg = new string[4]; u32[] meta = new u32[5]; InitData initData = new InitData(); string zMasterSchema; string zMasterName = SCHEMA_TABLE(iDb); int openedTransaction = 0; /* ** The master database table has a structure like this */ string master_schema = "CREATE TABLE sqlite_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")" ; #if !SQLITE_OMIT_TEMPDB string temp_master_schema = "CREATE TEMP TABLE sqlite_temp_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")" ; #else //#define temp_master_schema 0 #endif Debug.Assert(iDb >= 0 && iDb < db.nDb); Debug.Assert(db.aDb[iDb].pSchema != null); Debug.Assert(sqlite3_mutex_held(db.mutex)); Debug.Assert(iDb == 1 || sqlite3BtreeHoldsMutex(db.aDb[iDb].pBt)); /* zMasterSchema and zInitScript are set to point at the master schema ** and initialisation script appropriate for the database being ** initialised. zMasterName is the name of the master table. */ if (OMIT_TEMPDB == 0 && iDb == 1) { zMasterSchema = temp_master_schema; } else { zMasterSchema = master_schema; } zMasterName = SCHEMA_TABLE(iDb); /* Construct the schema tables. */ azArg[0] = zMasterName; azArg[1] = "1"; azArg[2] = zMasterSchema; azArg[3] = ""; initData.db = db; initData.iDb = iDb; initData.rc = SQLITE_OK; initData.pzErrMsg = pzErrMsg; sqlite3InitCallback(initData, 3, azArg, null); if (initData.rc != 0) { rc = initData.rc; goto error_out; } pTab = sqlite3FindTable(db, zMasterName, db.aDb[iDb].zName); if (ALWAYS(pTab)) { pTab.tabFlags |= TF_Readonly; } /* Create a cursor to hold the database open */ pDb = db.aDb[iDb]; if (pDb.pBt == null) { if (OMIT_TEMPDB == 0 && ALWAYS(iDb == 1)) { DbSetProperty(db, 1, DB_SchemaLoaded); } return SQLITE_OK; } /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed before this function returns. */ sqlite3BtreeEnter(pDb.pBt); if (!sqlite3BtreeIsInReadTrans(pDb.pBt)) { rc = sqlite3BtreeBeginTrans(pDb.pBt, 0); if (rc != SQLITE_OK) { sqlite3SetString(ref pzErrMsg, db, "%s", sqlite3ErrStr(rc)); goto initone_error_out; } openedTransaction = 1; } /* Get the database meta information. ** ** Meta values are as follows: ** meta[0] Schema cookie. Changes with each schema change. ** meta[1] File format of schema layer. ** meta[2] Size of the page cache. ** meta[3] Largest rootpage (auto/incr_vacuum mode) ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE ** meta[5] User version ** meta[6] Incremental vacuum mode ** meta[7] unused ** meta[8] unused ** meta[9] unused ** ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to ** the possible values of meta[BTREE_TEXT_ENCODING-1]. */ for (i = 0; i < ArraySize(meta); i++) { sqlite3BtreeGetMeta(pDb.pBt, i + 1, ref meta[i]); } pDb.pSchema.schema_cookie = (int)meta[BTREE_SCHEMA_VERSION - 1]; /* If opening a non-empty database, check the text encoding. For the ** main database, set sqlite3.enc to the encoding of the main database. ** For an attached db, it is an error if the encoding is not the same ** as sqlite3.enc. */ if (meta[BTREE_TEXT_ENCODING - 1] != 0) { /* text encoding */ if (iDb == 0) { u8 encoding; /* If opening the main database, set ENC(db). */ encoding = (u8)(meta[BTREE_TEXT_ENCODING - 1] & 3); if (encoding == 0) encoding = SQLITE_UTF8; db.aDb[0].pSchema.enc = encoding; //ENC( db ) = encoding; db.pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0); } else { /* If opening an attached database, the encoding much match ENC(db) */ if (meta[BTREE_TEXT_ENCODING - 1] != ENC(db)) { sqlite3SetString(ref pzErrMsg, db, "attached databases must use the same" + " text encoding as main database"); rc = SQLITE_ERROR; goto initone_error_out; } } } else { DbSetProperty(db, iDb, DB_Empty); } pDb.pSchema.enc = ENC(db); if (pDb.pSchema.cache_size == 0) { size = (int)meta[BTREE_DEFAULT_CACHE_SIZE - 1]; if (size == 0) { size = SQLITE_DEFAULT_CACHE_SIZE; } if (size < 0) size = -size; pDb.pSchema.cache_size = size; sqlite3BtreeSetCacheSize(pDb.pBt, pDb.pSchema.cache_size); } /* ** file_format==1 Version 3.0.0. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants */ pDb.pSchema.file_format = (u8)meta[BTREE_FILE_FORMAT - 1]; if (pDb.pSchema.file_format == 0) { pDb.pSchema.file_format = 1; } if (pDb.pSchema.file_format > SQLITE_MAX_FILE_FORMAT) { sqlite3SetString(ref pzErrMsg, db, "unsupported file format"); rc = SQLITE_ERROR; goto initone_error_out; } /* Ticket #2804: When we open a database in the newer file format, ** clear the legacy_file_format pragma flag so that a VACUUM will ** not downgrade the database and thus invalidate any descending ** indices that the user might have created. */ if (iDb == 0 && meta[BTREE_FILE_FORMAT - 1] >= 4) { db.flags &= ~SQLITE_LegacyFileFmt; } /* Read the schema information out of the schema tables */ Debug.Assert(db.init.busy != 0); { string zSql; zSql = sqlite3MPrintf(db, "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid", db.aDb[iDb].zName, zMasterName); #if ! SQLITE_OMIT_AUTHORIZATION { int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); xAuth = db.xAuth; db.xAuth = 0; #endif rc = sqlite3_exec(db, zSql, (dxCallback)sqlite3InitCallback, initData, 0); pzErrMsg = initData.pzErrMsg; #if ! SQLITE_OMIT_AUTHORIZATION db.xAuth = xAuth; } #endif if (rc == SQLITE_OK) rc = initData.rc; sqlite3DbFree(db, ref zSql); #if !SQLITE_OMIT_ANALYZE if (rc == SQLITE_OK) { sqlite3AnalysisLoad(db, iDb); } #endif } //if ( db.mallocFailed != 0 ) //{ // rc = SQLITE_NOMEM; // sqlite3ResetInternalSchema( db, 0 ); //} if (rc == SQLITE_OK || (db.flags & SQLITE_RecoveryMode) != 0) { /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider ** the schema loaded, even if errors occurred. In this situation the ** current sqlite3_prepare() operation will fail, but the following one ** will attempt to compile the supplied statement against whatever subset ** of the schema was loaded before the error occurred. The primary ** purpose of this is to allow access to the sqlite_master table ** even when its contents have been corrupted. */ DbSetProperty(db, iDb, DB_SchemaLoaded); rc = SQLITE_OK; } /* Jump here for an error that occurs after successfully allocating ** curMain and calling sqlite3BtreeEnter(). For an error that occurs ** before that point, jump to error_out. */ initone_error_out: if (openedTransaction != 0) { sqlite3BtreeCommit(pDb.pBt); } sqlite3BtreeLeave(pDb.pBt); error_out: if (rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM) { // db.mallocFailed = 1; } return rc; } /* ** Initialize all database files - the main database file, the file ** used to store temporary tables, and any additional database files ** created using ATTACH statements. Return a success code. If an ** error occurs, write an error message into pzErrMsg. ** ** After a database is initialized, the DB_SchemaLoaded bit is set ** bit is set in the flags field of the Db structure. If the database ** file was of zero-length, then the DB_Empty flag is also set. */ static int sqlite3Init(sqlite3 db, ref string pzErrMsg) { int i, rc; bool commit_internal = !((db.flags & SQLITE_InternChanges) != 0); Debug.Assert(sqlite3_mutex_held(db.mutex)); rc = SQLITE_OK; db.init.busy = 1; for (i = 0; rc == SQLITE_OK && i < db.nDb; i++) { if (DbHasProperty(db, i, DB_SchemaLoaded) || i == 1) continue; rc = sqlite3InitOne(db, i, ref pzErrMsg); if (rc != 0) { sqlite3ResetInternalSchema(db, i); } } /* Once all the other databases have been initialised, load the schema ** for the TEMP database. This is loaded last, as the TEMP database ** schema may contain references to objects in other databases. */ #if !SQLITE_OMIT_TEMPDB if (rc == SQLITE_OK && ALWAYS(db.nDb > 1) && !DbHasProperty(db, 1, DB_SchemaLoaded)) { rc = sqlite3InitOne(db, 1, ref pzErrMsg); if (rc != 0) { sqlite3ResetInternalSchema(db, 1); } } #endif db.init.busy = 0; if (rc == SQLITE_OK && commit_internal) { sqlite3CommitInternalChanges(db); } return rc; } /* ** This routine is a no-op if the database schema is already initialised. ** Otherwise, the schema is loaded. An error code is returned. */ static int sqlite3ReadSchema(Parse pParse) { int rc = SQLITE_OK; sqlite3 db = pParse.db; Debug.Assert(sqlite3_mutex_held(db.mutex)); if (0 == db.init.busy) { rc = sqlite3Init(db, ref pParse.zErrMsg); } if (rc != SQLITE_OK) { pParse.rc = rc; pParse.nErr++; } return rc; } /* ** Check schema cookies in all databases. If any cookie is out ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies ** make no changes to pParse->rc. */ static void schemaIsValid(Parse pParse) { sqlite3 db = pParse.db; int iDb; int rc; u32 cookie = 0; Debug.Assert(pParse.checkSchema != 0); Debug.Assert(sqlite3_mutex_held(db.mutex)); for (iDb = 0; iDb < db.nDb; iDb++) { int openedTransaction = 0; /* True if a transaction is opened */ Btree pBt = db.aDb[iDb].pBt; /* Btree database to read cookie from */ if (pBt == null) continue; /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed immediately after reading the meta-value. */ if (!sqlite3BtreeIsInReadTrans(pBt)) { rc = sqlite3BtreeBeginTrans(pBt, 0); //if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM ) //{ // db.mallocFailed = 1; //} if (rc != SQLITE_OK) return; openedTransaction = 1; } /* Read the schema cookie from the database. If it does not match the ** value stored as part of the in-memory schema representation, ** set Parse.rc to SQLITE_SCHEMA. */ sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, ref cookie); if (cookie != db.aDb[iDb].pSchema.schema_cookie) { pParse.rc = SQLITE_SCHEMA; } /* Close the transaction, if one was opened. */ if (openedTransaction != 0) { sqlite3BtreeCommit(pBt); } } } /* ** Convert a schema pointer into the iDb index that indicates ** which database file in db.aDb[] the schema refers to. ** ** If the same database is attached more than once, the first ** attached database is returned. */ static int sqlite3SchemaToIndex(sqlite3 db, Schema pSchema) { int i = -1000000; /* If pSchema is NULL, then return -1000000. This happens when code in ** expr.c is trying to resolve a reference to a transient table (i.e. one ** created by a sub-select). In this case the return value of this ** function should never be used. ** ** We return -1000000 instead of the more usual -1 simply because using ** -1000000 as the incorrect index into db->aDb[] is much ** more likely to cause a segfault than -1 (of course there are assert() ** statements too, but it never hurts to play the odds). */ Debug.Assert(sqlite3_mutex_held(db.mutex)); if (pSchema != null) { for (i = 0; ALWAYS(i < db.nDb); i++) { if (db.aDb[i].pSchema == pSchema) { break; } } Debug.Assert(i >= 0 && i < db.nDb); } return i; } /* ** Compile the UTF-8 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ Vdbe pReprepare, /* VM being reprepared */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { Parse pParse; /* Parsing context */ string zErrMsg = ""; /* Error message */ int rc = SQLITE_OK; /* Result code */ int i; /* Loop counter */ /* Allocate the parsing context */ pParse = new Parse();//sqlite3StackAllocZero(db, sizeof(*pParse)); if (pParse == null) { rc = SQLITE_NOMEM; goto end_prepare; } pParse.pReprepare = pReprepare; pParse.sLastToken.z = ""; Debug.Assert(ppStmt == null);// assert( ppStmt && *ppStmt==0 ); //Debug.Assert( 0 == db.mallocFailed ); Debug.Assert(sqlite3_mutex_held(db.mutex)); /* Check to verify that it is possible to get a read lock on all ** database schemas. The inability to get a read lock indicates that ** some other database connection is holding a write-lock, which in ** turn means that the other connection has made uncommitted changes ** to the schema. ** ** Were we to proceed and prepare the statement against the uncommitted ** schema changes and if those schema changes are subsequently rolled ** back and different changes are made in their place, then when this ** prepared statement goes to run the schema cookie would fail to detect ** the schema change. Disaster would follow. ** ** This thread is currently holding mutexes on all Btrees (because ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it ** is not possible for another thread to start a new schema change ** while this routine is running. Hence, we do not need to hold ** locks on the schema, we just need to make sure nobody else is ** holding them. ** ** Note that setting READ_UNCOMMITTED overrides most lock detection, ** but it does *not* override schema lock detection, so this all still ** works even if READ_UNCOMMITTED is set. */ for (i = 0; i < db.nDb; i++) { Btree pBt = db.aDb[i].pBt; if (pBt != null) { Debug.Assert(sqlite3BtreeHoldsMutex(pBt)); rc = sqlite3BtreeSchemaLocked(pBt); if (rc != 0) { string zDb = db.aDb[i].zName; sqlite3Error(db, rc, "database schema is locked: %s", zDb); testcase(db.flags & SQLITE_ReadUncommitted); goto end_prepare; } } } sqlite3VtabUnlockList(db); pParse.db = db; if (nBytes >= 0 && (nBytes == 0 || zSql[nBytes - 1] != 0)) { string zSqlCopy; int mxLen = db.aLimit[SQLITE_LIMIT_SQL_LENGTH]; testcase(nBytes == mxLen); testcase(nBytes == mxLen + 1); if (nBytes > mxLen) { sqlite3Error(db, SQLITE_TOOBIG, "statement too long"); rc = sqlite3ApiExit(db, SQLITE_TOOBIG); goto end_prepare; } zSqlCopy = zSql.Substring(0, nBytes);// sqlite3DbStrNDup(db, zSql, nBytes); if (zSqlCopy != null) { sqlite3RunParser(pParse, zSqlCopy, ref zErrMsg); sqlite3DbFree(db, ref zSqlCopy); //pParse->zTail = &zSql[pParse->zTail-zSqlCopy]; } else { //pParse->zTail = &zSql[nBytes]; } } else { sqlite3RunParser(pParse, zSql, ref zErrMsg); } //if ( db.mallocFailed != 0 ) //{ // pParse.rc = SQLITE_NOMEM; //} if (pParse.rc == SQLITE_DONE) pParse.rc = SQLITE_OK; if (pParse.checkSchema != 0) { schemaIsValid(pParse); } if (pParse.rc == SQLITE_SCHEMA) { sqlite3ResetInternalSchema(db, 0); } //if ( db.mallocFailed != 0 ) //{ // pParse.rc = SQLITE_NOMEM; //} //if (pzTail != null) { pzTail = pParse.zTail == null ? "" : pParse.zTail.ToString(); } rc = pParse.rc; #if !SQLITE_OMIT_EXPLAIN if (rc == SQLITE_OK && pParse.pVdbe != null && pParse.explain != 0) { string[] azColName = new string[] { "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", "order", "from", "detail" }; int iFirst, mx; if (pParse.explain == 2) { sqlite3VdbeSetNumCols(pParse.pVdbe, 3); iFirst = 8; mx = 11; } else { sqlite3VdbeSetNumCols(pParse.pVdbe, 8); iFirst = 0; mx = 8; } for (i = iFirst; i < mx; i++) { sqlite3VdbeSetColName(pParse.pVdbe, i - iFirst, COLNAME_NAME, azColName[i], SQLITE_STATIC); } } #endif Debug.Assert(db.init.busy == 0 || saveSqlFlag == 0); if (db.init.busy == 0) { Vdbe pVdbe = pParse.pVdbe; sqlite3VdbeSetSql(pVdbe, zSql, (int)(zSql.Length - (pParse.zTail == null ? 0 : pParse.zTail.Length)), saveSqlFlag); } if (pParse.pVdbe != null && (rc != SQLITE_OK /*|| db.mallocFailed != 0 */ )) { sqlite3VdbeFinalize(pParse.pVdbe); Debug.Assert(ppStmt == null); } else { ppStmt = pParse.pVdbe; } if (zErrMsg != "") { sqlite3Error(db, rc, "%s", zErrMsg); sqlite3DbFree(db, ref zErrMsg); } else { sqlite3Error(db, rc, 0); } /* Delete any TriggerPrg structures allocated while parsing this statement. */ while (pParse.pTriggerPrg != null) { TriggerPrg pT = pParse.pTriggerPrg; pParse.pTriggerPrg = pT.pNext; sqlite3VdbeProgramDelete(db, pT.pProgram, 0); pT = null; sqlite3DbFree(db, ref pT); } end_prepare: //sqlite3StackFree( db, pParse ); rc = sqlite3ApiExit(db, rc); Debug.Assert((rc & db.errMask) == rc); return rc; } static int sqlite3LockAndPrepare( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ Vdbe pOld, /* VM being reprepared */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; // assert( ppStmt!=0 ); ppStmt = null; if (!sqlite3SafetyCheckOk(db)) { return SQLITE_MISUSE_BKPT(); } sqlite3_mutex_enter(db.mutex); sqlite3BtreeEnterAll(db); rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ref ppStmt, ref pzTail); if (rc == SQLITE_SCHEMA) { sqlite3_finalize(ref ppStmt); rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ref ppStmt, ref pzTail); } sqlite3BtreeLeaveAll(db); sqlite3_mutex_leave(db.mutex); return rc; } /* ** Rerun the compilation of a statement after a schema change. ** ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, ** if the statement cannot be recompiled because another connection has ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error ** occurs, return SQLITE_SCHEMA. */ static int sqlite3Reprepare(Vdbe p) { int rc; sqlite3_stmt pNew = new sqlite3_stmt(); string zSql; sqlite3 db; Debug.Assert(sqlite3_mutex_held(sqlite3VdbeDb(p).mutex)); zSql = sqlite3_sql((sqlite3_stmt)p); Debug.Assert(zSql != null); /* Reprepare only called for prepare_v2() statements */ db = sqlite3VdbeDb(p); Debug.Assert(sqlite3_mutex_held(db.mutex)); string dummy = ""; rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, ref pNew, ref dummy); if (rc != 0) { if (rc == SQLITE_NOMEM) { // db.mallocFailed = 1; } Debug.Assert(pNew == null); return rc; } else { Debug.Assert(pNew != null); } sqlite3VdbeSwap((Vdbe)pNew, p); sqlite3TransferBindings(pNew, (sqlite3_stmt)p); sqlite3VdbeResetStepResult((Vdbe)pNew); sqlite3VdbeFinalize((Vdbe)pNew); return SQLITE_OK; } /* ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by ** sqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ static public int sqlite3_prepare( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; rc = sqlite3LockAndPrepare(db, zSql, nBytes, 0, null, ref ppStmt, ref pzTail); Debug.Assert(rc == SQLITE_OK || ppStmt == null); /* VERIFY: F13021 */ return rc; } public static int sqlite3_prepare_v2( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ int dummy /* ( No string passed) */ ) { string pzTail = null; int rc; rc = sqlite3LockAndPrepare(db, zSql, nBytes, 1, null, ref ppStmt, ref pzTail); Debug.Assert(rc == SQLITE_OK || ppStmt == null); /* VERIFY: F13021 */ return rc; } public static int sqlite3_prepare_v2( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; rc = sqlite3LockAndPrepare(db, zSql, nBytes, 1, null, ref ppStmt, ref pzTail); Debug.Assert(rc == SQLITE_OK || ppStmt == null); /* VERIFY: F13021 */ return rc; } #if ! SQLITE_OMIT_UTF16 /* ** Compile the UTF-16 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare16( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ bool saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ){ /* This function currently works by first transforming the UTF-16 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The ** tricky bit is figuring out the pointer to return in pzTail. */ string zSql8; string zTail8 = ""; int rc = SQLITE_OK; assert( ppStmt ); *ppStmt = 0; if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } sqlite3_mutex_enter(db.mutex); zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); if( zSql8 !=""){ rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, null, ref ppStmt, ref zTail8); } if( zTail8 !="" && pzTail !=""){ /* If sqlite3_prepare returns a tail pointer, we calculate the ** equivalent pointer into the UTF-16 string by counting the unicode ** characters between zSql8 and zTail8, and then returning a pointer ** the same number of characters into the UTF-16 string. */ Debugger.Break (); // TODO -- // int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); // pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); } sqlite3DbFree(db,ref zSql8); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db.mutex); return rc; } /* ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by ** sqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ public static int sqlite3_prepare16( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ){ int rc; rc = sqlite3Prepare16(db,zSql,nBytes,false,ref ppStmt,ref pzTail); Debug.Assert( rc==SQLITE_OK || ppStmt==null || ppStmt==null ); /* VERIFY: F13021 */ return rc; } public static int sqlite3_prepare16_v2( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; rc = sqlite3Prepare16(db,zSql,nBytes,true,ref ppStmt,ref pzTail); Debug.Assert( rc==SQLITE_OK || ppStmt==null || ppStmt==null ); /* VERIFY: F13021 */ return rc; } #endif // * SQLITE_OMIT_UTF16 */ } }
//EDITOR CLASS TO CREATE QUAD MESH WITH SPECIFIED ANCHOR //Created by Alan Thorn on 23.01.2013 //------------------------------------------------ using UnityEngine; using UnityEditor; using System.IO; //------------------------------------------------ //Run from unity editor. This class should be placed in Editor folder public class CreateQuad : ScriptableWizard { //Anchor point for created quad public enum AnchorPoint { TopLeft, TopMiddle, TopRight, RightMiddle, BottomRight, BottomMiddle, BottomLeft, LeftMiddle, Center, Custom } //Name of Quad Asset public string MeshName = "Quad"; //Game Object Name public string GameObjectName = "Plane_Object"; //Name of asset folder to contain quad asset when created public string AssetFolder = "Assets"; //Width of quad in world units (pixels) public float Width = 1.0f; //Height of quad in world units (pixels) public float Height = 1.0f; //Position of Anchor public AnchorPoint Anchor = AnchorPoint.Center; //Horz Position of Anchor on Plane public float AnchorX = 0.5f; //Vert Position of Anchor on Plane public float AnchorY = 0.5f; //------------------------------------------------ [MenuItem("GameObject/Create Other/Custom Plane")] static void CreateWizard() { ScriptableWizard.DisplayWizard("Create Plane",typeof(CreateQuad)); } //------------------------------------------------ //Function called when window is created void OnEnable() { //Call selection change to load asset path from selected, if any OnSelectionChange(); } //------------------------------------------------ //Called 10 times per second void OnInspectorUpdate() { switch(Anchor) { //Anchor is set to top-left case AnchorPoint.TopLeft: AnchorX = 0.0f * Width; AnchorY = 1.0f * Height; break; //Anchor is set to top-middle case AnchorPoint.TopMiddle: AnchorX = 0.5f * Width; AnchorY = 1.0f * Height; break; //Anchor is set to top-right case AnchorPoint.TopRight: AnchorX = 1.0f * Width; AnchorY = 1.0f * Height; break; //Anchor is set to right-middle case AnchorPoint.RightMiddle: AnchorX = 1.0f * Width; AnchorY = 0.5f * Height; break; //Anchor is set to Bottom-Right case AnchorPoint.BottomRight: AnchorX = 1.0f * Width; AnchorY = 0.0f * Height; break; //Anchor is set to Bottom-Middle case AnchorPoint.BottomMiddle: AnchorX = 0.5f * Width; AnchorY = 0.0f * Height; break; //Anchor is set to Bottom-Left case AnchorPoint.BottomLeft: AnchorX = 0.0f * Width; AnchorY = 0.0f * Height; break; //Anchor is set to Left-Middle case AnchorPoint.LeftMiddle: AnchorX = 0.0f * Width; AnchorY = 0.5f * Height; break; //Anchor is set to center case AnchorPoint.Center: AnchorX = 0.5f * Width; AnchorY = 0.5f * Height; break; case AnchorPoint.Custom: default: break; } } //------------------------------------------------ //Function called when window is updated void OnSelectionChange() { //Check user selection in editor - check for folder selection if (Selection.objects != null && Selection.objects.Length == 1) { //Get path from selected asset AssetFolder = Path.GetDirectoryName(AssetDatabase.GetAssetPath(Selection.objects[0])); } } //------------------------------------------------ //Function to create quad mesh void OnWizardCreate() { //Create Vertices Vector3[] Vertices = new Vector3[4]; //Create UVs Vector2[] UVs = new Vector2[4]; //Two triangles of quad int[] Triangles = new int[6]; //Assign vertices based on pivot //Bottom-left Vertices[0].x = -AnchorX; Vertices[0].y = -AnchorY; //Bottom-right Vertices[1].x = Vertices[0].x+Width; Vertices[1].y = Vertices[0].y; //Top-left Vertices[2].x = Vertices[0].x; Vertices[2].y = Vertices[0].y+Height; //Top-right Vertices[3].x = Vertices[0].x+Width; Vertices[3].y = Vertices[0].y+Height; //Assign UVs //Bottom-left UVs[0].x=0.0f; UVs[0].y=0.0f; //Bottom-right UVs[1].x=1.0f; UVs[1].y=0.0f; //Top-left UVs[2].x=0.0f; UVs[2].y=1.0f; //Top-right UVs[3].x=1.0f; UVs[3].y=1.0f; //Assign triangles Triangles[0]=3; Triangles[1]=1; Triangles[2]=2; Triangles[3]=2; Triangles[4]=1; Triangles[5]=0; //Generate mesh Mesh mesh = new Mesh(); mesh.name = MeshName; mesh.vertices = Vertices; mesh.uv = UVs; mesh.triangles = Triangles; mesh.RecalculateNormals(); //Create asset in database AssetDatabase.CreateAsset(mesh, AssetDatabase.GenerateUniqueAssetPath(AssetFolder + "/" + MeshName) + ".asset"); AssetDatabase.SaveAssets(); //Create plane game object GameObject plane = new GameObject(GameObjectName); MeshFilter meshFilter = (MeshFilter)plane.AddComponent(typeof(MeshFilter)); plane.AddComponent(typeof(MeshRenderer)); //Assign mesh to mesh filter meshFilter.sharedMesh = mesh; mesh.RecalculateBounds(); //Add a box collider component plane.AddComponent(typeof(BoxCollider)); } //------------------------------------------------ }
using XPT.Games.Generic.Constants; using XPT.Games.Generic.Maps; using XPT.Games.Twinion.Entities; namespace XPT.Games.Twinion.Maps { class TwMap23 : TwMap { public override int MapIndex => 23; public override int MapID => 0x0A01; protected override int RandomEncounterChance => 12; protected override int RandomEncounterExtraCount => 2; private const int MYTHW = 1; private const int ISLANDW = 2; private const int LEGENDW = 3; private const int EREBUSW = 4; private const int ABYSSW = 5; private const int WIZARDW = 6; private const int GUILDW = 7; private const int ASPW = 8; private const int MAGMAW = 9; private const int PALACEW = 10; private const int VOLCANOW = 11; private const int LONGBOWW = 12; private const int HARMONYW = 13; private const int TWINIONW = 14; private const int CHAOTICW = 15; private const int ELEMENTALW = 16; private const int SWITCH30 = 17; private const int SWITCH31 = 18; private const int SWITCH32 = 19; private const int SWITCH33 = 20; private const int SWITCH34 = 21; private const int SWITCH35 = 22; private const int SWITCH36 = 23; private const int SWITCH37 = 24; private const int CASETRAP = 25; private const int MIXEDONE = 26; private const int ROGUES = 27; private const int FOTEREBUS = 28; private const int SEENWRAITH = 29; private const int SPRUNGTRAP = 1; protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); SetWallItem(player, type, doMsgs, PORTAL, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { int picture = 0; int flagname = 0; int nextflag = 0; int tile = 0; tile = GetTile(player, type, doMsgs); switch (tile) { case 74: picture = HUMANBARBARIAN; flagname = TwIndexes.LEARNEDGREMLIN; nextflag = TwIndexes.LEARNEDHUMAN; ShowText(player, type, doMsgs, "'Babble is surely what is to be had if you take the words at face value."); ShowText(player, type, doMsgs, "You now know the Common tongue.'"); break; case 75: picture = ORCRANGER; flagname = TwIndexes.LEARNEDGNOME; nextflag = TwIndexes.LEARNEDORC; ShowText(player, type, doMsgs, "'The letters are the keys; the switches set the words; you must spell inside the words."); ShowText(player, type, doMsgs, "You now know Orc.'"); break; case 90: picture = ELFBARBARIAN; flagname = TwIndexes.LEARNEDHUMAN; nextflag = TwIndexes.LEARNEDELF; ShowText(player, type, doMsgs, "'This mountain of lava sets one stage; the other has befriended thee."); ShowText(player, type, doMsgs, "You are now fluent with the Elven tongue.'"); break; case 91: picture = TROLLKNIGHT; flagname = TwIndexes.LEARNEDORC; nextflag = TwIndexes.LEARNEDTROLL; ShowText(player, type, doMsgs, "'Ignore the last till second; see the second first."); ShowText(player, type, doMsgs, "You are now the Troll language incarnate.'"); break; case 106: picture = DWARFWIZARD; flagname = TwIndexes.LEARNEDELF; nextflag = TwIndexes.LEARNEDDWARF; ShowText(player, type, doMsgs, "'With hallowed halls the dead king lies, his offspring now rules the mount."); ShowText(player, type, doMsgs, "You now know Dwarf.'"); break; case 107: picture = HALFLINGKNIGHT; flagname = TwIndexes.LEARNEDTROLL; nextflag = TwIndexes.LEARNEDHALF; ShowText(player, type, doMsgs, "'As the last, let the good Queen shine; in a second the lava spouts."); ShowText(player, type, doMsgs, "You are now able to mumble Halfling.'"); break; case 122: picture = GNOMEBARBARIAN; flagname = TwIndexes.LEARNEDDWARF; nextflag = TwIndexes.LEARNEDGNOME; ShowText(player, type, doMsgs, "'Read it friend, two names are there if only you can see the clues."); ShowText(player, type, doMsgs, "You now know Gnome.'"); break; case 123: picture = GREMLINTHIEF; flagname = TwIndexes.LEARNEDHALF; nextflag = TwIndexes.LEARNEDGREMLIN; ShowText(player, type, doMsgs, "'The King is dead; long live the Queen!"); ShowText(player, type, doMsgs, "You now speak Gremlin - but only when you must.'"); break; } ShowPortrait(player, type, doMsgs, picture); if (GetFlag(player, type, doMsgs, FlagTypeDungeon, flagname) == 1) { if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, nextflag) == 0)) { SetFlag(player, type, doMsgs, FlagTypeDungeon, nextflag, 1); } SetFlag(player, type, doMsgs, FlagTypeDungeon, flagname, 2); } } else { ShowText(player, type, doMsgs, "You must enter the room alone."); TeleportParty(player, type, doMsgs, 10, 1, 120, Direction.West); } } protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 10, 1, 136, Direction.East); } protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Enter now the legacy of babel's nexus."); SetFlag(player, type, doMsgs, FlagTypeParty, FOTEREBUS, 1); } protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Back to the upper level."); TeleportParty(player, type, doMsgs, 9, 2, 120, Direction.West); } protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) { int picture = 0; int flagname = 0; int nextflag = 0; int tally = 0; tally = GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDHUMAN) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDDWARF) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDGNOME) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDGREMLIN) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDELF) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDTROLL) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDORC) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDHALF); switch (GetTile(player, type, doMsgs)) { case 83: picture = HUMANBARBARIAN; flagname = TwIndexes.LEARNEDHUMAN; nextflag = TwIndexes.LEARNEDELF; ShowText(player, type, doMsgs, "A Human is here."); break; case 0: picture = ORCRANGER; flagname = TwIndexes.LEARNEDORC; nextflag = TwIndexes.LEARNEDTROLL; ShowText(player, type, doMsgs, "An Orc is here."); break; case 81: picture = TROLLKNIGHT; flagname = TwIndexes.LEARNEDTROLL; nextflag = TwIndexes.LEARNEDHALF; ShowText(player, type, doMsgs, "A Troll is here."); break; case 160: picture = ELFBARBARIAN; flagname = TwIndexes.LEARNEDELF; nextflag = TwIndexes.LEARNEDDWARF; ShowText(player, type, doMsgs, "An Elf is here."); break; case 133: picture = HALFLINGKNIGHT; flagname = TwIndexes.LEARNEDHALF; nextflag = TwIndexes.LEARNEDGREMLIN; ShowText(player, type, doMsgs, "A Halfling is here."); break; case 50: picture = GREMLINTHIEF; flagname = TwIndexes.LEARNEDGREMLIN; nextflag = TwIndexes.LEARNEDHUMAN; ShowText(player, type, doMsgs, "A Gremlin is here."); break; case 147: picture = DWARFWIZARD; flagname = TwIndexes.LEARNEDDWARF; nextflag = TwIndexes.LEARNEDGNOME; ShowText(player, type, doMsgs, "A Dwarf Wizard is here."); break; case 96: picture = GNOMEBARBARIAN; flagname = TwIndexes.LEARNEDGNOME; nextflag = TwIndexes.LEARNEDORC; ShowText(player, type, doMsgs, "A Gnome is here."); break; } ShowPortrait(player, type, doMsgs, picture); if (tally == 16) { ShowText(player, type, doMsgs, "'You know all that you need. Go to the northeast room. Find your fate and unlock the gate.'"); } else if (IsFlagOn(player, type, doMsgs, FlagTypeDungeon, flagname)) { if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, nextflag) == 0)) { RaceText(player, type, doMsgs); ShowText(player, type, doMsgs, "lies the teleport that will take you to the next scholar. Go, it will now be unlocked.'"); } else { ShowText(player, type, doMsgs, "'I can do nothing more for you. Learn all of the languages; then read the plaques in the northeast.'"); } } else { switch (GetRace(player, type, doMsgs)) { case HUMAN: ShowText(player, type, doMsgs, "nemo me impune lacessit"); break; case ELF: ShowText(player, type, doMsgs, "fortuna favet fortibus"); break; case DWARF: ShowText(player, type, doMsgs, "vox populi, vox Dei"); break; case TROLL: ShowText(player, type, doMsgs, "vox et praeterea nihil"); break; case GNOME: ShowText(player, type, doMsgs, "quem Deus vult perdere, prius dementat"); break; case HALFLING: ShowText(player, type, doMsgs, "lasciate ogni speranza"); break; case ORC: ShowText(player, type, doMsgs, "finis coronat opus"); break; case GREMLIN: ShowText(player, type, doMsgs, "flat justitia, ruat coelum"); break; } } } private void RaceText(TwPlayerServer player, MapEventType type, bool doMsgs) { switch (GetTile(player, type, doMsgs)) { case 83: ShowText(player, type, doMsgs, "'To the southeast "); break; case 0: ShowText(player, type, doMsgs, "'Go to the northeast "); break; case 81: ShowText(player, type, doMsgs, "'Somewhere in the center "); break; case 160: ShowText(player, type, doMsgs, "'Now, just south of the scholar's rooms "); break; case 133: ShowText(player, type, doMsgs, "'One south of where we are "); break; case 50: ShowText(player, type, doMsgs, "'At the southern edge "); break; case 147: ShowText(player, type, doMsgs, "'In the northwest "); break; case 96: ShowText(player, type, doMsgs, "'In the east "); break; } } protected override void FnEvent15(TwPlayerServer player, MapEventType type, bool doMsgs) { int flagname = 0; Direction compass1 = 0; Direction compass2 = 0; int totile = 0; int tile = 0; tile = GetTile(player, type, doMsgs); switch (tile) { case 238: flagname = TwIndexes.LEARNEDHUMAN; compass1 = Direction.West; compass2 = Direction.West; totile = 90; ShowText(player, type, doMsgs, "HUMAN"); break; case 250: flagname = TwIndexes.LEARNEDGREMLIN; compass1 = Direction.South; compass2 = Direction.West; totile = 74; ShowText(player, type, doMsgs, "GREMLIN"); break; case 149: flagname = TwIndexes.LEARNEDHALF; compass1 = Direction.East; compass2 = Direction.East; totile = 123; ShowText(player, type, doMsgs, "HALFLING"); break; case 53: flagname = TwIndexes.LEARNEDDWARF; compass1 = Direction.West; compass2 = Direction.West; totile = 122; ShowText(player, type, doMsgs, "DWARF"); break; case 119: flagname = TwIndexes.LEARNEDTROLL; compass1 = Direction.South; compass2 = Direction.East; totile = 107; ShowText(player, type, doMsgs, "TROLL"); break; case 27: flagname = TwIndexes.LEARNEDORC; compass1 = Direction.North; compass2 = Direction.East; totile = 91; ShowText(player, type, doMsgs, "ORC"); break; case 93: flagname = TwIndexes.LEARNEDGNOME; compass1 = Direction.North; compass2 = Direction.East; totile = 75; ShowText(player, type, doMsgs, "GNOME"); break; case 139: flagname = TwIndexes.LEARNEDELF; compass1 = Direction.South; compass2 = Direction.West; totile = 106; ShowText(player, type, doMsgs, "ELF"); break; } if (GetFlag(player, type, doMsgs, FlagTypeDungeon, flagname) == 1) { SetWallItem(player, type, doMsgs, GATEWAY, GetTile(player, type, doMsgs), compass1); ShowText(player, type, doMsgs, "A gateway is here."); TeleportParty(player, type, doMsgs, 10, 1, totile, compass2); } else { ShowText(player, type, doMsgs, "This portal will lead to the name marked upon it. Return once you are told by those that babble in the west."); ShowText(player, type, doMsgs, "At present, it will only take you to the heart of this maze."); TeleportParty(player, type, doMsgs, 10, 1, 88, Direction.North); } } protected override void FnEvent1D(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ENDGAMETELE) == 1) { if (GetPartyCount(player, type, doMsgs) == 1) { ShowText(player, type, doMsgs, "This wall glows with power, beckoning you to enter."); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); TeleportParty(player, type, doMsgs, 10, 1, 22, Direction.North); } else { ShowText(player, type, doMsgs, "Alone! You must use this gateway alone."); TeleportParty(player, type, doMsgs, 10, 1, 184, Direction.East); } } } protected override void FnEvent1E(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDHUMAN) == 2) { int switchA = 0; int valueA = 0; int valueB = 0; switchA = GetFlag(player, type, doMsgs, FlagTypeParty, SWITCH30); switch (switchA) { case 1: ShowText(player, type, doMsgs, "EREBUS"); valueA = 1; valueB = 0; switchA = 2; break; case 2: ShowText(player, type, doMsgs, "MAGMA"); valueA = 0; valueB = 1; switchA = 3; break; default: OffText(player, type, doMsgs); valueA = 0; valueB = 0; switchA = 1; break; } SetFlag(player, type, doMsgs, FlagTypeParty, EREBUSW, valueA); SetFlag(player, type, doMsgs, FlagTypeParty, MAGMAW, valueB); SetFlag(player, type, doMsgs, FlagTypeParty, SWITCH30, switchA); } else { ShowText(player, type, doMsgs, "sculpsit"); } } protected override void FnEvent1F(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDHALF) == 2) { int switchA = 0; int valueA = 0; int valueB = 0; switchA = GetFlag(player, type, doMsgs, FlagTypeParty, SWITCH31); switch (switchA) { case 1: ShowText(player, type, doMsgs, "ASP"); valueA = 1; valueB = 0; switchA++; break; case 2: ShowText(player, type, doMsgs, "LONGBOW"); valueA = 0; valueB = 1; switchA++; break; default: OffText(player, type, doMsgs); valueA = 0; valueB = 0; switchA = 1; break; } SetFlag(player, type, doMsgs, FlagTypeParty, ASPW, valueA); SetFlag(player, type, doMsgs, FlagTypeParty, LONGBOWW, valueB); SetFlag(player, type, doMsgs, FlagTypeParty, SWITCH31, switchA); } else { ShowText(player, type, doMsgs, "tant mieux"); } } protected override void FnEvent20(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDDWARF) == 2) { int switchA = 0; int valueA = 0; int valueB = 0; switchA = GetFlag(player, type, doMsgs, FlagTypeParty, SWITCH32); switch (switchA) { case 1: ShowText(player, type, doMsgs, "ELEMENTAL"); valueA = 1; valueB = 0; switchA++; break; case 2: ShowText(player, type, doMsgs, "ISLAND"); valueA = 0; valueB = 1; switchA++; break; default: OffText(player, type, doMsgs); valueA = 0; valueB = 0; switchA = 1; break; } SetFlag(player, type, doMsgs, FlagTypeParty, ELEMENTALW, valueA); SetFlag(player, type, doMsgs, FlagTypeParty, ISLANDW, valueB); SetFlag(player, type, doMsgs, FlagTypeParty, SWITCH32, switchA); } else { ShowText(player, type, doMsgs, "obiit"); } } protected override void FnEvent21(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDGNOME) == 2) { int switchA = 0; int valueA = 0; int valueB = 0; switchA = GetFlag(player, type, doMsgs, FlagTypeParty, SWITCH33); switch (switchA) { case 1: ShowText(player, type, doMsgs, "HARMONY"); valueA = 1; valueB = 0; switchA++; break; case 2: ShowText(player, type, doMsgs, "GUILD"); valueA = 0; valueB = 1; switchA++; break; default: OffText(player, type, doMsgs); valueA = 0; valueB = 0; switchA = 1; break; } SetFlag(player, type, doMsgs, FlagTypeParty, HARMONYW, valueA); SetFlag(player, type, doMsgs, FlagTypeParty, GUILDW, valueB); SetFlag(player, type, doMsgs, FlagTypeParty, SWITCH33, switchA); } else { ShowText(player, type, doMsgs, "peccavi"); } } protected override void FnEvent22(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDGREMLIN) == 2) { int switchA = 0; int valueA = 0; int valueB = 0; switchA = GetFlag(player, type, doMsgs, FlagTypeParty, SWITCH34); switch (switchA) { case 1: ShowText(player, type, doMsgs, "CHAOTIC"); valueA = 1; valueB = 0; switchA++; break; case 2: ShowText(player, type, doMsgs, "MYTH"); valueA = 0; valueB = 1; switchA++; break; default: OffText(player, type, doMsgs); valueA = 0; valueB = 0; switchA = 1; break; } SetFlag(player, type, doMsgs, FlagTypeParty, CHAOTICW, valueA); SetFlag(player, type, doMsgs, FlagTypeParty, MYTHW, valueB); SetFlag(player, type, doMsgs, FlagTypeParty, SWITCH34, switchA); } else { ShowText(player, type, doMsgs, "l'onconnu"); } } protected override void FnEvent23(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDORC) == 2) { int switchA = 0; int valueA = 0; int valueB = 0; switchA = GetFlag(player, type, doMsgs, FlagTypeParty, SWITCH35); switch (switchA) { case 1: ShowText(player, type, doMsgs, "VOLCANO"); valueA = 1; valueB = 0; switchA++; break; case 2: ShowText(player, type, doMsgs, "ABYSS"); valueA = 0; valueB = 1; switchA++; break; default: OffText(player, type, doMsgs); valueA = 0; valueB = 0; switchA = 1; break; } SetFlag(player, type, doMsgs, FlagTypeParty, VOLCANOW, valueA); SetFlag(player, type, doMsgs, FlagTypeParty, ABYSSW, valueB); SetFlag(player, type, doMsgs, FlagTypeParty, SWITCH35, switchA); } else { ShowText(player, type, doMsgs, "fiat lux"); } } protected override void FnEvent24(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDTROLL) == 2) { int switchA = 0; int valueA = 0; int valueB = 0; switchA = GetFlag(player, type, doMsgs, FlagTypeParty, SWITCH36); switch (switchA) { case 1: ShowText(player, type, doMsgs, "TWINION"); valueA = 1; valueB = 0; switchA++; break; case 2: ShowText(player, type, doMsgs, "LEGEND"); valueA = 0; valueB = 1; switchA++; break; default: OffText(player, type, doMsgs); valueA = 0; valueB = 0; switchA = 1; break; } SetFlag(player, type, doMsgs, FlagTypeParty, TWINIONW, valueA); SetFlag(player, type, doMsgs, FlagTypeParty, LEGENDW, valueB); SetFlag(player, type, doMsgs, FlagTypeParty, SWITCH36, switchA); } else { ShowText(player, type, doMsgs, "a priori"); } } protected override void FnEvent25(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDELF) == 2) { int switchA = 0; int valueA = 0; int valueB = 0; switchA = GetFlag(player, type, doMsgs, FlagTypeParty, SWITCH37); switch (switchA) { case 1: ShowText(player, type, doMsgs, "WIZARD"); valueA = 1; valueB = 0; switchA++; break; case 2: ShowText(player, type, doMsgs, "PALACE"); valueA = 0; valueB = 1; switchA++; break; default: OffText(player, type, doMsgs); valueA = 0; valueB = 0; switchA = 1; break; } SetFlag(player, type, doMsgs, FlagTypeParty, WIZARDW, valueA); SetFlag(player, type, doMsgs, FlagTypeParty, PALACEW, valueB); SetFlag(player, type, doMsgs, FlagTypeParty, SWITCH37, switchA); } else { ShowText(player, type, doMsgs, "ad finem"); } } private void OffText(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "-OFF-"); } protected override void FnEvent26(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPELLEDBOTH) == 0)) { int i = 0; int word = 0; int valueA = 0; int valueB = 0; word = GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPELLINGWORD); if (word == 0) { word = 1; } switch (word) { case 2: valueB = GetFlag(player, type, doMsgs, FlagTypeParty, ELEMENTALW) + GetFlag(player, type, doMsgs, FlagTypeParty, CHAOTICW) + GetFlag(player, type, doMsgs, FlagTypeParty, MAGMAW) + GetFlag(player, type, doMsgs, FlagTypeParty, PALACEW) + GetFlag(player, type, doMsgs, FlagTypeParty, VOLCANOW) + GetFlag(player, type, doMsgs, FlagTypeParty, LONGBOWW) + GetFlag(player, type, doMsgs, FlagTypeParty, HARMONYW) + GetFlag(player, type, doMsgs, FlagTypeParty, TWINIONW); if (valueB == 6) { ShowText(player, type, doMsgs, "Your experience increases along with your gold and your strength!"); ModifyGold(player, type, doMsgs, 250000); ModAttribute(player, type, doMsgs, STRENGTH, 3); ModifyExperience(player, type, doMsgs, 750000); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPELLINGWORD, 3); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPELLEDBOTH, 1); SetFloorItem(player, type, doMsgs, PIT, 11); for (i = 39; i <= 46; i++) { SetFlag(player, type, doMsgs, FlagTypeDungeon, i, 4); } for (i = 23; i <= 31; i++) { ClearWallItem(player, type, doMsgs, i, Direction.South); } SpelledEm(player, type, doMsgs); } else { NadaQue(player, type, doMsgs); } break; case 1: valueA = GetFlag(player, type, doMsgs, FlagTypeParty, MYTHW) + GetFlag(player, type, doMsgs, FlagTypeParty, ISLANDW) + GetFlag(player, type, doMsgs, FlagTypeParty, LEGENDW) + GetFlag(player, type, doMsgs, FlagTypeParty, EREBUSW) + GetFlag(player, type, doMsgs, FlagTypeParty, ABYSSW) + GetFlag(player, type, doMsgs, FlagTypeParty, WIZARDW) + GetFlag(player, type, doMsgs, FlagTypeParty, GUILDW) + GetFlag(player, type, doMsgs, FlagTypeParty, ASPW); if (valueA == 8) { ShowText(player, type, doMsgs, "You've set the first word. On to the next. Here's a taste of experience, gold and a little initiative!"); ModAttribute(player, type, doMsgs, INITIATIVE, 3); ModifyGold(player, type, doMsgs, 175000); ModifyExperience(player, type, doMsgs, 700000); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPELLINGWORD, 2); } else { NadaQue(player, type, doMsgs); } break; } } else { SpelledEm(player, type, doMsgs); } } private void SpelledEm(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "You've spelled the words. Now through the exit and onward to your Fate!"); } private void NadaQue(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Nothing happens."); } protected override void FnEvent27(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPELLEDBOTH) == 1) { if (GetPartyCount(player, type, doMsgs) == 1) { ShowText(player, type, doMsgs, "The magical winds sweep you up and pull you down through the opening into Concordia."); TeleportParty(player, type, doMsgs, 10, 2, 225, Direction.East); } else { ShowText(player, type, doMsgs, "You may enter only if alone!"); SetFloorItem(player, type, doMsgs, NO_OBJECT, 11); } } else { SetFloorItem(player, type, doMsgs, NO_OBJECT, 11); } } protected override void FnEvent28(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.KNOWSALL) == 0)) { if (GetPartyCount(player, type, doMsgs) != 1) { ShowText(player, type, doMsgs, "Only alone may you pass through."); TeleportParty(player, type, doMsgs, 10, 1, 6, Direction.East); } else if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPELLEDBOTH) == 1) { ShowText(player, type, doMsgs, "You have already solved this puzzle!"); ShowText(player, type, doMsgs, "Proceed to your exit."); SetFloorItem(player, type, doMsgs, PIT, 11); for (i = 23; i <= 31; i++) { ClearWallItem(player, type, doMsgs, i, Direction.South); } } else { int flagcount = 0; flagcount = GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDHUMAN) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDGNOME) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDHALF) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDTROLL) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDORC) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDGREMLIN) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDELF) + GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDDWARF); if ((flagcount == 16) || (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.KNOWSALL) == 1)) { if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.KNOWSALL) == 0)) { SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.KNOWSALL, 1); } ShowText(player, type, doMsgs, "You have proven your knowledge of the major languages. Now read the plaques and set the switches. Then you may proceed."); } else { ShowText(player, type, doMsgs, "You need to learn more about languages before you can tackle this puzzle."); } } } } protected override void FnEvent29(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetFlag(player, type, doMsgs, FlagTypeParty, SEENWRAITH) == 0)) { ShowPortrait(player, type, doMsgs, WRAITH); ShowText(player, type, doMsgs, "'Beware! Beware! The traps here are of fiendish conception! They change whence you step them again although they are the same tile! Beware!'"); SetFlag(player, type, doMsgs, FlagTypeParty, SEENWRAITH, 1); } } protected override void FnEvent2A(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; int pl = 0; if (GetPartyLevel(player, type, doMsgs, 35)) { pl = 1; } ShowText(player, type, doMsgs, "Night Elf berserkers scream wildly as they attack."); if (HasItem(player, type, doMsgs, BLACKBLADE)) { SetTreasure(player, type, doMsgs, ELIXIROFHEALTH, NIGHTELFHELM, 0, 0, 0, 1000); } else { SetTreasure(player, type, doMsgs, BLACKBLADE, 0, 0, 0, 0, 1500); } switch (pl) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 36); } for (i = 5; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 37); } break; default: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 36); } for (i = 5; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 37); } break; } } protected override void FnEvent2B(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetFlag(player, type, doMsgs, FlagTypeParty, FOTEREBUS) == 0)) { int i = 0; ShowText(player, type, doMsgs, "Two Erebus fiends hiss as you approach."); for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 40); } } } protected override void FnEvent2C(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "Hulking Kaalroths launch a fierce magical attack."); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 28); } break; case 2: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 28); } break; default: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 28); } for (i = 5; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 29); } break; } } protected override void FnEvent2D(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "'You've slain many of our friends. It is your time now!'"); for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 26); } } protected override void FnEvent2E(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; if (GetFlag(player, type, doMsgs, FlagTypeParty, MIXEDONE) == 2) { ShowText(player, type, doMsgs, "Wizards and their servants are tending the fallen Golems you killed!"); switch (GetPartyCount(player, type, doMsgs)) { case 1: AddEncounter(player, type, doMsgs, 1, 25); for (i = 5; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 30); } break; case 2: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 25); } for (i = 5; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 30); } break; default: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 25); } for (i = 5; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 30); } break; } } else if (GetFlag(player, type, doMsgs, FlagTypeParty, MIXEDONE) == 1) { ShowText(player, type, doMsgs, "Huge golems lumber forward to block your path."); for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 25); } } else { ShowText(player, type, doMsgs, "The floor here shows traces of recent activity by huge creatures."); SetFlag(player, type, doMsgs, FlagTypeParty, MIXEDONE, 1); } } protected override void FnEvent2F(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LEARNEDELF) == 1) { ShowText(player, type, doMsgs, "An eerie sense of magic surrounds you."); ShowText(player, type, doMsgs, "Something is different! You'd better check this area again."); } } protected override void FnEvent30(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "A horde of Golems stir to life as they sense your approach!"); for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 31); } } protected override void FnEvent31(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "Babbling rogues, driven mad from their quests, see you as their next prey."); switch (GetPartyCount(player, type, doMsgs)) { case 1: AddEncounter(player, type, doMsgs, 1, 32); AddEncounter(player, type, doMsgs, 2, 33); break; case 2: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 32); } for (i = 5; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 33); } break; default: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 32); } for (i = 5; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 33); } break; } } protected override void FnEvent32(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; if (GetFlag(player, type, doMsgs, FlagTypeParty, ROGUES) == 1) { ShowText(player, type, doMsgs, "'OUT! Keep out of our domain!'"); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 34); } break; case 2: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 34); } break; default: for (i = 1; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 34); } break; } } else { ShowPortrait(player, type, doMsgs, NIGHTELFWARRIOR); ShowText(player, type, doMsgs, "A Night Elf warrior holds his forces at the ready."); ShowText(player, type, doMsgs, "'Leave this place and do not return. Abandon your quest for our Dralkarians."); ShowText(player, type, doMsgs, "This shall be your only warning.'"); SetFlag(player, type, doMsgs, FlagTypeParty, ROGUES, 1); } } protected override void FnEvent33(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "More Night Elves have been called to defend their domain."); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 35); } break; case 2: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 35); } break; default: for (i = 1; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 35); } break; } } protected override void FnEvent34(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Babbling creatures begin feuding and draw you into their fray."); AddEncounter(player, type, doMsgs, 01, 37); AddEncounter(player, type, doMsgs, 02, 38); } protected override void FnEvent35(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "A slew of bats rush through this hallway."); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 39); } break; case 2: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 39); } break; default: for (i = 1; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 39); } break; } } protected override void FnEvent36(TwPlayerServer player, MapEventType type, bool doMsgs) { int trap = 0; trap = GetFlag(player, type, doMsgs, FlagTypeParty, CASETRAP); if ((GetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP) == 0)) { switch (trap) { case 1: DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 6); SetDebuff(player, type, doMsgs, POISON, 15, 100); DisableSpells(player, type, doMsgs); ShowText(player, type, doMsgs, "You spring a trap laced with poisoned darts."); trap++; break; case 2: DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 5); ShowText(player, type, doMsgs, "You trigger some mage's trap. A cloud of acid surrounds you!!"); ModifyGold(player, type, doMsgs, - 2000); trap++; break; case 3: DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 4); ShowText(player, type, doMsgs, "Fireballs slam into you as you set off another fiendish trap."); trap++; break; case 4: SetDebuff(player, type, doMsgs, POISON, 15, 200); ModifyMana(player, type, doMsgs, - 500); while (HasItem(player, type, doMsgs, CURATIVEELIXIR)) RemoveItem(player, type, doMsgs, CURATIVEELIXIR); ShowText(player, type, doMsgs, "You clumsily set off a gas trap."); trap++; break; default: DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 5); DisableHealing(player, type, doMsgs); trap = 1; DisableSpells(player, type, doMsgs); ShowText(player, type, doMsgs, "A fierce whirlwind strikes you from some unseen sorcerer's hand!"); break; } SetFlag(player, type, doMsgs, FlagTypeParty, CASETRAP, trap); SetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP, 1); SetFlag(player, type, doMsgs, FlagTypeParty, FOTEREBUS, 0); } } protected override void FnEvent37(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "Well-trained Night Elves guard these corridors."); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 34); } break; case 2: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 34); } for (i = 5; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 34); } break; default: for (i = 1; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 34); } break; } } protected override void FnEvent38(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, DWARFKNIGHT); ShowText(player, type, doMsgs, "An ancient Knight whispers, 'The leader must be removed to see the summit. And even though the spells of royalty be at the end, they shall be the first.'"); } protected override void FnEvent39(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, ORCRANGER); ShowText(player, type, doMsgs, "'The nine switches are used to open the way down to the next area. You must learn which switches to turn on."); ShowText(player, type, doMsgs, "Having the nine switches set in unison will unlock the way for you.'"); } protected override void FnEvent3A(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, FOUNTAIN); ShowText(player, type, doMsgs, "The cool waters satisfy and enrich you."); ModifyHealth(player, type, doMsgs, GetHealthMax(player, type, doMsgs)); ModifyMana(player, type, doMsgs, 2500); } protected override void FnEvent3B(TwPlayerServer player, MapEventType type, bool doMsgs) { int flag = 0; int racecheck = 0; racecheck = GetRace(player, type, doMsgs); switch (racecheck) { case HUMAN: flag = TwIndexes.LEARNEDHUMAN; break; case ELF: flag = TwIndexes.LEARNEDELF; break; case DWARF: flag = TwIndexes.LEARNEDDWARF; break; case GNOME: flag = TwIndexes.LEARNEDGNOME; break; case ORC: flag = TwIndexes.LEARNEDORC; break; case TROLL: flag = TwIndexes.LEARNEDTROLL; break; case HALFLING: flag = TwIndexes.LEARNEDHALF; break; case GREMLIN: flag = TwIndexes.LEARNEDGREMLIN; break; } if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, flag) == 0)) { SetFlag(player, type, doMsgs, FlagTypeDungeon, flag, 1); } if (HasItem(player, type, doMsgs, JESTERSCAP) && (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.CHOR_NPC_KILLED) == 0)) { ShowText(player, type, doMsgs, "A maniacal fiend appears; removes an item you stole from him; and kills you outright."); while (HasItem(player, type, doMsgs, JESTERSCAP)) RemoveItem(player, type, doMsgs, JESTERSCAP); ModifyGold(player, type, doMsgs, - 10000); DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs)); } } protected override void FnEvent3C(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The door glows with a magical force."); if (GetPartyCount(player, type, doMsgs) == 1) { ShowText(player, type, doMsgs, "You may proceed alone."); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } else { ShowText(player, type, doMsgs, "You must enter here one at a time."); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } } }
// CRC32.cs // ------------------------------------------------------------------ // // Copyright (c) 2011 Dino Chiesa. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // Last Saved: <2011-August-02 18:25:54> // // ------------------------------------------------------------------ // // This module defines the CRC32 class, which can do the CRC32 algorithm, using // arbitrary starting polynomials, and bit reversal. The bit reversal is what // distinguishes this CRC-32 used in BZip2 from the CRC-32 that is used in PKZIP // files, or GZIP files. This class does both. // // ------------------------------------------------------------------ using System; using System.IO; using System.Runtime.InteropServices; using Interop = System.Runtime.InteropServices; namespace Ore.Compiler.Zlib { /// <summary> /// Computes a CRC-32. The CRC-32 algorithm is parameterized - you /// can set the polynomial and enable or disable bit /// reversal. This can be used for GZIP, BZip2, or ZIP. /// </summary> /// <remarks> /// This type is used internally by DotNetZip; it is generally not used /// directly by applications wishing to create, read, or manipulate zip /// archive files. /// </remarks> [Guid("ebc25cf6-9120-4283-b972-0e5520d0000C")] [ComVisible(true)] #if !NETCF [ClassInterface(Interop.ClassInterfaceType.AutoDispatch)] #endif public class Crc32 { private const int BufferSize = 8192; // private member vars private readonly UInt32 _dwPolynomial; private readonly bool _reverseBits; private UInt32 _register = 0xFFFFFFFFU; private UInt32[] _crc32Table; /// <summary> /// Create an instance of the CRC32 class using the default settings: no /// bit reversal, and a polynomial of 0xEDB88320. /// </summary> public Crc32() : this(false) { } /// <summary> /// Create an instance of the CRC32 class, specifying whether to reverse /// data bits or not. /// </summary> /// <param name='reverseBits'> /// specify true if the instance should reverse data bits. /// </param> /// <remarks> /// <para> /// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you /// want a CRC32 with compatibility with BZip2, you should pass true /// here. In the CRC-32 used by GZIP and PKZIP, the bits are not /// reversed; Therefore if you want a CRC32 with compatibility with /// those, you should pass false. /// </para> /// </remarks> public Crc32(bool reverseBits) : this(unchecked((int) 0xEDB88320), reverseBits) { } /// <summary> /// Create an instance of the CRC32 class, specifying the polynomial and /// whether to reverse data bits or not. /// </summary> /// <param name='polynomial'> /// The polynomial to use for the CRC, expressed in the reversed (LSB) /// format: the highest ordered bit in the polynomial value is the /// coefficient of the 0th power; the second-highest order bit is the /// coefficient of the 1 power, and so on. Expressed this way, the /// polynomial for the CRC-32C used in IEEE 802.3, is 0xEDB88320. /// </param> /// <param name='reverseBits'> /// specify true if the instance should reverse data bits. /// </param> /// <remarks> /// <para> /// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you /// want a CRC32 with compatibility with BZip2, you should pass true /// here for the <c>reverseBits</c> parameter. In the CRC-32 used by /// GZIP and PKZIP, the bits are not reversed; Therefore if you want a /// CRC32 with compatibility with those, you should pass false for the /// <c>reverseBits</c> parameter. /// </para> /// </remarks> public Crc32(int polynomial, bool reverseBits) { this._reverseBits = reverseBits; _dwPolynomial = (uint) polynomial; GenerateLookupTable(); } /// <summary> /// Indicates the total number of bytes applied to the CRC. /// </summary> public Int64 TotalBytesRead { get; private set; } /// <summary> /// Indicates the current CRC for all blocks slurped in. /// </summary> public Int32 Crc32Result => unchecked((Int32) (~_register)); /// <summary> /// Returns the CRC32 for the specified stream. /// </summary> /// <param name="input">The stream over which to calculate the CRC32</param> /// <returns>the CRC32 calculation</returns> public Int32 GetCrc32(Stream input) { return GetCrc32AndCopy(input, null); } /// <summary> /// Returns the CRC32 for the specified stream, and writes the input into the /// output stream. /// </summary> /// <param name="input">The stream over which to calculate the CRC32</param> /// <param name="output">The stream into which to deflate the input</param> /// <returns>the CRC32 calculation</returns> public Int32 GetCrc32AndCopy(Stream input, Stream output) { if (input == null) throw new Exception("The input stream must not be null."); unchecked { var buffer = new byte[BufferSize]; var readSize = BufferSize; TotalBytesRead = 0; var count = input.Read(buffer, 0, readSize); if (output != null) output.Write(buffer, 0, count); TotalBytesRead += count; while (count > 0) { SlurpBlock(buffer, 0, count); count = input.Read(buffer, 0, readSize); if (output != null) output.Write(buffer, 0, count); TotalBytesRead += count; } return (Int32) (~_register); } } /// <summary> /// Get the CRC32 for the given (word,byte) combo. This is a /// computation defined by PKzip for PKZIP 2.0 (weak) encryption. /// </summary> /// <param name="w">The word to start with.</param> /// <param name="b">The byte to combine it with.</param> /// <returns>The CRC-ized result.</returns> public Int32 ComputeCrc32(Int32 w, byte b) { return _InternalComputeCrc32((UInt32) w, b); } internal Int32 _InternalComputeCrc32(UInt32 w, byte b) { return (Int32) (_crc32Table[(w ^ b) & 0xFF] ^ (w >> 8)); } /// <summary> /// Update the value for the running CRC32 using the given block of bytes. /// This is useful when using the CRC32() class in a Stream. /// </summary> /// <param name="block">block of bytes to slurp</param> /// <param name="offset">starting point in the block</param> /// <param name="count">how many bytes within the block to slurp</param> public void SlurpBlock(byte[] block, int offset, int count) { if (block == null) throw new Exception("The data buffer must not be null."); // bzip algorithm for (var i = 0; i < count; i++) { var x = offset + i; var b = block[x]; if (_reverseBits) { var temp = (_register >> 24) ^ b; _register = (_register << 8) ^ _crc32Table[temp]; } else { var temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ _crc32Table[temp]; } } TotalBytesRead += count; } /// <summary> /// Process one byte in the CRC. /// </summary> /// <param name="b">the byte to include into the CRC . </param> public void UpdateCRC(byte b) { if (_reverseBits) { var temp = (_register >> 24) ^ b; _register = (_register << 8) ^ _crc32Table[temp]; } else { var temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ _crc32Table[temp]; } } /// <summary> /// Process a run of N identical bytes into the CRC. /// </summary> /// <remarks> /// <para> /// This method serves as an optimization for updating the CRC when a /// run of identical bytes is found. Rather than passing in a buffer of /// length n, containing all identical bytes b, this method accepts the /// byte value and the length of the (virtual) buffer - the length of /// the run. /// </para> /// </remarks> /// <param name="b">the byte to include into the CRC. </param> /// <param name="n">the number of times that byte should be repeated. </param> public void UpdateCRC(byte b, int n) { while (n-- > 0) { if (_reverseBits) { var temp = (_register >> 24) ^ b; _register = (_register << 8) ^ _crc32Table[(temp >= 0) ? temp : (temp + 256)]; } else { var temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ _crc32Table[(temp >= 0) ? temp : (temp + 256)]; } } } private static uint ReverseBits(uint data) { unchecked { var ret = data; ret = (ret & 0x55555555) << 1 | (ret >> 1) & 0x55555555; ret = (ret & 0x33333333) << 2 | (ret >> 2) & 0x33333333; ret = (ret & 0x0F0F0F0F) << 4 | (ret >> 4) & 0x0F0F0F0F; ret = (ret << 24) | ((ret & 0xFF00) << 8) | ((ret >> 8) & 0xFF00) | (ret >> 24); return ret; } } private static byte ReverseBits(byte data) { unchecked { var u = (uint) data*0x00020202; uint m = 0x01044010; var s = u & m; var t = (u << 2) & (m << 1); return (byte) ((0x01001001*(s + t)) >> 24); } } private void GenerateLookupTable() { _crc32Table = new UInt32[256]; unchecked { UInt32 dwCrc; byte i = 0; do { dwCrc = i; for (byte j = 8; j > 0; j--) { if ((dwCrc & 1) == 1) { dwCrc = (dwCrc >> 1) ^ _dwPolynomial; } else { dwCrc >>= 1; } } if (_reverseBits) { _crc32Table[ReverseBits(i)] = ReverseBits(dwCrc); } else { _crc32Table[i] = dwCrc; } i++; } while (i != 0); } #if VERBOSE Console.WriteLine(); Console.WriteLine("private static readonly UInt32[] crc32Table = {"); for (int i = 0; i < crc32Table.Length; i+=4) { Console.Write(" "); for (int j=0; j < 4; j++) { Console.Write(" 0x{0:X8}U,", crc32Table[i+j]); } Console.WriteLine(); } Console.WriteLine("};"); Console.WriteLine(); #endif } private uint gf2_matrix_times(uint[] matrix, uint vec) { uint sum = 0; var i = 0; while (vec != 0) { if ((vec & 0x01) == 0x01) sum ^= matrix[i]; vec >>= 1; i++; } return sum; } private void gf2_matrix_square(uint[] square, uint[] mat) { for (var i = 0; i < 32; i++) square[i] = gf2_matrix_times(mat, mat[i]); } /// <summary> /// Combines the given CRC32 value with the current running total. /// </summary> /// <remarks> /// This is useful when using a divide-and-conquer approach to /// calculating a CRC. Multiple threads can each calculate a /// CRC32 on a segment of the data, and then combine the /// individual CRC32 values at the end. /// </remarks> /// <param name="crc">the crc value to be combined with this one</param> /// <param name="length">the length of data the CRC value was calculated on</param> public void Combine(int crc, int length) { var even = new uint[32]; // even-power-of-two zeros operator var odd = new uint[32]; // odd-power-of-two zeros operator if (length == 0) return; var crc1 = ~_register; var crc2 = (uint) crc; // put operator for one zero bit in odd odd[0] = _dwPolynomial; // the CRC-32 polynomial uint row = 1; for (var i = 1; i < 32; i++) { odd[i] = row; row <<= 1; } // put operator for two zero bits in even gf2_matrix_square(even, odd); // put operator for four zero bits in odd gf2_matrix_square(odd, even); var len2 = (uint) length; // apply len2 zeros to crc1 (first square will put the operator for one // zero byte, eight zero bits, in even) do { // apply zeros operator for this bit of len2 gf2_matrix_square(even, odd); if ((len2 & 1) == 1) crc1 = gf2_matrix_times(even, crc1); len2 >>= 1; if (len2 == 0) break; // another iteration of the loop with odd and even swapped gf2_matrix_square(odd, even); if ((len2 & 1) == 1) crc1 = gf2_matrix_times(odd, crc1); len2 >>= 1; } while (len2 != 0); crc1 ^= crc2; _register = ~crc1; //return (int) crc1; } /// <summary> /// Reset the CRC-32 class - clear the CRC "remainder register." /// </summary> /// <remarks> /// <para> /// Use this when employing a single instance of this class to compute /// multiple, distinct CRCs on multiple, distinct data blocks. /// </para> /// </remarks> public void Reset() { _register = 0xFFFFFFFFU; } } /// <summary> /// A Stream that calculates a CRC32 (a checksum) on all bytes read, /// or on all bytes written. /// </summary> /// <remarks> /// <para> /// This class can be used to verify the CRC of a ZipEntry when /// reading from a stream, or to calculate a CRC when writing to a /// stream. The stream should be used to either read, or write, but /// not both. If you intermix reads and writes, the results are not /// defined. /// </para> /// <para> /// This class is intended primarily for use internally by the /// DotNetZip library. /// </para> /// </remarks> public class CrcCalculatorStream : Stream, IDisposable { private static readonly Int64 UnsetLengthLimit = -99; private readonly Crc32 _crc32; private readonly Int64 _lengthLimit = -99; internal Stream InnerStream; /// <summary> /// The default constructor. /// </summary> /// <remarks> /// <para> /// Instances returned from this constructor will leave the underlying /// stream open upon Close(). The stream uses the default CRC32 /// algorithm, which implies a polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> public CrcCalculatorStream(Stream stream) : this(true, UnsetLengthLimit, stream, null) { } /// <summary> /// The constructor allows the caller to specify how to handle the /// underlying stream at close. /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="leaveOpen"> /// true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise. /// </param> public CrcCalculatorStream(Stream stream, bool leaveOpen) : this(leaveOpen, UnsetLengthLimit, stream, null) { } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read. /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// <para> /// Instances returned from this constructor will leave the underlying /// stream open upon Close(). /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> public CrcCalculatorStream(Stream stream, Int64 length) : this(true, length, stream, null) { if (length < 0) throw new ArgumentException("length"); } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read, as well as whether to keep the underlying stream open upon /// Close(). /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> /// <param name="leaveOpen"> /// true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise. /// </param> public CrcCalculatorStream(Stream stream, Int64 length, bool leaveOpen) : this(leaveOpen, length, stream, null) { if (length < 0) throw new ArgumentException("length"); } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read, as well as whether to keep the underlying stream open upon /// Close(), and the CRC32 instance to use. /// </summary> /// <remarks> /// <para> /// The stream uses the specified CRC32 instance, which allows the /// application to specify how the CRC gets calculated. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> /// <param name="leaveOpen"> /// true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise. /// </param> /// <param name="crc32">the CRC32 instance to use to calculate the CRC32</param> public CrcCalculatorStream(Stream stream, Int64 length, bool leaveOpen, Crc32 crc32) : this(leaveOpen, length, stream, crc32) { if (length < 0) throw new ArgumentException("length"); } // This ctor is private - no validation is done here. This is to allow the use // of a (specific) negative value for the _lengthLimit, to indicate that there // is no length set. So we validate the length limit in those ctors that use an // explicit param, otherwise we don't validate, because it could be our special // value. private CrcCalculatorStream (bool leaveOpen, Int64 length, Stream stream, Crc32 crc32) { InnerStream = stream; _crc32 = crc32 ?? new Crc32(); _lengthLimit = length; LeaveOpen = leaveOpen; } /// <summary> /// Gets the total number of bytes run through the CRC32 calculator. /// </summary> /// <remarks> /// This is either the total number of bytes read, or the total number of /// bytes written, depending on the direction of this stream. /// </remarks> public Int64 TotalBytesSlurped => _crc32.TotalBytesRead; /// <summary> /// Provides the current CRC for all blocks slurped in. /// </summary> /// <remarks> /// <para> /// The running total of the CRC is kept as data is written or read /// through the stream. read this property after all reads or writes to /// get an accurate CRC for the entire stream. /// </para> /// </remarks> public Int32 Crc => _crc32.Crc32Result; /// <summary> /// Indicates whether the underlying stream will be left open when the /// <c>CrcCalculatorStream</c> is Closed. /// </summary> /// <remarks> /// <para> /// Set this at any point before calling <see cref="Close()" />. /// </para> /// </remarks> public bool LeaveOpen { get; set; } /// <summary> /// Indicates whether the stream supports reading. /// </summary> public override bool CanRead => InnerStream.CanRead; /// <summary> /// Indicates whether the stream supports seeking. /// </summary> /// <remarks> /// <para> /// Always returns false. /// </para> /// </remarks> public override bool CanSeek => false; /// <summary> /// Indicates whether the stream supports writing. /// </summary> public override bool CanWrite => InnerStream.CanWrite; /// <summary> /// Returns the length of the underlying stream. /// </summary> public override long Length { get { if (_lengthLimit == UnsetLengthLimit) return InnerStream.Length; return _lengthLimit; } } /// <summary> /// The getter for this property returns the total bytes read. /// If you use the setter, it will throw /// <see cref="NotSupportedException" />. /// </summary> public override long Position { get { return _crc32.TotalBytesRead; } set { throw new NotSupportedException(); } } void IDisposable.Dispose() { Close(); } /// <summary> /// Read from the stream /// </summary> /// <param name="buffer">the buffer to read</param> /// <param name="offset">the offset at which to start</param> /// <param name="count">the number of bytes to read</param> /// <returns>the number of bytes actually read</returns> public override int Read(byte[] buffer, int offset, int count) { var bytesToRead = count; // Need to limit the # of bytes returned, if the stream is intended to have // a definite length. This is especially useful when returning a stream for // the uncompressed data directly to the application. The app won't // necessarily read only the UncompressedSize number of bytes. For example // wrapping the stream returned from OpenReader() into a StreadReader() and // calling ReadToEnd() on it, We can "over-read" the zip data and get a // corrupt string. The length limits that, prevents that problem. if (_lengthLimit != UnsetLengthLimit) { if (_crc32.TotalBytesRead >= _lengthLimit) return 0; // EOF var bytesRemaining = _lengthLimit - _crc32.TotalBytesRead; if (bytesRemaining < count) bytesToRead = (int) bytesRemaining; } var n = InnerStream.Read(buffer, offset, bytesToRead); if (n > 0) _crc32.SlurpBlock(buffer, offset, n); return n; } /// <summary> /// Write to the stream. /// </summary> /// <param name="buffer">the buffer from which to write</param> /// <param name="offset">the offset at which to start writing</param> /// <param name="count">the number of bytes to write</param> public override void Write(byte[] buffer, int offset, int count) { if (count > 0) _crc32.SlurpBlock(buffer, offset, count); InnerStream.Write(buffer, offset, count); } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { InnerStream.Flush(); } /// <summary> /// Seeking is not supported on this stream. This method always throws /// <see cref="NotSupportedException" /> /// </summary> /// <param name="offset">N/A</param> /// <param name="origin">N/A</param> /// <returns>N/A</returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// This method always throws /// <see cref="NotSupportedException" /> /// </summary> /// <param name="value">N/A</param> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Closes the stream. /// </summary> public override void Close() { base.Close(); if (!LeaveOpen) InnerStream.Close(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using Xunit; namespace Microsoft.AspNetCore.Routing.DecisionTree { public class DecisionTreeBuilderTest { [Fact] public void BuildTree_Empty() { // Arrange var items = new List<Item>(); // Act var tree = DecisionTreeBuilder<Item>.GenerateTree(items, new ItemClassifier()); // Assert Assert.Empty(tree.Criteria); Assert.Empty(tree.Matches); } [Fact] public void BuildTree_TrivialMatch() { // Arrange var items = new List<Item>(); var item = new Item(); items.Add(item); // Act var tree = DecisionTreeBuilder<Item>.GenerateTree(items, new ItemClassifier()); // Assert Assert.Empty(tree.Criteria); Assert.Same(item, Assert.Single(tree.Matches)); } [Fact] public void BuildTree_WithMultipleCriteria() { // Arrange var items = new List<Item>(); var item = new Item(); item.Criteria.Add("area", new DecisionCriterionValue(value: "Admin")); item.Criteria.Add("controller", new DecisionCriterionValue(value: "Users")); item.Criteria.Add("action", new DecisionCriterionValue(value: "AddUser")); items.Add(item); // Act var tree = DecisionTreeBuilder<Item>.GenerateTree(items, new ItemClassifier()); // Assert Assert.Empty(tree.Matches); var area = Assert.Single(tree.Criteria); Assert.Equal("area", area.Key); var admin = Assert.Single(area.Branches); Assert.Equal("Admin", admin.Key); Assert.Empty(admin.Value.Matches); var controller = Assert.Single(admin.Value.Criteria); Assert.Equal("controller", controller.Key); var users = Assert.Single(controller.Branches); Assert.Equal("Users", users.Key); Assert.Empty(users.Value.Matches); var action = Assert.Single(users.Value.Criteria); Assert.Equal("action", action.Key); var addUser = Assert.Single(action.Branches); Assert.Equal("AddUser", addUser.Key); Assert.Empty(addUser.Value.Criteria); Assert.Same(item, Assert.Single(addUser.Value.Matches)); } [Fact] public void BuildTree_WithMultipleItems() { // Arrange var items = new List<Item>(); var item1 = new Item(); item1.Criteria.Add("controller", new DecisionCriterionValue(value: "Store")); item1.Criteria.Add("action", new DecisionCriterionValue(value: "Buy")); items.Add(item1); var item2 = new Item(); item2.Criteria.Add("controller", new DecisionCriterionValue(value: "Store")); item2.Criteria.Add("action", new DecisionCriterionValue(value: "Checkout")); items.Add(item2); // Act var tree = DecisionTreeBuilder<Item>.GenerateTree(items, new ItemClassifier()); // Assert Assert.Empty(tree.Matches); var action = Assert.Single(tree.Criteria); Assert.Equal("action", action.Key); var buy = action.Branches["Buy"]; Assert.Empty(buy.Matches); var controller = Assert.Single(buy.Criteria); Assert.Equal("controller", controller.Key); var store = Assert.Single(controller.Branches); Assert.Equal("Store", store.Key); Assert.Empty(store.Value.Criteria); Assert.Same(item1, Assert.Single(store.Value.Matches)); var checkout = action.Branches["Checkout"]; Assert.Empty(checkout.Matches); controller = Assert.Single(checkout.Criteria); Assert.Equal("controller", controller.Key); store = Assert.Single(controller.Branches); Assert.Equal("Store", store.Key); Assert.Empty(store.Value.Criteria); Assert.Same(item2, Assert.Single(store.Value.Matches)); } [Fact] public void BuildTree_WithInteriorMatch() { // Arrange var items = new List<Item>(); var item1 = new Item(); item1.Criteria.Add("controller", new DecisionCriterionValue(value: "Store")); item1.Criteria.Add("action", new DecisionCriterionValue(value: "Buy")); items.Add(item1); var item2 = new Item(); item2.Criteria.Add("controller", new DecisionCriterionValue(value: "Store")); item2.Criteria.Add("action", new DecisionCriterionValue(value: "Checkout")); items.Add(item2); var item3 = new Item(); item3.Criteria.Add("action", new DecisionCriterionValue(value: "Buy")); items.Add(item3); // Act var tree = DecisionTreeBuilder<Item>.GenerateTree(items, new ItemClassifier()); // Assert Assert.Empty(tree.Matches); var action = Assert.Single(tree.Criteria); Assert.Equal("action", action.Key); var buy = action.Branches["Buy"]; Assert.Same(item3, Assert.Single(buy.Matches)); } [Fact] public void BuildTree_WithDivergentCriteria() { // Arrange var items = new List<Item>(); var item1 = new Item(); item1.Criteria.Add("controller", new DecisionCriterionValue(value: "Store")); item1.Criteria.Add("action", new DecisionCriterionValue(value: "Buy")); items.Add(item1); var item2 = new Item(); item2.Criteria.Add("controller", new DecisionCriterionValue(value: "Store")); item2.Criteria.Add("action", new DecisionCriterionValue(value: "Checkout")); items.Add(item2); var item3 = new Item(); item3.Criteria.Add("stub", new DecisionCriterionValue(value: "Bleh")); items.Add(item3); // Act var tree = DecisionTreeBuilder<Item>.GenerateTree(items, new ItemClassifier()); // Assert Assert.Empty(tree.Matches); var action = tree.Criteria[0]; Assert.Equal("action", action.Key); var stub = tree.Criteria[1]; Assert.Equal("stub", stub.Key); } private class Item { public Item() { Criteria = new Dictionary<string, DecisionCriterionValue>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, DecisionCriterionValue> Criteria { get; private set; } } private class ItemClassifier : IClassifier<Item> { public IEqualityComparer<object> ValueComparer => RouteValueEqualityComparer.Default; public IDictionary<string, DecisionCriterionValue> GetCriteria(Item item) { return item.Criteria; } } } }
using System; using Microsoft.SPOT; using Math = uk.andyjohnson0.Netduino.Utils.Math; namespace uk.andyjohnson0.Netduino.Drivers.Gps { public enum CoordSystem { /// <summary> /// World Geodetic System. GRS80 datum. /// </summary> WGS84, /// <summary> /// UK national grid. Airy 1830 ellipsoid. /// </summary> OSGB36 } /// <summary> /// Represents a latitude/longitude coordinate on a given elipsoid. /// Latitudes south of the equator and longitudes west of the meridian are negative. /// </summary> public class LatLonCoord { public LatLonCoord( double latitude, double longitude, double altitude, // Above Elipsoid CoordSystem elipsoid) { Latitude = latitude; Longitude = longitude; Altitude = altitude; Elipsoid = elipsoid; } public LatLonCoord( int latitudeDegrees, double latitudeMinutes, int longitudeDegrees, double longitudeMinutes, double altitude, // Above Elipsoid CoordSystem elipsoid) { // TODO: Calculate seconds from double minutes; See http://notinthemanual.blogspot.co.uk/2008/07/convert-nmea-latitude-longitude-to.html Latitude = (double)latitudeDegrees; if (latitudeDegrees >= 0) Latitude += (latitudeMinutes / 60D); else Latitude -= (latitudeMinutes / 60D); Longitude = (double)longitudeDegrees; if (longitudeDegrees >= 0) Longitude += (longitudeMinutes / 60D); else Longitude -= (longitudeMinutes / 60D); Altitude = altitude; Elipsoid = elipsoid; } public double Latitude { get; private set; } public double Longitude { get; private set; } public double Altitude { get; private set; } public CoordSystem Elipsoid { get; private set; } public bool IsEqualTo(LatLonCoord coord) { return (coord != null) && (this.Latitude == coord.Latitude) && (this.Longitude == coord.Longitude) && (this.Altitude == coord.Altitude) && (this.Elipsoid == coord.Elipsoid); } public int LatitudeDegrees { get { return (int)Latitude; } } public double LatitudeMinutes { get { return Math.Abs((Latitude - (double)LatitudeDegrees) * 60D); } } public int LongitudeDegrees { get { return (int)Longitude; } } public double LongitudeMinutes { get { return Math.Abs((Longitude - (double)LongitudeDegrees) * 60D); } } public override string ToString() { return ((LatitudeDegrees >= 0) ? "+" : "") + LatitudeDegrees.ToString() + " " + LatitudeMinutes.ToString("N3") + "' " + ((LongitudeDegrees >= 0) ? "+" : "") + LongitudeDegrees.ToString() + " " + LongitudeMinutes.ToString("N3") + "'"; } public static LatLonCoord Convert( LatLonCoord sourceCoord, CoordSystem targetElipsoid) { if ((sourceCoord.Elipsoid == CoordSystem.WGS84) && (targetElipsoid == CoordSystem.OSGB36)) { return WGS84ToOSGB36(sourceCoord); } throw new NotImplementedException("Conversion not supported");; } // Processes WGS84 lat and lon in decimal form with S and W as -ve private static LatLonCoord WGS84ToOSGB36(LatLonCoord coord) { // Debug.Assert(coord.Elipsoid == CoordSystem.WGS84); double WGlat = coord.Latitude; double WGlon = coord.Longitude; double height = coord.Altitude; //first off convert to radians double radWGlat = Math.DegToRad(WGlat); double radWGlon = Math.DegToRad(WGlon); /* these calculations were derived from the work of * Roger Muggleton (http://www.carabus.co.uk/) */ /* quoting Roger Muggleton :- * There are many ways to convert data from one system to another, the most accurate * being the most complex! For this example I shall use a 7 parameter Helmert * transformation. * The process is in three parts: * (1) Convert latitude and longitude to Cartesian coordinates (these also include height * data, and have three parameters, X, Y and Z). * (2) Transform to the new system by applying the 7 parameters and using a little maths. * (3) Convert back to latitude and longitude. * For the example we shall transform a GRS80 location to Airy, e.g. a GPS reading to * the Airy spheroid. * The following code converts latitude and longitude to Cartesian coordinates. The * input parameters are: WGS84 latitude and longitude, axis is the GRS80/WGS84 major * axis in metres, ecc is the eccentricity, and height is the height above the * ellipsoid. * v = axis / (Math.sqrt (1 - ecc * (Math.Pow (Math.sin(lat), 2)))); * x = (v + height) * Math.cos(lat) * Math.cos(lon); * y = (v + height) * Math.cos(lat) * Math.sin(lon); * z = ((1 - ecc) * v + height) * Math.sin(lat); * The transformation requires the 7 parameters: xp, yp and zp correct the coordinate * origin, xr, yr and zr correct the orientation of the axes, and sf deals with the * changing scale factors. */ //these are the values for WGS86(GRS80) to OSGB36(Airy) double h = height; // height above datum (from GPS GGA sentence) const double a = 6378137; // WGS84_AXIS const double e = 0.00669438037928458; // WGS84_ECCENTRIC const double a2 = 6377563.396; //OSGB_AXIS const double e2 = 0.0066705397616; // OSGB_ECCENTRIC const double xp = -446.448; const double yp = 125.157; const double zp = -542.06; const double xr = -0.1502; const double yr = -0.247; const double zr = -0.8421; const double s = 20.4894; // convert to cartesian; lat, lon are radians double sf = s * 0.000001; double v = a / (Math.Sqrt(1 - (e * (Math.Sin(radWGlat) * Math.Sin(radWGlat))))); double x = (v + h) * Math.Cos(radWGlat) * Math.Cos(radWGlon); double y = (v + h) * Math.Cos(radWGlat) * Math.Sin(radWGlon); double z = ((1 - e) * v + h) * Math.Sin(radWGlat); // transform cartesian double xrot = Math.DegToRad(xr / 3600); double yrot = Math.DegToRad(yr / 3600); double zrot = Math.DegToRad(zr / 3600); double hx = x + (x * sf) - (y * zrot) + (z * yrot) + xp; double hy = (x * zrot) + y + (y * sf) - (z * xrot) + yp; double hz = (-1 * x * yrot) + (y * xrot) + z + (z * sf) + zp; // Convert back to lat, lon double newLon = Math.Atan(hy / hx); double p = Math.Sqrt((hx * hx) + (hy * hy)); double newLat = Math.Atan(hz / (p * (1 - e2))); v = a2 / (Math.Sqrt(1 - e2 * (Math.Sin(newLat) * Math.Sin(newLat)))); double errvalue = 1.0; double lat0 = 0; while (errvalue > 0.001) { lat0 = Math.Atan((hz + e2 * v * Math.Sin(newLat)) / p); errvalue = Math.Abs(lat0 - newLat); newLat = lat0; } //convert back to degrees newLat = Math.RadToDeg(newLat); newLon = Math.RadToDeg(newLon); return new LatLonCoord(newLat, newLon, height, CoordSystem.OSGB36); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Xunit; namespace Compute.Tests { public class VMScenarioTests : VMTestBase { /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VM /// GET VM Model View /// GET VM InstanceView /// GETVMs in a RG /// List VMSizes in a RG /// List VMSizes in an AvailabilitySet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScenarioOperations")] public void TestVMScenarioOperations() { TestVMScenarioOperationsInternal("TestVMScenarioOperations"); } /// <summary> /// Covers following Operations for managed disks: /// Create RG /// Create Network Resources /// Create VM with WriteAccelerator enabled OS and Data disk /// GET VM Model View /// GET VM InstanceView /// GETVMs in a RG /// List VMSizes in a RG /// List VMSizes in an AvailabilitySet /// Delete RG /// /// To record this test case, you need to run it in region which support XMF VMSizeFamily like eastus2. /// </summary> [Fact] [Trait("Name", "TestVMScenarioOperations_ManagedDisks")] public void TestVMScenarioOperations_ManagedDisks() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks", vmSize: VirtualMachineSizeTypes.StandardM64s, hasManagedDisks: true, osDiskStorageAccountType: StorageAccountTypes.PremiumLRS, dataDiskStorageAccountType: StorageAccountTypes.PremiumLRS, writeAcceleratorEnabled: true); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it in region which support local diff disks. /// </summary> [Fact] [Trait("Name", "TestVMScenarioOperations_DiffDisks")] public void TestVMScenarioOperations_DiffDisks() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "northeurope"); TestVMScenarioOperationsInternal("TestVMScenarioOperations_DiffDisks", vmSize: VirtualMachineSizeTypes.StandardDS148V2, hasManagedDisks: true, hasDiffDisks: true, osDiskStorageAccountType: StorageAccountTypes.StandardLRS); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it in region which support DiskEncryptionSet resource for the Disks /// </summary> [Fact] [Trait("Name", "TestVMScenarioOperations_ManagedDisks_DiskEncryptionSet")] public void TestVMScenarioOperations_ManagedDisks_DiskEncryptionSet() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); string diskEncryptionSetId = getDefaultDiskEncryptionSetId(); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "centraluseuap"); TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_DiskEncryptionSet", vmSize: VirtualMachineSizeTypes.StandardA1V2, hasManagedDisks: true, osDiskStorageAccountType: StorageAccountTypes.StandardLRS, diskEncryptionSetId: diskEncryptionSetId); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// TODO: StandardSSD is currently in preview and is available only in a few regions. Once it goes GA, it can be tested in /// the default test location. /// </summary> [Fact] [Trait("Name", "TestVMScenarioOperations_ManagedDisks_StandardSSD")] public void TestVMScenarioOperations_ManagedDisks_StandardSSD() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "northeurope"); TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_StandardSSD", hasManagedDisks: true, osDiskStorageAccountType: StorageAccountTypes.StandardSSDLRS, dataDiskStorageAccountType: StorageAccountTypes.StandardSSDLRS); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it in zone supported regions like eastus2. /// </summary> [Fact] [Trait("Name", "TestVMScenarioOperations_ManagedDisks_PirImage_Zones")] public void TestVMScenarioOperations_ManagedDisks_PirImage_Zones() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "centralus"); TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_PirImage_Zones", hasManagedDisks: true, zones: new List<string> { "1" }, callUpdateVM: true); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it in zone supported regions like eastus2euap. /// </summary> [Fact] [Trait("Name", "TestVMScenarioOperations_ManagedDisks_UltraSSD")] public void TestVMScenarioOperations_ManagedDisks_UltraSSD() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_UltraSSD", hasManagedDisks: true, zones: new List<string> { "1" }, vmSize: VirtualMachineSizeTypes.StandardE16sV3, osDiskStorageAccountType: StorageAccountTypes.PremiumLRS, dataDiskStorageAccountType: StorageAccountTypes.UltraSSDLRS, callUpdateVM: true); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it in zone supported regions like eastus2euap. /// </summary> [Fact] [Trait("Name", "TestVMScenarioOperations_PpgScenario")] public void TestVMScenarioOperations_PpgScenario() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); TestVMScenarioOperationsInternal("TestVMScenarioOperations_PpgScenario", hasManagedDisks: true, isPpgScenario: true); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } private void TestVMScenarioOperationsInternal(string methodName, bool hasManagedDisks = false, IList<string> zones = null, string vmSize = "Standard_A0", string osDiskStorageAccountType = "Standard_LRS", string dataDiskStorageAccountType = "Standard_LRS", bool? writeAcceleratorEnabled = null, bool hasDiffDisks = false, bool callUpdateVM = false, bool isPpgScenario = false, string diskEncryptionSetId = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); const string expectedOSName = "Windows Server 2012 R2 Datacenter", expectedOSVersion = "Microsoft Windows NT 6.3.9600.0", expectedComputerName = ComputerName; // Create resource group var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string asName = ComputeManagementTestUtilities.GenerateName("as"); string ppgName = null; string expectedPpgReferenceId = null; if (isPpgScenario) { ppgName = ComputeManagementTestUtilities.GenerateName("ppgtest"); expectedPpgReferenceId = Helpers.GetProximityPlacementGroupRef(m_subId, rgName, ppgName); } VirtualMachine inputVM; try { if (!hasManagedDisks) { CreateStorageAccount(rgName, storageAccountName); } CreateVM(rgName, asName, storageAccountName, imageRef, out inputVM, hasManagedDisks: hasManagedDisks,hasDiffDisks: hasDiffDisks, vmSize: vmSize, osDiskStorageAccountType: osDiskStorageAccountType, dataDiskStorageAccountType: dataDiskStorageAccountType, writeAcceleratorEnabled: writeAcceleratorEnabled, zones: zones, ppgName: ppgName, diskEncryptionSetId: diskEncryptionSetId); // Instance view is not completely populated just after VM is provisioned. So we wait here for a few minutes to // allow GA blob to populate. ComputeManagementTestUtilities.WaitMinutes(5); var getVMWithInstanceViewResponse = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name, InstanceViewTypes.InstanceView); Assert.True(getVMWithInstanceViewResponse != null, "VM in Get"); if (diskEncryptionSetId != null) { Assert.True(getVMWithInstanceViewResponse.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != null, "OsDisk.ManagedDisk.DiskEncryptionSet is null"); Assert.True(string.Equals(diskEncryptionSetId, getVMWithInstanceViewResponse.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase), "OsDisk.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource"); Assert.Equal(1, getVMWithInstanceViewResponse.StorageProfile.DataDisks.Count); Assert.True(getVMWithInstanceViewResponse.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet != null, ".DataDisks.ManagedDisk.DiskEncryptionSet is null"); Assert.True(string.Equals(diskEncryptionSetId, getVMWithInstanceViewResponse.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase), "DataDisks.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource"); } ValidateVMInstanceView(inputVM, getVMWithInstanceViewResponse, hasManagedDisks, expectedComputerName, expectedOSName, expectedOSVersion); var getVMInstanceViewResponse = m_CrpClient.VirtualMachines.InstanceView(rgName, inputVM.Name); Assert.True(getVMInstanceViewResponse != null, "VM in InstanceView"); ValidateVMInstanceView(inputVM, getVMInstanceViewResponse, hasManagedDisks, expectedComputerName, expectedOSName, expectedOSVersion); bool hasUserDefinedAS = zones == null; string expectedVMReferenceId = Helpers.GetVMReferenceId(m_subId, rgName, inputVM.Name); var listResponse = m_CrpClient.VirtualMachines.List(rgName); ValidateVM(inputVM, listResponse.FirstOrDefault(x => x.Name == inputVM.Name), expectedVMReferenceId, hasManagedDisks, hasUserDefinedAS, writeAcceleratorEnabled, hasDiffDisks, expectedPpgReferenceId: expectedPpgReferenceId); var listVMSizesResponse = m_CrpClient.VirtualMachines.ListAvailableSizes(rgName, inputVM.Name); Helpers.ValidateVirtualMachineSizeListResponse(listVMSizesResponse, hasAZ: zones != null, writeAcceleratorEnabled: writeAcceleratorEnabled, hasDiffDisks: hasDiffDisks); listVMSizesResponse = m_CrpClient.AvailabilitySets.ListAvailableSizes(rgName, asName); Helpers.ValidateVirtualMachineSizeListResponse(listVMSizesResponse, hasAZ: zones != null, writeAcceleratorEnabled: writeAcceleratorEnabled, hasDiffDisks: hasDiffDisks); if(isPpgScenario) { ProximityPlacementGroup outProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.Get(rgName, ppgName); string expectedAvSetReferenceId = Helpers.GetAvailabilitySetRef(m_subId, rgName, asName); Assert.Equal(1, outProximityPlacementGroup.VirtualMachines.Count); Assert.Equal(1, outProximityPlacementGroup.AvailabilitySets.Count); Assert.Equal(expectedVMReferenceId, outProximityPlacementGroup.VirtualMachines.First().Id, StringComparer.OrdinalIgnoreCase); Assert.Equal(expectedAvSetReferenceId, outProximityPlacementGroup.AvailabilitySets.First().Id, StringComparer.OrdinalIgnoreCase); } if (callUpdateVM) { VirtualMachineUpdate updateParams = new VirtualMachineUpdate() { Tags = inputVM.Tags }; string updateKey = "UpdateTag"; updateParams.Tags.Add(updateKey, "UpdateTagValue"); VirtualMachine updateResponse = m_CrpClient.VirtualMachines.Update(rgName, inputVM.Name, updateParams); Assert.True(updateResponse.Tags.ContainsKey(updateKey)); } } finally { // Fire and forget. No need to wait for RG deletion completion try { m_ResourcesClient.ResourceGroups.BeginDelete(rgName); } catch (Exception e) { // Swallow this exception so that the original exception is thrown Console.WriteLine(e); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: class to sort arrays ** ** ===========================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { #region ArraySortHelper for single arrays internal static class IntrospectiveSortUtilities { // This is the threshold where Introspective sort switches to Insertion sort. // Empirically, 16 seems to speed up most cases without slowing down others, at least for integers. // Large value types may benefit from a smaller number. internal const int IntrosortSizeThreshold = 16; internal static int FloorLog2PlusOne(int n) { int result = 0; while (n >= 1) { result++; n /= 2; } return result; } [DoesNotReturn] internal static void ThrowOrIgnoreBadComparer(object? comparer) { throw new ArgumentException(SR.Format(SR.Arg_BogusIComparer, comparer)); } } internal partial class ArraySortHelper<T> { #region IArraySortHelper<T> Members public void Sort(T[] keys, int index, int length, IComparer<T>? comparer) { Debug.Assert(keys != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { comparer ??= Comparer<T>.Default; IntrospectiveSort(keys, index, length, comparer.Compare); } catch (IndexOutOfRangeException) { IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); } catch (Exception e) { throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); } } public int BinarySearch(T[] array, int index, int length, T value, IComparer<T>? comparer) { try { comparer ??= Comparer<T>.Default; return InternalBinarySearch(array, index, length, value, comparer); } catch (Exception e) { throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); } } #endregion internal static void Sort(T[] keys, int index, int length, Comparison<T> comparer) { Debug.Assert(keys != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); Debug.Assert(comparer != null, "Check the arguments in the caller!"); // Add a try block here to detect bogus comparisons try { IntrospectiveSort(keys, index, length, comparer); } catch (IndexOutOfRangeException) { IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); } catch (Exception e) { throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); } } internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer) { Debug.Assert(array != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order = comparer.Compare(array[i], value); if (order == 0) return i; if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } private static void SwapIfGreater(T[] keys, Comparison<T> comparer, int a, int b) { if (a != b) { if (comparer(keys[a], keys[b]) > 0) { T key = keys[a]; keys[a] = keys[b]; keys[b] = key; } } } private static void Swap(T[] a, int i, int j) { if (i != j) { T t = a[i]; a[i] = a[j]; a[j] = t; } } internal static void IntrospectiveSort(T[] keys, int left, int length, Comparison<T> comparer) { Debug.Assert(keys != null); Debug.Assert(comparer != null); Debug.Assert(left >= 0); Debug.Assert(length >= 0); Debug.Assert(length <= keys.Length); Debug.Assert(length + left <= keys.Length); if (length < 2) return; IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length), comparer); } private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, Comparison<T> comparer) { Debug.Assert(keys != null); Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(hi < keys.Length); while (hi > lo) { int partitionSize = hi - lo + 1; if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) { if (partitionSize == 1) { return; } if (partitionSize == 2) { SwapIfGreater(keys, comparer, lo, hi); return; } if (partitionSize == 3) { SwapIfGreater(keys, comparer, lo, hi - 1); SwapIfGreater(keys, comparer, lo, hi); SwapIfGreater(keys, comparer, hi - 1, hi); return; } InsertionSort(keys, lo, hi, comparer); return; } if (depthLimit == 0) { Heapsort(keys, lo, hi, comparer); return; } depthLimit--; int p = PickPivotAndPartition(keys, lo, hi, comparer); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys, p + 1, hi, depthLimit, comparer); hi = p - 1; } } private static int PickPivotAndPartition(T[] keys, int lo, int hi, Comparison<T> comparer) { Debug.Assert(keys != null); Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(hi > lo); Debug.Assert(hi < keys.Length); // Compute median-of-three. But also partition them, since we've done the comparison. int middle = lo + ((hi - lo) / 2); // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreater(keys, comparer, lo, middle); // swap the low with the mid point SwapIfGreater(keys, comparer, lo, hi); // swap the low with the high SwapIfGreater(keys, comparer, middle, hi); // swap the middle with the high T pivot = keys[middle]; Swap(keys, middle, hi - 1); int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer(keys[++left], pivot) < 0) ; while (comparer(pivot, keys[--right]) < 0) ; if (left >= right) break; Swap(keys, left, right); } // Put pivot in the right location. Swap(keys, left, hi - 1); return left; } private static void Heapsort(T[] keys, int lo, int hi, Comparison<T> comparer) { Debug.Assert(keys != null); Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(hi > lo); Debug.Assert(hi < keys.Length); int n = hi - lo + 1; for (int i = n / 2; i >= 1; i--) { DownHeap(keys, i, n, lo, comparer); } for (int i = n; i > 1; i--) { Swap(keys, lo, lo + i - 1); DownHeap(keys, 1, i - 1, lo, comparer); } } private static void DownHeap(T[] keys, int i, int n, int lo, Comparison<T> comparer) { Debug.Assert(keys != null); Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; int child; while (i <= n / 2) { child = 2 * i; if (child < n && comparer(keys[lo + child - 1], keys[lo + child]) < 0) { child++; } if (!(comparer(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; i = child; } keys[lo + i - 1] = d; } private static void InsertionSort(T[] keys, int lo, int hi, Comparison<T> comparer) { Debug.Assert(keys != null); Debug.Assert(lo >= 0); Debug.Assert(hi >= lo); Debug.Assert(hi <= keys.Length); int i, j; T t; for (i = lo; i < hi; i++) { j = i; t = keys[i + 1]; while (j >= lo && comparer(t, keys[j]) < 0) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t; } } } internal partial class GenericArraySortHelper<T> where T : IComparable<T> { // Do not add a constructor to this class because ArraySortHelper<T>.CreateSortHelper will not execute it #region IArraySortHelper<T> Members public void Sort(T[] keys, int index, int length, IComparer<T>? comparer) { Debug.Assert(keys != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); try { if (comparer == null || comparer == Comparer<T>.Default) { IntrospectiveSort(keys, index, length); } else { ArraySortHelper<T>.IntrospectiveSort(keys, index, length, comparer.Compare); } } catch (IndexOutOfRangeException) { IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); } catch (Exception e) { throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); } } public int BinarySearch(T[] array, int index, int length, T value, IComparer<T>? comparer) { Debug.Assert(array != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); try { if (comparer == null || comparer == Comparer<T>.Default) { return BinarySearch(array, index, length, value); } else { return ArraySortHelper<T>.InternalBinarySearch(array, index, length, value, comparer); } } catch (Exception e) { throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); } } #endregion // This function is called when the user doesn't specify any comparer. // Since T is constrained here, we can call IComparable<T>.CompareTo here. // We can avoid boxing for value type and casting for reference types. private static int BinarySearch(T[] array, int index, int length, T value) { int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order; if (array[i] == null) { order = (value == null) ? 0 : -1; } else { order = array[i].CompareTo(value); } if (order == 0) { return i; } if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } private static void SwapIfGreaterWithItems(T[] keys, int a, int b) { Debug.Assert(keys != null); Debug.Assert(0 <= a && a < keys.Length); Debug.Assert(0 <= b && b < keys.Length); if (a != b) { if (keys[a] != null && keys[a].CompareTo(keys[b]) > 0) { T key = keys[a]; keys[a] = keys[b]; keys[b] = key; } } } private static void Swap(T[] a, int i, int j) { if (i != j) { T t = a[i]; a[i] = a[j]; a[j] = t; } } internal static void IntrospectiveSort(T[] keys, int left, int length) { Debug.Assert(keys != null); Debug.Assert(left >= 0); Debug.Assert(length >= 0); Debug.Assert(length <= keys.Length); Debug.Assert(length + left <= keys.Length); if (length < 2) return; IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length)); } private static void IntroSort(T[] keys, int lo, int hi, int depthLimit) { Debug.Assert(keys != null); Debug.Assert(lo >= 0); Debug.Assert(hi < keys.Length); while (hi > lo) { int partitionSize = hi - lo + 1; if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) { if (partitionSize == 1) { return; } if (partitionSize == 2) { SwapIfGreaterWithItems(keys, lo, hi); return; } if (partitionSize == 3) { SwapIfGreaterWithItems(keys, lo, hi - 1); SwapIfGreaterWithItems(keys, lo, hi); SwapIfGreaterWithItems(keys, hi - 1, hi); return; } InsertionSort(keys, lo, hi); return; } if (depthLimit == 0) { Heapsort(keys, lo, hi); return; } depthLimit--; int p = PickPivotAndPartition(keys, lo, hi); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys, p + 1, hi, depthLimit); hi = p - 1; } } private static int PickPivotAndPartition(T[] keys, int lo, int hi) { Debug.Assert(keys != null); Debug.Assert(lo >= 0); Debug.Assert(hi > lo); Debug.Assert(hi < keys.Length); // Compute median-of-three. But also partition them, since we've done the comparison. int middle = lo + ((hi - lo) / 2); // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithItems(keys, lo, middle); // swap the low with the mid point SwapIfGreaterWithItems(keys, lo, hi); // swap the low with the high SwapIfGreaterWithItems(keys, middle, hi); // swap the middle with the high T pivot = keys[middle]; Swap(keys, middle, hi - 1); int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { if (pivot == null) { while (left < (hi - 1) && keys[++left] == null) ; while (right > lo && keys[--right] != null) ; } else { while (pivot.CompareTo(keys[++left]) > 0) ; while (pivot.CompareTo(keys[--right]) < 0) ; } if (left >= right) break; Swap(keys, left, right); } // Put pivot in the right location. Swap(keys, left, hi - 1); return left; } private static void Heapsort(T[] keys, int lo, int hi) { Debug.Assert(keys != null); Debug.Assert(lo >= 0); Debug.Assert(hi > lo); Debug.Assert(hi < keys.Length); int n = hi - lo + 1; for (int i = n / 2; i >= 1; i--) { DownHeap(keys, i, n, lo); } for (int i = n; i > 1; i--) { Swap(keys, lo, lo + i - 1); DownHeap(keys, 1, i - 1, lo); } } private static void DownHeap(T[] keys, int i, int n, int lo) { Debug.Assert(keys != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; int child; while (i <= n / 2) { child = 2 * i; if (child < n && (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(keys[lo + child]) < 0)) { child++; } if (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(d) < 0) break; keys[lo + i - 1] = keys[lo + child - 1]; i = child; } keys[lo + i - 1] = d; } private static void InsertionSort(T[] keys, int lo, int hi) { Debug.Assert(keys != null); Debug.Assert(lo >= 0); Debug.Assert(hi >= lo); Debug.Assert(hi <= keys.Length); int i, j; T t; for (i = lo; i < hi; i++) { j = i; t = keys[i + 1]; while (j >= lo && (t == null || t.CompareTo(keys[j]) < 0)) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t; } } } #endregion #region ArraySortHelper for paired key and value arrays internal partial class ArraySortHelper<TKey, TValue> { public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey>? comparer) { Debug.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method Debug.Assert(values != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { if (comparer == null || comparer == Comparer<TKey>.Default) { comparer = Comparer<TKey>.Default; } IntrospectiveSort(keys, values, index, length, comparer); } catch (IndexOutOfRangeException) { IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); } catch (Exception e) { throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, IComparer<TKey> comparer, int a, int b) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(comparer != null); Debug.Assert(0 <= a && a < keys.Length && a < values.Length); Debug.Assert(0 <= b && b < keys.Length && b < values.Length); if (a != b) { if (comparer.Compare(keys[a], keys[b]) > 0) { TKey key = keys[a]; keys[a] = keys[b]; keys[b] = key; TValue value = values[a]; values[a] = values[b]; values[b] = value; } } } private static void Swap(TKey[] keys, TValue[] values, int i, int j) { if (i != j) { TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } } internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length, IComparer<TKey> comparer) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(comparer != null); Debug.Assert(left >= 0); Debug.Assert(length >= 0); Debug.Assert(length <= keys.Length); Debug.Assert(length + left <= keys.Length); Debug.Assert(length + left <= values.Length); if (length < 2) return; IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length), comparer); } private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit, IComparer<TKey> comparer) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(hi < keys.Length); while (hi > lo) { int partitionSize = hi - lo + 1; if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) { if (partitionSize == 1) { return; } if (partitionSize == 2) { SwapIfGreaterWithItems(keys, values, comparer, lo, hi); return; } if (partitionSize == 3) { SwapIfGreaterWithItems(keys, values, comparer, lo, hi - 1); SwapIfGreaterWithItems(keys, values, comparer, lo, hi); SwapIfGreaterWithItems(keys, values, comparer, hi - 1, hi); return; } InsertionSort(keys, values, lo, hi, comparer); return; } if (depthLimit == 0) { Heapsort(keys, values, lo, hi, comparer); return; } depthLimit--; int p = PickPivotAndPartition(keys, values, lo, hi, comparer); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys, values, p + 1, hi, depthLimit, comparer); hi = p - 1; } } private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(hi > lo); Debug.Assert(hi < keys.Length); // Compute median-of-three. But also partition them, since we've done the comparison. int middle = lo + ((hi - lo) / 2); // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithItems(keys, values, comparer, lo, middle); // swap the low with the mid point SwapIfGreaterWithItems(keys, values, comparer, lo, hi); // swap the low with the high SwapIfGreaterWithItems(keys, values, comparer, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer.Compare(keys[++left], pivot) < 0) ; while (comparer.Compare(pivot, keys[--right]) < 0) ; if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. Swap(keys, values, left, hi - 1); return left; } private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(hi > lo); Debug.Assert(hi < keys.Length); int n = hi - lo + 1; for (int i = n / 2; i >= 1; i--) { DownHeap(keys, values, i, n, lo, comparer); } for (int i = n; i > 1; i--) { Swap(keys, values, lo, lo + i - 1); DownHeap(keys, values, 1, i - 1, lo, comparer); } } private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo, IComparer<TKey> comparer) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = values[lo + i - 1]; int child; while (i <= n / 2) { child = 2 * i; if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0) { child++; } if (!(comparer.Compare(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; values[lo + i - 1] = values[lo + child - 1]; i = child; } keys[lo + i - 1] = d; values[lo + i - 1] = dValue; } private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(hi >= lo); Debug.Assert(hi <= keys.Length); int i, j; TKey t; TValue tValue; for (i = lo; i < hi; i++) { j = i; t = keys[i + 1]; tValue = values[i + 1]; while (j >= lo && comparer.Compare(t, keys[j]) < 0) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t; values[j + 1] = tValue; } } } internal partial class GenericArraySortHelper<TKey, TValue> where TKey : IComparable<TKey> { public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey>? comparer) { Debug.Assert(keys != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { if (comparer == null || comparer == Comparer<TKey>.Default) { IntrospectiveSort(keys, values, index, length); } else { ArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, index, length, comparer); } } catch (IndexOutOfRangeException) { IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer); } catch (Exception e) { throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, int a, int b) { if (a != b) { if (keys[a] != null && keys[a].CompareTo(keys[b]) > 0) { TKey key = keys[a]; keys[a] = keys[b]; keys[b] = key; TValue value = values[a]; values[a] = values[b]; values[b] = value; } } } private static void Swap(TKey[] keys, TValue[] values, int i, int j) { if (i != j) { TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } } internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(left >= 0); Debug.Assert(length >= 0); Debug.Assert(length <= keys.Length); Debug.Assert(length + left <= keys.Length); Debug.Assert(length + left <= values.Length); if (length < 2) return; IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length)); } private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(lo >= 0); Debug.Assert(hi < keys.Length); while (hi > lo) { int partitionSize = hi - lo + 1; if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold) { if (partitionSize == 1) { return; } if (partitionSize == 2) { SwapIfGreaterWithItems(keys, values, lo, hi); return; } if (partitionSize == 3) { SwapIfGreaterWithItems(keys, values, lo, hi - 1); SwapIfGreaterWithItems(keys, values, lo, hi); SwapIfGreaterWithItems(keys, values, hi - 1, hi); return; } InsertionSort(keys, values, lo, hi); return; } if (depthLimit == 0) { Heapsort(keys, values, lo, hi); return; } depthLimit--; int p = PickPivotAndPartition(keys, values, lo, hi); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys, values, p + 1, hi, depthLimit); hi = p - 1; } } private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(lo >= 0); Debug.Assert(hi > lo); Debug.Assert(hi < keys.Length); // Compute median-of-three. But also partition them, since we've done the comparison. int middle = lo + ((hi - lo) / 2); // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithItems(keys, values, lo, middle); // swap the low with the mid point SwapIfGreaterWithItems(keys, values, lo, hi); // swap the low with the high SwapIfGreaterWithItems(keys, values, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { if (pivot == null) { while (left < (hi - 1) && keys[++left] == null) ; while (right > lo && keys[--right] != null) ; } else { while (pivot.CompareTo(keys[++left]) > 0) ; while (pivot.CompareTo(keys[--right]) < 0) ; } if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. Swap(keys, values, left, hi - 1); return left; } private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(lo >= 0); Debug.Assert(hi > lo); Debug.Assert(hi < keys.Length); int n = hi - lo + 1; for (int i = n / 2; i >= 1; i--) { DownHeap(keys, values, i, n, lo); } for (int i = n; i > 1; i--) { Swap(keys, values, lo, lo + i - 1); DownHeap(keys, values, 1, i - 1, lo); } } private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo) { Debug.Assert(keys != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = values[lo + i - 1]; int child; while (i <= n / 2) { child = 2 * i; if (child < n && (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(keys[lo + child]) < 0)) { child++; } if (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(d) < 0) break; keys[lo + i - 1] = keys[lo + child - 1]; values[lo + i - 1] = values[lo + child - 1]; i = child; } keys[lo + i - 1] = d; values[lo + i - 1] = dValue; } private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(lo >= 0); Debug.Assert(hi >= lo); Debug.Assert(hi <= keys.Length); int i, j; TKey t; TValue tValue; for (i = lo; i < hi; i++) { j = i; t = keys[i + 1]; tValue = values[i + 1]; while (j >= lo && (t == null || t.CompareTo(keys[j]) < 0)) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t; values[j + 1] = tValue; } } } #endregion }
using System; using System.Collections.Generic; using System.Data; using System.Data.OracleClient; using System.Linq; using NMG.Core.Domain; namespace NMG.Core.Reader { public static class ConstraintTypeResolver //: IConstraintTypeResolver { public static bool IsPrimaryKey(int constraintType) { return (constraintType & OracleConstraintType.PrimaryKey.Value) == OracleConstraintType.PrimaryKey.Value; } public static bool IsForeignKey(int constraintType) { return (constraintType & OracleConstraintType.ForeignKey.Value) == OracleConstraintType.ForeignKey.Value; } public static bool IsUnique(int constraintType) { return (constraintType & OracleConstraintType.Unique.Value) == OracleConstraintType.Unique.Value; } public static bool IsCheck(int constraintType) { return (constraintType & OracleConstraintType.Check.Value) == OracleConstraintType.Check.Value; } } public class OracleMetadataReader : IMetadataReader { private readonly string connectionStr; public OracleMetadataReader(string connectionStr) { this.connectionStr = connectionStr; } #region IMetadataReader Members /// <summary> /// Return all table details based on table and owner. /// </summary> /// <param name="table"></param> /// <param name="owner"></param> /// <returns></returns> public IList<Column> GetTableDetails(Table table, string owner) { var columns = new List<Column>(); using (var conn = new OracleConnection(connectionStr)) { conn.Open(); using (OracleCommand tableCommand = conn.CreateCommand()) { tableCommand.CommandText = @"select column_name, data_type, nullable, sum(constraint_type) constraint_type, data_length, data_precision, data_scale from ( SELECT tc.column_name AS column_name, tc.data_type AS data_type, tc.nullable AS NULLABLE, decode(c.constraint_type, 'P', 1, 'R', 2, 'U', 4, 'C', 8, 16) AS constraint_type, data_length, data_precision, data_scale, column_id from all_tab_columns tc left outer join ( all_cons_columns cc join all_constraints c on ( c.owner=cc.owner and c.constraint_name = cc.constraint_name ) ) on ( tc.owner = cc.owner and tc.table_name = cc.table_name and tc.column_name = cc.column_name ) where tc.table_name = :table_name and tc.owner = :owner order by tc.table_name, cc.position nulls last, tc.column_id) group by column_name, data_type, nullable, data_length, data_precision, data_scale, column_id order by column_id"; tableCommand.Parameters.Add("table_name", table.Name); tableCommand.Parameters.Add("owner", owner); using (OracleDataReader oracleDataReader = tableCommand.ExecuteReader(CommandBehavior.Default)) { var m = new DataTypeMapper(); while (oracleDataReader.Read()) { var constraintType = Convert.ToInt32(oracleDataReader.GetOracleNumber(3).Value); int? dataLength = oracleDataReader.IsDBNull(4) ? (int?)null : Convert.ToInt32(oracleDataReader.GetOracleNumber(4).Value); int? dataPrecision = oracleDataReader.IsDBNull(5) ? (int?)null : Convert.ToInt32(oracleDataReader.GetOracleNumber(5).Value); int? dataScale = oracleDataReader.IsDBNull(6) ? (int?)null : Convert.ToInt32(oracleDataReader.GetOracleNumber(6).Value); columns.Add(new Column { Name = oracleDataReader.GetOracleString(0).Value, DataType = oracleDataReader.GetOracleString(1).Value, IsNullable = string.Equals(oracleDataReader.GetOracleString(2).Value, "Y", StringComparison.OrdinalIgnoreCase), IsPrimaryKey = ConstraintTypeResolver.IsPrimaryKey(constraintType), IsForeignKey = ConstraintTypeResolver.IsForeignKey(constraintType), IsUnique = ConstraintTypeResolver.IsUnique(constraintType), MappedDataType = m.MapFromDBType(ServerType.Oracle, oracleDataReader.GetOracleString(1).Value, dataLength, dataPrecision, dataScale).ToString(), DataLength = dataLength, DataPrecision = dataPrecision, DataScale = dataScale }); } table.Owner = owner; table.Columns = columns; table.PrimaryKey = DeterminePrimaryKeys(table); // Need to find the table name associated with the FK foreach (var c in table.Columns.Where(c => c.IsForeignKey)) { var foreignInfo = GetForeignKeyReferenceTableName(table.Name, c.Name); c.ForeignKeyTableName = foreignInfo.Item1; c.ForeignKeyColumnName = foreignInfo.Item2; } table.ForeignKeys = DetermineForeignKeyReferences(table); table.HasManyRelationships = DetermineHasManyRelationships(table); } } conn.Close(); } return columns; } public List<Table> GetTables(string owner) { var tables = new List<Table>(); var conn = new OracleConnection(connectionStr); conn.Open(); using (conn) { using (OracleCommand tableCommand = conn.CreateCommand()) { tableCommand.CommandText = "select table_name from all_tables where owner = :table_name order by table_name"; tableCommand.Parameters.Add(new OracleParameter("table_name", owner)); using (OracleDataReader oracleDataReader = tableCommand.ExecuteReader(CommandBehavior.CloseConnection)) { while (oracleDataReader.Read()) { string tableName = oracleDataReader.GetString(0); tables.Add(new Table { Name = tableName }); } } } } return tables; } public IList<string> GetOwners() { var owners = new List<string>(); using (var conn = new OracleConnection(connectionStr)) { conn.Open(); using (OracleCommand tableCommand = conn.CreateCommand()) { tableCommand.CommandText = "select username from all_users order by username"; using (OracleDataReader oracleDataReader = tableCommand.ExecuteReader(CommandBehavior.CloseConnection)) { while (oracleDataReader.Read()) { string owner = oracleDataReader.GetString(0); owners.Add(owner); } } } conn.Close(); } return owners; } public List<string> GetSequences(string owner) { var sequences = new List<string>(); using (var conn = new OracleConnection(connectionStr)) { conn.Open(); using (var seqCommand = conn.CreateCommand()) { seqCommand.CommandText = "select sequence_name from all_sequences where sequence_owner = :owner order by sequence_name"; seqCommand.Parameters.Add(new OracleParameter("owner", owner)); using (OracleDataReader seqReader = seqCommand.ExecuteReader(CommandBehavior.CloseConnection)) { while (seqReader.Read()) { string tableName = seqReader.GetString(0); sequences.Add(tableName); } } } conn.Close(); } return sequences; } public PrimaryKey DeterminePrimaryKeys(Table table) { var primaryKeys = table.Columns.Where(x => x.IsPrimaryKey.Equals(true)).ToList(); if (primaryKeys.Count() == 1) { var c = primaryKeys.First(); var key = new PrimaryKey { Type = PrimaryKeyType.PrimaryKey, Columns = { c } }; return key; } if (primaryKeys.Count() > 1) { // Composite key var key = new PrimaryKey { Type = PrimaryKeyType.CompositeKey, Columns = primaryKeys }; return key; } return null; } public IList<ForeignKey> DetermineForeignKeyReferences(Table table) { var foreignKeys = (from c in table.Columns where c.IsForeignKey group c by new { c.ConstraintName, c.ForeignKeyTableName } into g select new ForeignKey { Name = g.Key.ConstraintName, References = g.Key.ForeignKeyTableName, Columns = g.ToList(), UniquePropertyName = g.Key.ForeignKeyTableName }).ToList(); Table.SetUniqueNamesForForeignKeyProperties(foreignKeys); return foreignKeys; } #endregion public IList<HasMany> DetermineHasManyRelationships(Table table) { var hasManyRelationships = new List<HasMany>(); var conn = new OracleConnection(connectionStr); conn.Open(); using (conn) { using (var command = new OracleCommand()) { command.Connection = conn; command.CommandText = @"SELECT R.TABLE_NAME, COL.COLUMN_NAME FROM ALL_CONSTRAINTS C, ALL_CONSTRAINTS R, ALL_CONS_COLUMNS COL WHERE C.TABLE_NAME = :TABLE_NAME AND C.CONSTRAINT_NAME = R.R_CONSTRAINT_NAME AND R.CONSTRAINT_NAME = COL.CONSTRAINT_NAME AND R.TABLE_NAME = COL.TABLE_NAME AND R.OWNER = COL.OWNER"; command.Parameters.Add(new OracleParameter("TABLE_NAME", table.Name)); OracleDataReader reader = command.ExecuteReader(); while (reader.Read()) { hasManyRelationships.Add(new HasMany { Reference = reader.GetString(0), ReferenceColumn = reader.GetString(1) }); } return hasManyRelationships; } } } // http://blog.mclaughlinsoftware.com/2009/03/05/validating-foreign-keys/ private Tuple<string, string> GetForeignKeyReferenceTableName(string selectedTableName, string columnName) { using (var conn = new OracleConnection(connectionStr)) { conn.Open(); using (OracleCommand tableCommand = conn.CreateCommand()) { tableCommand.CommandText = @"SELECT ucc2.table_name, ucc2.column_name FROM all_constraints uc, all_cons_columns ucc1, all_cons_columns ucc2 WHERE uc.constraint_name = ucc1.constraint_name AND uc.r_constraint_name = ucc2.constraint_name AND uc.constraint_type = 'R' AND ucc1.table_name = :table_name and ucc1.column_name = :column_name"; tableCommand.Parameters.Add("table_name", selectedTableName); tableCommand.Parameters.Add("column_name", columnName); using (var reader = tableCommand.ExecuteReader()) { if (reader.Read()) { return new Tuple<string, string>(reader.GetOracleString(0).Value, reader.GetOracleString(1).Value); } else return null; } } conn.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.Collections.Generic; /// <summary> /// System.Collections.Generic.IDictionary.Item(TKey) /// </summary> public class IDictionaryItem { private int c_MINI_STRING_LENGTH = 1; private int c_MAX_STRING_LENGTH = 20; public static int Main(string[] args) { IDictionaryItem testObj = new IDictionaryItem(); TestLibrary.TestFramework.BeginTestCase("Testing for Property: System.Collections.Generic.IDictionary.Item(TKey)"); if (testObj.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; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Netativ]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Using Dictionary<TKey,TValue> which implemented the item property in IDictionay<TKey,TValue> and TKey is int..."; const string c_TEST_ID = "P001"; Dictionary<int, int> dictionary = new Dictionary<int, int>(); int key = TestLibrary.Generator.GetInt32(-55); int value = TestLibrary.Generator.GetInt32(-55); int newValue = TestLibrary.Generator.GetInt32(-55); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IDictionary<int, int>)dictionary)[key] = value; if (((IDictionary<int, int>)dictionary)[key] != value) { string errorDesc = "Value is not " + value + " as expected: Actual(" + dictionary[key] + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } ((IDictionary<int, int>)dictionary)[key] = newValue; if (((IDictionary<int, int>)dictionary)[key] != newValue) { string errorDesc = "Value is not " + newValue + " as expected: Actual(" + dictionary[key] + ")"; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Using Dictionary<TKey,TValue> which implemented the item property in IDictionay<TKey,TValue> and TKey is String..."; const string c_TEST_ID = "P002"; Dictionary<String, String> dictionary = new Dictionary<String, String>(); String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); String value = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); dictionary.Add(key, value); String newValue = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (((IDictionary<String, String>)dictionary)[key] != value) { string errorDesc = "Value is not " + value + " as expected: Actual(" + dictionary[key] + ")"; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } ((IDictionary<String, String>)dictionary)[key] = newValue; if (((IDictionary<String, String>)dictionary)[key] != newValue) { string errorDesc = "Value is not " + newValue + " as expected: Actual(" + dictionary[key] + ")"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Using Dictionary<TKey,TValue> which implemented the item property in IDictionay<TKey,TValue> and TKey is customer class..."; const string c_TEST_ID = "P003"; Dictionary<MyClass, int> dictionary = new Dictionary<MyClass, int>(); MyClass key = new MyClass(); int value = TestLibrary.Generator.GetInt32(-55); dictionary.Add(key, value); int newValue = TestLibrary.Generator.GetInt32(-55); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (((IDictionary<MyClass, int>)dictionary)[key] != value) { string errorDesc = "Value is not " + value + " as expected: Actual(" + dictionary[key] + ")"; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } ((IDictionary<MyClass, int>)dictionary)[key] = newValue; if (((IDictionary<MyClass, int>)dictionary)[key] != newValue) { string errorDesc = "Value is not " + newValue + " as expected: Actual(" + dictionary[key] + ")"; TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("009", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: Using customer class which implemented the item property in IDictionay<TKey,TValue>..."; const string c_TEST_ID = "P004"; MyDictionary<int, int> dictionary = new MyDictionary<int, int>(); int key = TestLibrary.Generator.GetInt32(-55); int value = TestLibrary.Generator.GetInt32(-55); int newValue = TestLibrary.Generator.GetInt32(-55); dictionary.Add(key, value); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (((IDictionary<int, int>)dictionary)[key] != value) { string errorDesc = "Value is not " + value + " as expected: Actual(" + dictionary[key] + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } ((IDictionary<int, int>)dictionary)[key] = newValue; if (((IDictionary<int, int>)dictionary)[key] != newValue) { string errorDesc = "Value is not " + newValue + " as expected: Actual(" + dictionary[key] + ")"; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: Using Dictionary<TKey,TValue> which implemented the item property in IDictionay<TKey,TValue> and Key is a null reference..."; const string c_TEST_ID = "N001"; Dictionary<String, int> dictionary = new Dictionary<String, int>(); String key = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int value = ((IDictionary<String, int>)dictionary)[key]; TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "The ArgumentNullException was not thrown as expected"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; const string c_TEST_DESC = "NegTest2: Using Dictionary<TKey,TValue> which implemented the item property in IDictionay<TKey,TValue> and Key is a null reference..."; const string c_TEST_ID = "N002"; Dictionary<String, int> dictionary = new Dictionary<String, int>(); String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int value = ((IDictionary<String, int>)dictionary)[key]; TestLibrary.TestFramework.LogError("015" + "TestId-" + c_TEST_ID, "The KeyNotFoundException was not thrown as expected"); retVal = false; } catch (KeyNotFoundException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; const string c_TEST_DESC = "NegTest3: Using user-defined class which implemented the add method in IDictionay<TKey,TValue> and ReadOnly is true"; const string c_TEST_ID = "N003"; MyDictionary<String, int> dictionary = new MyDictionary<String, int>(); String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); int value = TestLibrary.Generator.GetInt32(-55); int newValue = TestLibrary.Generator.GetInt32(-55); dictionary.Add(key, value); dictionary.readOnly = true; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IDictionary<String, int>)dictionary)[key] = newValue; TestLibrary.TestFramework.LogError("017" + " TestId-" + c_TEST_ID, "The NotSupportedException was not thrown as expected"); retVal = false; } catch (NotSupportedException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyDictionary<TKey, TValue> : IDictionary<TKey, TValue> { private int count; private int capacity = 10; public bool readOnly = false; private KeyValuePair<TKey, TValue>[] keyvaluePair; public MyDictionary() { count = 0; keyvaluePair = new KeyValuePair<TKey, TValue>[capacity]; } #region IDictionary<TKey,TValue> Members public void Add(TKey key, TValue value) { if (readOnly) throw new NotSupportedException(); if (ContainsKey(key)) throw new ArgumentException(); try { KeyValuePair<TKey, TValue> pair = new KeyValuePair<TKey, TValue>(key, value); keyvaluePair[count] = pair; count++; } catch (Exception en) { throw en; } } public bool ContainsKey(TKey key) { bool exist = false; if (key == null) throw new ArgumentNullException(); foreach (KeyValuePair<TKey, TValue> pair in keyvaluePair) { if (pair.Key != null && pair.Key.Equals(key)) { exist = true; } } return exist; } public ICollection<TKey> Keys { get { throw new Exception("The method or operation is not implemented."); } } public bool Remove(TKey key) { throw new Exception("The method or operation is not implemented."); } public bool TryGetValue(TKey key, out TValue value) { throw new Exception("The method or operation is not implemented."); } public ICollection<TValue> Values { get { throw new Exception("The method or operation is not implemented."); } } public TValue this[TKey key] { get { if (!ContainsKey(key)) throw new KeyNotFoundException(); int index = -1; for (int j = 0; j < count; j++) { KeyValuePair<TKey, TValue> pair = keyvaluePair[j]; if (pair.Key.Equals(key)) { index = j; break; } } return keyvaluePair[index].Value; } set { if (readOnly) throw new NotSupportedException(); if (ContainsKey(key)) { int index = -1; for (int j = 0; j < count; j++) { KeyValuePair<TKey, TValue> pair = keyvaluePair[j]; if (pair.Key.Equals(key)) { index = j; break; } } KeyValuePair<TKey, TValue> newpair = new KeyValuePair<TKey, TValue>(key, value); keyvaluePair[index] = newpair; } else { KeyValuePair<TKey, TValue> pair = new KeyValuePair<TKey, TValue>(key, value); keyvaluePair[count] = pair; count++; } } } #endregion #region ICollection<KeyValuePair<TKey,TValue>> Members public void Add(KeyValuePair<TKey, TValue> item) { throw new Exception("The method or operation is not implemented."); } public void Clear() { throw new Exception("The method or operation is not implemented."); } public bool Contains(KeyValuePair<TKey, TValue> item) { throw new Exception("The method or operation is not implemented."); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new Exception("The method or operation is not implemented."); } public int Count { get { return count; } } public bool IsReadOnly { get { throw new Exception("The method or operation is not implemented."); } } public bool Remove(KeyValuePair<TKey, TValue> item) { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerable<KeyValuePair<TKey,TValue>> Members public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion } public class MyClass { } #endregion }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// MachineToMachineResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry { public class MachineToMachineResource : Resource { private static Request BuildReadRequest(ReadMachineToMachineOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/AvailablePhoneNumbers/" + options.PathCountryCode + "/MachineToMachine.json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read MachineToMachine parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of MachineToMachine </returns> public static ResourceSet<MachineToMachineResource> Read(ReadMachineToMachineOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<MachineToMachineResource>.FromJson("available_phone_numbers", response.Content); return new ResourceSet<MachineToMachineResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read MachineToMachine parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of MachineToMachine </returns> public static async System.Threading.Tasks.Task<ResourceSet<MachineToMachineResource>> ReadAsync(ReadMachineToMachineOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<MachineToMachineResource>.FromJson("available_phone_numbers", response.Content); return new ResourceSet<MachineToMachineResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathCountryCode"> The ISO Country code of the country from which to read phone numbers </param> /// <param name="pathAccountSid"> The SID of the Account requesting the AvailablePhoneNumber resources </param> /// <param name="areaCode"> The area code of the phone numbers to read </param> /// <param name="contains"> The pattern on which to match phone numbers </param> /// <param name="smsEnabled"> Whether the phone numbers can receive text messages </param> /// <param name="mmsEnabled"> Whether the phone numbers can receive MMS messages </param> /// <param name="voiceEnabled"> Whether the phone numbers can receive calls. </param> /// <param name="excludeAllAddressRequired"> Whether to exclude phone numbers that require an Address </param> /// <param name="excludeLocalAddressRequired"> Whether to exclude phone numbers that require a local address </param> /// <param name="excludeForeignAddressRequired"> Whether to exclude phone numbers that require a foreign address /// </param> /// <param name="beta"> Whether to read phone numbers new to the Twilio platform </param> /// <param name="nearNumber"> Given a phone number, find a geographically close number within distance miles. /// (US/Canada only) </param> /// <param name="nearLatLong"> Given a latitude/longitude pair lat,long find geographically close numbers within /// distance miles. (US/Canada only) </param> /// <param name="distance"> The search radius, in miles, for a near_ query. (US/Canada only) </param> /// <param name="inPostalCode"> Limit results to a particular postal code. (US/Canada only) </param> /// <param name="inRegion"> Limit results to a particular region. (US/Canada only) </param> /// <param name="inRateCenter"> Limit results to a specific rate center, or given a phone number search within the same /// rate center as that number. (US/Canada only) </param> /// <param name="inLata"> Limit results to a specific local access and transport area. (US/Canada only) </param> /// <param name="inLocality"> Limit results to a particular locality </param> /// <param name="faxEnabled"> Whether the phone numbers can receive faxes </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of MachineToMachine </returns> public static ResourceSet<MachineToMachineResource> Read(string pathCountryCode, string pathAccountSid = null, int? areaCode = null, string contains = null, bool? smsEnabled = null, bool? mmsEnabled = null, bool? voiceEnabled = null, bool? excludeAllAddressRequired = null, bool? excludeLocalAddressRequired = null, bool? excludeForeignAddressRequired = null, bool? beta = null, Types.PhoneNumber nearNumber = null, string nearLatLong = null, int? distance = null, string inPostalCode = null, string inRegion = null, string inRateCenter = null, string inLata = null, string inLocality = null, bool? faxEnabled = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadMachineToMachineOptions(pathCountryCode){PathAccountSid = pathAccountSid, AreaCode = areaCode, Contains = contains, SmsEnabled = smsEnabled, MmsEnabled = mmsEnabled, VoiceEnabled = voiceEnabled, ExcludeAllAddressRequired = excludeAllAddressRequired, ExcludeLocalAddressRequired = excludeLocalAddressRequired, ExcludeForeignAddressRequired = excludeForeignAddressRequired, Beta = beta, NearNumber = nearNumber, NearLatLong = nearLatLong, Distance = distance, InPostalCode = inPostalCode, InRegion = inRegion, InRateCenter = inRateCenter, InLata = inLata, InLocality = inLocality, FaxEnabled = faxEnabled, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathCountryCode"> The ISO Country code of the country from which to read phone numbers </param> /// <param name="pathAccountSid"> The SID of the Account requesting the AvailablePhoneNumber resources </param> /// <param name="areaCode"> The area code of the phone numbers to read </param> /// <param name="contains"> The pattern on which to match phone numbers </param> /// <param name="smsEnabled"> Whether the phone numbers can receive text messages </param> /// <param name="mmsEnabled"> Whether the phone numbers can receive MMS messages </param> /// <param name="voiceEnabled"> Whether the phone numbers can receive calls. </param> /// <param name="excludeAllAddressRequired"> Whether to exclude phone numbers that require an Address </param> /// <param name="excludeLocalAddressRequired"> Whether to exclude phone numbers that require a local address </param> /// <param name="excludeForeignAddressRequired"> Whether to exclude phone numbers that require a foreign address /// </param> /// <param name="beta"> Whether to read phone numbers new to the Twilio platform </param> /// <param name="nearNumber"> Given a phone number, find a geographically close number within distance miles. /// (US/Canada only) </param> /// <param name="nearLatLong"> Given a latitude/longitude pair lat,long find geographically close numbers within /// distance miles. (US/Canada only) </param> /// <param name="distance"> The search radius, in miles, for a near_ query. (US/Canada only) </param> /// <param name="inPostalCode"> Limit results to a particular postal code. (US/Canada only) </param> /// <param name="inRegion"> Limit results to a particular region. (US/Canada only) </param> /// <param name="inRateCenter"> Limit results to a specific rate center, or given a phone number search within the same /// rate center as that number. (US/Canada only) </param> /// <param name="inLata"> Limit results to a specific local access and transport area. (US/Canada only) </param> /// <param name="inLocality"> Limit results to a particular locality </param> /// <param name="faxEnabled"> Whether the phone numbers can receive faxes </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of MachineToMachine </returns> public static async System.Threading.Tasks.Task<ResourceSet<MachineToMachineResource>> ReadAsync(string pathCountryCode, string pathAccountSid = null, int? areaCode = null, string contains = null, bool? smsEnabled = null, bool? mmsEnabled = null, bool? voiceEnabled = null, bool? excludeAllAddressRequired = null, bool? excludeLocalAddressRequired = null, bool? excludeForeignAddressRequired = null, bool? beta = null, Types.PhoneNumber nearNumber = null, string nearLatLong = null, int? distance = null, string inPostalCode = null, string inRegion = null, string inRateCenter = null, string inLata = null, string inLocality = null, bool? faxEnabled = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadMachineToMachineOptions(pathCountryCode){PathAccountSid = pathAccountSid, AreaCode = areaCode, Contains = contains, SmsEnabled = smsEnabled, MmsEnabled = mmsEnabled, VoiceEnabled = voiceEnabled, ExcludeAllAddressRequired = excludeAllAddressRequired, ExcludeLocalAddressRequired = excludeLocalAddressRequired, ExcludeForeignAddressRequired = excludeForeignAddressRequired, Beta = beta, NearNumber = nearNumber, NearLatLong = nearLatLong, Distance = distance, InPostalCode = inPostalCode, InRegion = inRegion, InRateCenter = inRateCenter, InLata = inLata, InLocality = inLocality, FaxEnabled = faxEnabled, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<MachineToMachineResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<MachineToMachineResource>.FromJson("available_phone_numbers", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<MachineToMachineResource> NextPage(Page<MachineToMachineResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<MachineToMachineResource>.FromJson("available_phone_numbers", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<MachineToMachineResource> PreviousPage(Page<MachineToMachineResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<MachineToMachineResource>.FromJson("available_phone_numbers", response.Content); } /// <summary> /// Converts a JSON string into a MachineToMachineResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> MachineToMachineResource object represented by the provided JSON </returns> public static MachineToMachineResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<MachineToMachineResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// A formatted version of the phone number /// </summary> [JsonProperty("friendly_name")] [JsonConverter(typeof(PhoneNumberConverter))] public Types.PhoneNumber FriendlyName { get; private set; } /// <summary> /// The phone number in E.164 format /// </summary> [JsonProperty("phone_number")] [JsonConverter(typeof(PhoneNumberConverter))] public Types.PhoneNumber PhoneNumber { get; private set; } /// <summary> /// The LATA of this phone number /// </summary> [JsonProperty("lata")] public string Lata { get; private set; } /// <summary> /// The locality or city of this phone number's location /// </summary> [JsonProperty("locality")] public string Locality { get; private set; } /// <summary> /// The rate center of this phone number /// </summary> [JsonProperty("rate_center")] public string RateCenter { get; private set; } /// <summary> /// The latitude of this phone number's location /// </summary> [JsonProperty("latitude")] public decimal? Latitude { get; private set; } /// <summary> /// The longitude of this phone number's location /// </summary> [JsonProperty("longitude")] public decimal? Longitude { get; private set; } /// <summary> /// The two-letter state or province abbreviation of this phone number's location /// </summary> [JsonProperty("region")] public string Region { get; private set; } /// <summary> /// The postal or ZIP code of this phone number's location /// </summary> [JsonProperty("postal_code")] public string PostalCode { get; private set; } /// <summary> /// The ISO country code of this phone number /// </summary> [JsonProperty("iso_country")] public string IsoCountry { get; private set; } /// <summary> /// The type of Address resource the phone number requires /// </summary> [JsonProperty("address_requirements")] public string AddressRequirements { get; private set; } /// <summary> /// Whether the phone number is new to the Twilio platform /// </summary> [JsonProperty("beta")] public bool? Beta { get; private set; } /// <summary> /// Whether a phone number can receive calls or messages /// </summary> [JsonProperty("capabilities")] public PhoneNumberCapabilities Capabilities { get; private set; } private MachineToMachineResource() { } } }
/* * OANDA v20 REST API * * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. * * OpenAPI spec version: 3.0.15 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace Oanda.RestV20.Model { /// <summary> /// A MarginCallEnterTransaction is created when an Account enters the margin call state. /// </summary> [DataContract] public partial class MarginCallEnterTransaction : IEquatable<MarginCallEnterTransaction>, IValidatableObject { /// <summary> /// The Type of the Transaction. Always set to \"MARGIN_CALL_ENTER\" for an MarginCallEnterTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"MARGIN_CALL_ENTER\" for an MarginCallEnterTransaction.</value> [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { /// <summary> /// Enum CREATE for "CREATE" /// </summary> [EnumMember(Value = "CREATE")] CREATE, /// <summary> /// Enum CLOSE for "CLOSE" /// </summary> [EnumMember(Value = "CLOSE")] CLOSE, /// <summary> /// Enum REOPEN for "REOPEN" /// </summary> [EnumMember(Value = "REOPEN")] REOPEN, /// <summary> /// Enum CLIENTCONFIGURE for "CLIENT_CONFIGURE" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE")] CLIENTCONFIGURE, /// <summary> /// Enum CLIENTCONFIGUREREJECT for "CLIENT_CONFIGURE_REJECT" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE_REJECT")] CLIENTCONFIGUREREJECT, /// <summary> /// Enum TRANSFERFUNDS for "TRANSFER_FUNDS" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS")] TRANSFERFUNDS, /// <summary> /// Enum TRANSFERFUNDSREJECT for "TRANSFER_FUNDS_REJECT" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS_REJECT")] TRANSFERFUNDSREJECT, /// <summary> /// Enum MARKETORDER for "MARKET_ORDER" /// </summary> [EnumMember(Value = "MARKET_ORDER")] MARKETORDER, /// <summary> /// Enum MARKETORDERREJECT for "MARKET_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_ORDER_REJECT")] MARKETORDERREJECT, /// <summary> /// Enum LIMITORDER for "LIMIT_ORDER" /// </summary> [EnumMember(Value = "LIMIT_ORDER")] LIMITORDER, /// <summary> /// Enum LIMITORDERREJECT for "LIMIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "LIMIT_ORDER_REJECT")] LIMITORDERREJECT, /// <summary> /// Enum STOPORDER for "STOP_ORDER" /// </summary> [EnumMember(Value = "STOP_ORDER")] STOPORDER, /// <summary> /// Enum STOPORDERREJECT for "STOP_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_ORDER_REJECT")] STOPORDERREJECT, /// <summary> /// Enum MARKETIFTOUCHEDORDER for "MARKET_IF_TOUCHED_ORDER" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER")] MARKETIFTOUCHEDORDER, /// <summary> /// Enum MARKETIFTOUCHEDORDERREJECT for "MARKET_IF_TOUCHED_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER_REJECT")] MARKETIFTOUCHEDORDERREJECT, /// <summary> /// Enum TAKEPROFITORDER for "TAKE_PROFIT_ORDER" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER")] TAKEPROFITORDER, /// <summary> /// Enum TAKEPROFITORDERREJECT for "TAKE_PROFIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER_REJECT")] TAKEPROFITORDERREJECT, /// <summary> /// Enum STOPLOSSORDER for "STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER")] STOPLOSSORDER, /// <summary> /// Enum STOPLOSSORDERREJECT for "STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER_REJECT")] STOPLOSSORDERREJECT, /// <summary> /// Enum TRAILINGSTOPLOSSORDER for "TRAILING_STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER")] TRAILINGSTOPLOSSORDER, /// <summary> /// Enum TRAILINGSTOPLOSSORDERREJECT for "TRAILING_STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER_REJECT")] TRAILINGSTOPLOSSORDERREJECT, /// <summary> /// Enum ORDERFILL for "ORDER_FILL" /// </summary> [EnumMember(Value = "ORDER_FILL")] ORDERFILL, /// <summary> /// Enum ORDERCANCEL for "ORDER_CANCEL" /// </summary> [EnumMember(Value = "ORDER_CANCEL")] ORDERCANCEL, /// <summary> /// Enum ORDERCANCELREJECT for "ORDER_CANCEL_REJECT" /// </summary> [EnumMember(Value = "ORDER_CANCEL_REJECT")] ORDERCANCELREJECT, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFY for "ORDER_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY")] ORDERCLIENTEXTENSIONSMODIFY, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFYREJECT for "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT")] ORDERCLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFY for "TRADE_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY")] TRADECLIENTEXTENSIONSMODIFY, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFYREJECT for "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT")] TRADECLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum MARGINCALLENTER for "MARGIN_CALL_ENTER" /// </summary> [EnumMember(Value = "MARGIN_CALL_ENTER")] MARGINCALLENTER, /// <summary> /// Enum MARGINCALLEXTEND for "MARGIN_CALL_EXTEND" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXTEND")] MARGINCALLEXTEND, /// <summary> /// Enum MARGINCALLEXIT for "MARGIN_CALL_EXIT" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXIT")] MARGINCALLEXIT, /// <summary> /// Enum DELAYEDTRADECLOSURE for "DELAYED_TRADE_CLOSURE" /// </summary> [EnumMember(Value = "DELAYED_TRADE_CLOSURE")] DELAYEDTRADECLOSURE, /// <summary> /// Enum DAILYFINANCING for "DAILY_FINANCING" /// </summary> [EnumMember(Value = "DAILY_FINANCING")] DAILYFINANCING, /// <summary> /// Enum RESETRESETTABLEPL for "RESET_RESETTABLE_PL" /// </summary> [EnumMember(Value = "RESET_RESETTABLE_PL")] RESETRESETTABLEPL } /// <summary> /// The Type of the Transaction. Always set to \"MARGIN_CALL_ENTER\" for an MarginCallEnterTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"MARGIN_CALL_ENTER\" for an MarginCallEnterTransaction.</value> [DataMember(Name="type", EmitDefaultValue=false)] public TypeEnum? Type { get; set; } /// <summary> /// Initializes a new instance of the <see cref="MarginCallEnterTransaction" /> class. /// </summary> /// <param name="Id">The Transaction&#39;s Identifier..</param> /// <param name="Time">The date/time when the Transaction was created..</param> /// <param name="UserID">The ID of the user that initiated the creation of the Transaction..</param> /// <param name="AccountID">The ID of the Account the Transaction was created for..</param> /// <param name="BatchID">The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously..</param> /// <param name="RequestID">The Request ID of the request which generated the transaction..</param> /// <param name="Type">The Type of the Transaction. Always set to \&quot;MARGIN_CALL_ENTER\&quot; for an MarginCallEnterTransaction..</param> public MarginCallEnterTransaction(string Id = default(string), string Time = default(string), int? UserID = default(int?), string AccountID = default(string), string BatchID = default(string), string RequestID = default(string), TypeEnum? Type = default(TypeEnum?)) { this.Id = Id; this.Time = Time; this.UserID = UserID; this.AccountID = AccountID; this.BatchID = BatchID; this.RequestID = RequestID; this.Type = Type; } /// <summary> /// The Transaction&#39;s Identifier. /// </summary> /// <value>The Transaction&#39;s Identifier.</value> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// The date/time when the Transaction was created. /// </summary> /// <value>The date/time when the Transaction was created.</value> [DataMember(Name="time", EmitDefaultValue=false)] public string Time { get; set; } /// <summary> /// The ID of the user that initiated the creation of the Transaction. /// </summary> /// <value>The ID of the user that initiated the creation of the Transaction.</value> [DataMember(Name="userID", EmitDefaultValue=false)] public int? UserID { get; set; } /// <summary> /// The ID of the Account the Transaction was created for. /// </summary> /// <value>The ID of the Account the Transaction was created for.</value> [DataMember(Name="accountID", EmitDefaultValue=false)] public string AccountID { get; set; } /// <summary> /// The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously. /// </summary> /// <value>The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously.</value> [DataMember(Name="batchID", EmitDefaultValue=false)] public string BatchID { get; set; } /// <summary> /// The Request ID of the request which generated the transaction. /// </summary> /// <value>The Request ID of the request which generated the transaction.</value> [DataMember(Name="requestID", EmitDefaultValue=false)] public string RequestID { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class MarginCallEnterTransaction {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Time: ").Append(Time).Append("\n"); sb.Append(" UserID: ").Append(UserID).Append("\n"); sb.Append(" AccountID: ").Append(AccountID).Append("\n"); sb.Append(" BatchID: ").Append(BatchID).Append("\n"); sb.Append(" RequestID: ").Append(RequestID).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as MarginCallEnterTransaction); } /// <summary> /// Returns true if MarginCallEnterTransaction instances are equal /// </summary> /// <param name="other">Instance of MarginCallEnterTransaction to be compared</param> /// <returns>Boolean</returns> public bool Equals(MarginCallEnterTransaction other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Time == other.Time || this.Time != null && this.Time.Equals(other.Time) ) && ( this.UserID == other.UserID || this.UserID != null && this.UserID.Equals(other.UserID) ) && ( this.AccountID == other.AccountID || this.AccountID != null && this.AccountID.Equals(other.AccountID) ) && ( this.BatchID == other.BatchID || this.BatchID != null && this.BatchID.Equals(other.BatchID) ) && ( this.RequestID == other.RequestID || this.RequestID != null && this.RequestID.Equals(other.RequestID) ) && ( this.Type == other.Type || this.Type != null && this.Type.Equals(other.Type) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Time != null) hash = hash * 59 + this.Time.GetHashCode(); if (this.UserID != null) hash = hash * 59 + this.UserID.GetHashCode(); if (this.AccountID != null) hash = hash * 59 + this.AccountID.GetHashCode(); if (this.BatchID != null) hash = hash * 59 + this.BatchID.GetHashCode(); if (this.RequestID != null) hash = hash * 59 + this.RequestID.GetHashCode(); if (this.Type != null) hash = hash * 59 + this.Type.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.IO; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Xml; using System.Text; using System.Text.RegularExpressions; using System.Management.Automation.Help; using System.Reflection; namespace System.Management.Automation { /// <summary> /// Parses help comments and turns them into HelpInfo objects /// </summary> internal class HelpCommentsParser { private HelpCommentsParser() { } private HelpCommentsParser(List<string> parameterDescriptions) { _parameterDescriptions = parameterDescriptions; } private HelpCommentsParser(CommandInfo commandInfo, List<string> parameterDescriptions) { FunctionInfo fi = commandInfo as FunctionInfo; if (fi != null) { _scriptBlock = fi.ScriptBlock; _commandName = fi.Name; } else { ExternalScriptInfo si = commandInfo as ExternalScriptInfo; if (si != null) { _scriptBlock = si.ScriptBlock; _commandName = si.Path; } } _commandMetadata = commandInfo.CommandMetadata; _parameterDescriptions = parameterDescriptions; } private readonly Language.CommentHelpInfo _sections = new Language.CommentHelpInfo(); private readonly Dictionary<string, string> _parameters = new Dictionary<string, string>(); private readonly List<string> _examples = new List<string>(); private readonly List<string> _inputs = new List<string>(); private readonly List<string> _outputs = new List<string>(); private readonly List<string> _links = new List<string>(); internal bool isExternalHelpSet = false; private ScriptBlock _scriptBlock; private CommandMetadata _commandMetadata; private string _commandName; private List<string> _parameterDescriptions; private XmlDocument _doc; internal static readonly string mamlURI = "http://schemas.microsoft.com/maml/2004/10"; internal static readonly string commandURI = "http://schemas.microsoft.com/maml/dev/command/2004/10"; internal static readonly string devURI = "http://schemas.microsoft.com/maml/dev/2004/10"; private const string directive = @"^\s*\.(\w+)(\s+(\S.*))?\s*$"; private const string blankline = @"^\s*$"; internal static readonly string ProviderHelpCommandXPath = "/helpItems/providerHelp/CmdletHelpPaths/CmdletHelpPath{0}/command:command[command:details/command:verb='{1}' and command:details/command:noun='{2}']"; private void DetermineParameterDescriptions() { int i = 0; foreach (string parameterName in _commandMetadata.StaticCommandParameterMetadata.BindableParameters.Keys) { string description; if (!_parameters.TryGetValue(parameterName.ToUpperInvariant(), out description)) { if (i < _parameterDescriptions.Count) { _parameters.Add(parameterName.ToUpperInvariant(), _parameterDescriptions[i]); } } ++i; } } private string GetParameterDescription(string parameterName) { Diagnostics.Assert(!string.IsNullOrEmpty(parameterName), "Parameter name must not be empty"); string description; _parameters.TryGetValue(parameterName.ToUpperInvariant(), out description); return description; } private XmlElement BuildXmlForParameter( string parameterName, bool isMandatory, bool valueFromPipeline, bool valueFromPipelineByPropertyName, string position, Type type, string description, bool supportsWildcards, string defaultValue, bool forSyntax) { XmlElement command_parameter = _doc.CreateElement("command:parameter", commandURI); command_parameter.SetAttribute("required", isMandatory ? "true" : "false"); //command_parameter.SetAttribute("variableLength", "unknown"); command_parameter.SetAttribute("globbing", supportsWildcards ? "true" : "false"); string fromPipeline; if (valueFromPipeline && valueFromPipelineByPropertyName) { fromPipeline = "true (ByValue, ByPropertyName)"; } else if (valueFromPipeline) { fromPipeline = "true (ByValue)"; } else if (valueFromPipelineByPropertyName) { fromPipeline = "true (ByPropertyName)"; } else { fromPipeline = "false"; } command_parameter.SetAttribute("pipelineInput", fromPipeline); command_parameter.SetAttribute("position", position); XmlElement name = _doc.CreateElement("maml:name", mamlURI); XmlText name_text = _doc.CreateTextNode(parameterName); command_parameter.AppendChild(name).AppendChild(name_text); if (!string.IsNullOrEmpty(description)) { XmlElement maml_description = _doc.CreateElement("maml:description", mamlURI); XmlElement maml_para = _doc.CreateElement("maml:para", mamlURI); XmlText maml_para_text = _doc.CreateTextNode(description); command_parameter.AppendChild(maml_description).AppendChild(maml_para).AppendChild(maml_para_text); } if (type == null) type = typeof(object); var typeInfo = type.GetTypeInfo(); var elementType = typeInfo.IsArray ? typeInfo.GetElementType() : type; if (elementType.GetTypeInfo().IsEnum) { XmlElement parameterValueGroup = _doc.CreateElement("command:parameterValueGroup", commandURI); foreach (string valueName in Enum.GetNames(elementType)) { XmlElement parameterValue = _doc.CreateElement("command:parameterValue", commandURI); parameterValue.SetAttribute("required", "false"); XmlText parameterValue_text = _doc.CreateTextNode(valueName); parameterValueGroup.AppendChild(parameterValue).AppendChild(parameterValue_text); } command_parameter.AppendChild(parameterValueGroup); } else { bool isSwitchParameter = elementType == typeof(SwitchParameter); if (!forSyntax || !isSwitchParameter) { XmlElement parameterValue = _doc.CreateElement("command:parameterValue", commandURI); parameterValue.SetAttribute("required", isSwitchParameter ? "false" : "true"); //parameterValue.SetAttribute("variableLength", "unknown"); XmlText parameterValue_text = _doc.CreateTextNode(type.Name); command_parameter.AppendChild(parameterValue).AppendChild(parameterValue_text); } } if (!forSyntax) { XmlElement devType = _doc.CreateElement("dev:type", devURI); XmlElement typeName = _doc.CreateElement("maml:name", mamlURI); XmlText typeName_text = _doc.CreateTextNode(type.Name); command_parameter.AppendChild(devType).AppendChild(typeName).AppendChild(typeName_text); XmlElement defaultValueElement = _doc.CreateElement("dev:defaultValue", devURI); XmlText defaultValue_text = _doc.CreateTextNode(defaultValue); command_parameter.AppendChild(defaultValueElement).AppendChild(defaultValue_text); } return command_parameter; } /// <summary> /// Create the maml xml after a successful analysis of the comments. /// </summary> /// <returns>The xml node for the command constructed</returns> internal XmlDocument BuildXmlFromComments() { Diagnostics.Assert(!string.IsNullOrEmpty(_commandName), "Name can never be null"); _doc = new XmlDocument(); XmlElement command = _doc.CreateElement("command:command", commandURI); command.SetAttribute("xmlns:maml", mamlURI); command.SetAttribute("xmlns:command", commandURI); command.SetAttribute("xmlns:dev", devURI); _doc.AppendChild(command); XmlElement details = _doc.CreateElement("command:details", commandURI); command.AppendChild(details); XmlElement name = _doc.CreateElement("command:name", commandURI); XmlText name_text = _doc.CreateTextNode(_commandName); details.AppendChild(name).AppendChild(name_text); if (!string.IsNullOrEmpty(_sections.Synopsis)) { XmlElement synopsis = _doc.CreateElement("maml:description", mamlURI); XmlElement synopsis_para = _doc.CreateElement("maml:para", mamlURI); XmlText synopsis_text = _doc.CreateTextNode(_sections.Synopsis); details.AppendChild(synopsis).AppendChild(synopsis_para).AppendChild(synopsis_text); } #region Syntax // The syntax is automatically generated from parameter metadata DetermineParameterDescriptions(); XmlElement syntax = _doc.CreateElement("command:syntax", commandURI); MergedCommandParameterMetadata parameterMetadata = _commandMetadata.StaticCommandParameterMetadata; if (parameterMetadata.ParameterSetCount > 0) { for (int i = 0; i < parameterMetadata.ParameterSetCount; ++i) { BuildSyntaxForParameterSet(command, syntax, parameterMetadata, i); } } else { BuildSyntaxForParameterSet(command, syntax, parameterMetadata, int.MaxValue); } #endregion Syntax #region Parameters XmlElement commandParameters = _doc.CreateElement("command:parameters", commandURI); foreach (KeyValuePair<string, MergedCompiledCommandParameter> pair in parameterMetadata.BindableParameters) { MergedCompiledCommandParameter mergedParameter = pair.Value; if (mergedParameter.BinderAssociation == ParameterBinderAssociation.CommonParameters) { continue; } string parameterName = pair.Key; string description = GetParameterDescription(parameterName); ParameterSetSpecificMetadata parameterSetData; bool isMandatory = false; bool valueFromPipeline = false; bool valueFromPipelineByPropertyName = false; string position = "named"; int i = 0; CompiledCommandParameter parameter = mergedParameter.Parameter; parameter.ParameterSetData.TryGetValue(ParameterAttribute.AllParameterSets, out parameterSetData); while (parameterSetData == null && i < 32) { parameterSetData = parameter.GetParameterSetData(1u << i++); } if (parameterSetData != null) { isMandatory = parameterSetData.IsMandatory; valueFromPipeline = parameterSetData.ValueFromPipeline; valueFromPipelineByPropertyName = parameterSetData.ValueFromPipelineByPropertyName; position = parameterSetData.IsPositional ? (1 + parameterSetData.Position).ToString(CultureInfo.InvariantCulture) : "named"; } var compiledAttributes = parameter.CompiledAttributes; bool supportsWildcards = compiledAttributes.OfType<SupportsWildcardsAttribute>().Any(); string defaultValueStr = ""; object defaultValue = null; var defaultValueAttribute = compiledAttributes.OfType<PSDefaultValueAttribute>().FirstOrDefault(); if (defaultValueAttribute != null) { defaultValueStr = defaultValueAttribute.Help; if (string.IsNullOrEmpty(defaultValueStr)) { defaultValue = defaultValueAttribute.Value; } } if (string.IsNullOrEmpty(defaultValueStr)) { if (defaultValue == null) { RuntimeDefinedParameter rdp; if (_scriptBlock.RuntimeDefinedParameters.TryGetValue(parameterName, out rdp)) { defaultValue = rdp.Value; } } var wrapper = defaultValue as Compiler.DefaultValueExpressionWrapper; if (wrapper != null) { defaultValueStr = wrapper.Expression.Extent.Text; } else if (defaultValue != null) { defaultValueStr = PSObject.ToStringParser(null, defaultValue); } } XmlElement parameterElement = BuildXmlForParameter(parameterName, isMandatory, valueFromPipeline, valueFromPipelineByPropertyName, position, parameter.Type, description, supportsWildcards, defaultValueStr, forSyntax: false); commandParameters.AppendChild(parameterElement); } command.AppendChild(commandParameters); #endregion Parameters if (!string.IsNullOrEmpty(_sections.Description)) { XmlElement description = _doc.CreateElement("maml:description", mamlURI); XmlElement description_para = _doc.CreateElement("maml:para", mamlURI); XmlText description_text = _doc.CreateTextNode(_sections.Description); command.AppendChild(description).AppendChild(description_para).AppendChild(description_text); } if (!string.IsNullOrEmpty(_sections.Notes)) { XmlElement alertSet = _doc.CreateElement("maml:alertSet", mamlURI); XmlElement alert = _doc.CreateElement("maml:alert", mamlURI); XmlElement alert_para = _doc.CreateElement("maml:para", mamlURI); XmlText alert_para_text = _doc.CreateTextNode(_sections.Notes); command.AppendChild(alertSet).AppendChild(alert).AppendChild(alert_para).AppendChild(alert_para_text); } if (_examples.Count > 0) { XmlElement examples = _doc.CreateElement("command:examples", commandURI); int count = 1; foreach (string example in _examples) { XmlElement example_node = _doc.CreateElement("command:example", commandURI); // The title is automatically generated XmlElement title = _doc.CreateElement("maml:title", mamlURI); string titleStr = string.Format(CultureInfo.InvariantCulture, " -------------------------- {0} {1} --------------------------", HelpDisplayStrings.ExampleUpperCase, count++); XmlText title_text = _doc.CreateTextNode(titleStr); example_node.AppendChild(title).AppendChild(title_text); string prompt_str; string code_str; string remarks_str; GetExampleSections(example, out prompt_str, out code_str, out remarks_str); // Introduction (usually the prompt) XmlElement introduction = _doc.CreateElement("maml:introduction", mamlURI); XmlElement introduction_para = _doc.CreateElement("maml:para", mamlURI); XmlText introduction_para_text = _doc.CreateTextNode(prompt_str); example_node.AppendChild(introduction).AppendChild(introduction_para).AppendChild(introduction_para_text); // Example code XmlElement code = _doc.CreateElement("dev:code", devURI); XmlText code_text = _doc.CreateTextNode(code_str); example_node.AppendChild(code).AppendChild(code_text); // Remarks are comments on the example XmlElement remarks = _doc.CreateElement("dev:remarks", devURI); XmlElement remarks_para = _doc.CreateElement("maml:para", mamlURI); XmlText remarks_para_text = _doc.CreateTextNode(remarks_str); example_node.AppendChild(remarks).AppendChild(remarks_para).AppendChild(remarks_para_text); // The convention is to have 4 blank paras after the example for spacing for (int i = 0; i < 4; i++) { remarks.AppendChild(_doc.CreateElement("maml:para", mamlURI)); } examples.AppendChild(example_node); } command.AppendChild(examples); } if (_inputs.Count > 0) { XmlElement inputTypes = _doc.CreateElement("command:inputTypes", commandURI); foreach (string inputStr in _inputs) { XmlElement inputType = _doc.CreateElement("command:inputType", commandURI); XmlElement type = _doc.CreateElement("dev:type", devURI); XmlElement maml_name = _doc.CreateElement("maml:name", mamlURI); XmlText maml_name_text = _doc.CreateTextNode(inputStr); inputTypes.AppendChild(inputType).AppendChild(type).AppendChild(maml_name).AppendChild(maml_name_text); } command.AppendChild(inputTypes); } // For outputs, we prefer what was specified in the comments, but if there are no comments // and the OutputType attribute was specified, we'll use those instead. IEnumerable outputs = null; if (_outputs.Count > 0) { outputs = _outputs; } else if (_scriptBlock.OutputType.Count > 0) { outputs = _scriptBlock.OutputType; } if (outputs != null) { XmlElement returnValues = _doc.CreateElement("command:returnValues", commandURI); foreach (object output in outputs) { XmlElement returnValue = _doc.CreateElement("command:returnValue", commandURI); XmlElement type = _doc.CreateElement("dev:type", devURI); XmlElement maml_name = _doc.CreateElement("maml:name", mamlURI); string returnValueStr = output as string ?? ((PSTypeName)output).Name; XmlText maml_name_text = _doc.CreateTextNode(returnValueStr); returnValues.AppendChild(returnValue).AppendChild(type).AppendChild(maml_name).AppendChild(maml_name_text); } command.AppendChild(returnValues); } if (_links.Count > 0) { XmlElement links = _doc.CreateElement("maml:relatedLinks", mamlURI); foreach (string link in _links) { XmlElement navigationLink = _doc.CreateElement("maml:navigationLink", mamlURI); bool isOnlineHelp = Uri.IsWellFormedUriString(Uri.EscapeUriString(link), UriKind.Absolute); string nodeName = isOnlineHelp ? "maml:uri" : "maml:linkText"; XmlElement linkText = _doc.CreateElement(nodeName, mamlURI); XmlText linkText_text = _doc.CreateTextNode(link); links.AppendChild(navigationLink).AppendChild(linkText).AppendChild(linkText_text); } command.AppendChild(links); } return _doc; } private void BuildSyntaxForParameterSet(XmlElement command, XmlElement syntax, MergedCommandParameterMetadata parameterMetadata, int i) { XmlElement syntaxItem = _doc.CreateElement("command:syntaxItem", commandURI); XmlElement syntaxItemName = _doc.CreateElement("maml:name", mamlURI); XmlText syntaxItemName_text = _doc.CreateTextNode(_commandName); syntaxItem.AppendChild(syntaxItemName).AppendChild(syntaxItemName_text); Collection<MergedCompiledCommandParameter> compiledParameters = parameterMetadata.GetParametersInParameterSet(1u << i); foreach (MergedCompiledCommandParameter mergedParameter in compiledParameters) { if (mergedParameter.BinderAssociation == ParameterBinderAssociation.CommonParameters) { continue; } CompiledCommandParameter parameter = mergedParameter.Parameter; ParameterSetSpecificMetadata parameterSetData = parameter.GetParameterSetData(1u << i); string description = GetParameterDescription(parameter.Name); bool supportsWildcards = parameter.CompiledAttributes.Any(attribute => attribute is SupportsWildcardsAttribute); XmlElement parameterElement = BuildXmlForParameter(parameter.Name, parameterSetData.IsMandatory, parameterSetData.ValueFromPipeline, parameterSetData.ValueFromPipelineByPropertyName, parameterSetData.IsPositional ? (1 + parameterSetData.Position).ToString(CultureInfo.InvariantCulture) : "named", parameter.Type, description, supportsWildcards, defaultValue: "", forSyntax: true); syntaxItem.AppendChild(parameterElement); } command.AppendChild(syntax).AppendChild(syntaxItem); } private static void GetExampleSections(string content, out string prompt_str, out string code_str, out string remarks_str) { prompt_str = code_str = ""; StringBuilder builder = new StringBuilder(); int collectingPart = 1; foreach (char c in content) { if (c == '>' && collectingPart == 1) { builder.Append(c); prompt_str = builder.ToString().Trim(); builder = new StringBuilder(); ++collectingPart; continue; } if (c == '\n' && collectingPart < 3) { if (collectingPart == 1) { prompt_str = "PS C:\\>"; } code_str = builder.ToString().Trim(); builder = new StringBuilder(); collectingPart = 3; continue; } builder.Append(c); } if (collectingPart == 1) { prompt_str = "PS C:\\>"; code_str = builder.ToString().Trim(); remarks_str = ""; } else { remarks_str = builder.ToString(); } } /// <summary> /// Split the text in the comment token into multiple lines, appending commentLines. /// </summary> /// <param name="comment">A single line or multiline comment token</param> /// <param name="commentLines"></param> private static void CollectCommentText(Token comment, List<string> commentLines) { string text = comment.Text; CollectCommentText(text, commentLines); } private static void CollectCommentText(string text, List<string> commentLines) { int i = 0; if (text[0] == '<') { int start = 2; // The full text includes '<#', so start at index 2 to skip those characters, // and the full text also includes '#>' at the end, so skip those as well. for (i = 2; i < text.Length - 2; i++) { if (text[i] == '\n') { commentLines.Add(text.Substring(start, i - start)); start = i + 1; } else if (text[i] == '\r') { commentLines.Add(text.Substring(start, i - start)); // No need to check length here, comment text has at least '#>' at the end. if (text[i + 1] == '\n') { i++; } start = i + 1; } } commentLines.Add(text.Substring(start, i - start)); } else { for (; i < text.Length; i++) { // Skip all leading '#' characters as it is a common convention // to use more than one '#' character. if (text[i] != '#') { break; } } commentLines.Add(text.Substring(i)); } } /// <summary> /// Collect the text of a section. Stop collecting the section /// when a new directive is found (even if it is an unknown directive). /// </summary> /// <param name="commentLines">The comment block, as a list of lines.</param> /// <param name="i"></param> /// <returns>The text of the help section, with 'i' left on the last line collected.</returns> private static string GetSection(List<string> commentLines, ref int i) { bool capturing = false; int countLeadingWS = 0; StringBuilder sb = new StringBuilder(); const char nbsp = (char)0xA0; for (i++; i < commentLines.Count; i++) { string line = commentLines[i]; if (!capturing && Regex.IsMatch(line, blankline)) { // Skip blank lines before capturing anything in the section. continue; } if (Regex.IsMatch(line, directive)) { // Break on any directive even if we haven't started capturing. i--; break; } // The first line of a section sets how much whitespace we'll ignore (and hence strip). if (!capturing) { int j = 0; while (j < line.Length && (line[j] == ' ' || line[j] == '\t' || line[j] == nbsp)) { countLeadingWS++; j++; } } capturing = true; // Skip leading whitespace based on the first line in the section, skipping // only as much whitespace as the first line had, no more (and possibly less.) int start = 0; while (start < line.Length && start < countLeadingWS && (line[start] == ' ' || line[start] == '\t' || line[start] == nbsp)) { start++; } sb.Append(line.Substring(start)); sb.Append('\n'); } return sb.ToString(); } internal string GetHelpFile(CommandInfo commandInfo) { if (_sections.MamlHelpFile == null) { return null; } string helpFileToLoad = _sections.MamlHelpFile; Collection<String> searchPaths = new Collection<String>(); string scriptFile = ((IScriptCommandInfo)commandInfo).ScriptBlock.File; if (!string.IsNullOrEmpty(scriptFile)) { helpFileToLoad = Path.Combine(Path.GetDirectoryName(scriptFile), _sections.MamlHelpFile); } else if (commandInfo.Module != null) { helpFileToLoad = Path.Combine(Path.GetDirectoryName(commandInfo.Module.Path), _sections.MamlHelpFile); } string location = MUIFileSearcher.LocateFile(helpFileToLoad, searchPaths); return location; } internal RemoteHelpInfo GetRemoteHelpInfo(ExecutionContext context, CommandInfo commandInfo) { if (string.IsNullOrEmpty(_sections.ForwardHelpTargetName) || string.IsNullOrEmpty(_sections.RemoteHelpRunspace)) { return null; } // get the PSSession object from the variable specified in the comments IScriptCommandInfo scriptCommandInfo = (IScriptCommandInfo)commandInfo; SessionState sessionState = scriptCommandInfo.ScriptBlock.SessionState; object runspaceInfoAsObject = sessionState.PSVariable.GetValue(_sections.RemoteHelpRunspace); PSSession runspaceInfo; if (runspaceInfoAsObject == null || !LanguagePrimitives.TryConvertTo(runspaceInfoAsObject, out runspaceInfo)) { string errorMessage = HelpErrors.RemoteRunspaceNotAvailable; throw new InvalidOperationException(errorMessage); } return new RemoteHelpInfo( context, (RemoteRunspace)runspaceInfo.Runspace, commandInfo.Name, _sections.ForwardHelpTargetName, _sections.ForwardHelpCategory, commandInfo.HelpCategory); } /// <summary> /// Look for special comments indicating the comment block is meant /// to be used for help. /// </summary> /// <param name="comments">The list of comments to process</param> /// <returns>True if any special comments are found, false otherwise.</returns> internal bool AnalyzeCommentBlock(List<Token> comments) { if (comments == null || comments.Count == 0) { return false; } List<string> commentLines = new List<string>(); foreach (Token comment in comments) { CollectCommentText(comment, commentLines); } return AnalyzeCommentBlock(commentLines); } private bool AnalyzeCommentBlock(List<string> commentLines) { bool directiveFound = false; for (int i = 0; i < commentLines.Count; i++) { Match match = Regex.Match(commentLines[i], directive); if (match.Success) { directiveFound = true; if (match.Groups[3].Success) { switch (match.Groups[1].Value.ToUpperInvariant()) { case "PARAMETER": { string param = match.Groups[3].Value.ToUpperInvariant().Trim(); string section = GetSection(commentLines, ref i); if (!_parameters.ContainsKey(param)) { _parameters.Add(param, section); } break; } case "FORWARDHELPTARGETNAME": _sections.ForwardHelpTargetName = match.Groups[3].Value.Trim(); break; case "FORWARDHELPCATEGORY": _sections.ForwardHelpCategory = match.Groups[3].Value.Trim(); break; case "REMOTEHELPRUNSPACE": _sections.RemoteHelpRunspace = match.Groups[3].Value.Trim(); break; case "EXTERNALHELP": _sections.MamlHelpFile = match.Groups[3].Value.Trim(); isExternalHelpSet = true; break; default: return false; } } else { switch (match.Groups[1].Value.ToUpperInvariant()) { case "SYNOPSIS": _sections.Synopsis = GetSection(commentLines, ref i); break; case "DESCRIPTION": _sections.Description = GetSection(commentLines, ref i); break; case "NOTES": _sections.Notes = GetSection(commentLines, ref i); break; case "LINK": _links.Add(GetSection(commentLines, ref i).Trim()); break; case "EXAMPLE": _examples.Add(GetSection(commentLines, ref i)); break; case "INPUTS": _inputs.Add(GetSection(commentLines, ref i)); break; case "OUTPUTS": _outputs.Add(GetSection(commentLines, ref i)); break; case "COMPONENT": _sections.Component = GetSection(commentLines, ref i).Trim(); break; case "ROLE": _sections.Role = GetSection(commentLines, ref i).Trim(); break; case "FUNCTIONALITY": _sections.Functionality = GetSection(commentLines, ref i).Trim(); break; default: return false; } } } else if (!Regex.IsMatch(commentLines[i], blankline)) { return false; } } _sections.Examples = new ReadOnlyCollection<string>(_examples); _sections.Inputs = new ReadOnlyCollection<string>(_inputs); _sections.Outputs = new ReadOnlyCollection<string>(_outputs); _sections.Links = new ReadOnlyCollection<string>(_links); // TODO, Changing this to an IDictionary because ReadOnlyDictionary is available only in .NET 4.5 // This is a temporary workaround and will be fixed later. Tracked by Win8: 354135 _sections.Parameters = new Dictionary<string, string>(_parameters); return directiveFound; } /// <summary> /// The analysis of the comments finds the component, functionality, and role fields, but /// those fields aren't added to the xml because they aren't children of the command xml /// node, they are under a sibling of the command xml node and apply to all command nodes /// in a maml file. /// </summary> /// <param name="helpInfo">The helpInfo object to set the fields on.</param> internal void SetAdditionalData(MamlCommandHelpInfo helpInfo) { helpInfo.SetAdditionalDataFromHelpComment( _sections.Component, _sections.Functionality, _sections.Role); } internal static CommentHelpInfo GetHelpContents(List<Language.Token> comments, List<string> parameterDescriptions) { HelpCommentsParser helpCommentsParser = new HelpCommentsParser(parameterDescriptions); helpCommentsParser.AnalyzeCommentBlock(comments); return helpCommentsParser._sections; } internal static HelpInfo CreateFromComments(ExecutionContext context, CommandInfo commandInfo, List<Language.Token> comments, List<string> parameterDescriptions, bool dontSearchOnRemoteComputer, out string helpFile, out string helpUriFromDotLink) { HelpCommentsParser helpCommentsParser = new HelpCommentsParser(commandInfo, parameterDescriptions); helpCommentsParser.AnalyzeCommentBlock(comments); if (helpCommentsParser._sections.Links != null && helpCommentsParser._sections.Links.Count != 0) { helpUriFromDotLink = helpCommentsParser._sections.Links[0]; } else { helpUriFromDotLink = null; } helpFile = helpCommentsParser.GetHelpFile(commandInfo); // If only .ExternalHelp is defined and the help file is not found, then we // use the metadata driven help if (comments.Count == 1 && helpCommentsParser.isExternalHelpSet && helpFile == null) { return null; } return CreateFromComments(context, commandInfo, helpCommentsParser, dontSearchOnRemoteComputer); } internal static HelpInfo CreateFromComments(ExecutionContext context, CommandInfo commandInfo, HelpCommentsParser helpCommentsParser, bool dontSearchOnRemoteComputer) { if (!dontSearchOnRemoteComputer) { RemoteHelpInfo remoteHelpInfo = helpCommentsParser.GetRemoteHelpInfo(context, commandInfo); if (remoteHelpInfo != null) { // Add HelpUri if necessary if (remoteHelpInfo.GetUriForOnlineHelp() == null) { DefaultCommandHelpObjectBuilder.AddRelatedLinksProperties(remoteHelpInfo.FullHelp, commandInfo.CommandMetadata.HelpUri); } return remoteHelpInfo; } } XmlDocument doc = helpCommentsParser.BuildXmlFromComments(); HelpCategory helpCategory = commandInfo.HelpCategory; MamlCommandHelpInfo localHelpInfo = MamlCommandHelpInfo.Load(doc.DocumentElement, helpCategory); if (localHelpInfo != null) { helpCommentsParser.SetAdditionalData(localHelpInfo); if (!string.IsNullOrEmpty(helpCommentsParser._sections.ForwardHelpTargetName) || !string.IsNullOrEmpty(helpCommentsParser._sections.ForwardHelpCategory)) { if (string.IsNullOrEmpty(helpCommentsParser._sections.ForwardHelpTargetName)) { localHelpInfo.ForwardTarget = localHelpInfo.Name; } else { localHelpInfo.ForwardTarget = helpCommentsParser._sections.ForwardHelpTargetName; } if (!string.IsNullOrEmpty(helpCommentsParser._sections.ForwardHelpCategory)) { try { localHelpInfo.ForwardHelpCategory = (HelpCategory)Enum.Parse(typeof(HelpCategory), helpCommentsParser._sections.ForwardHelpCategory, true); } catch (System.ArgumentException) { // Ignore conversion errors. } } else { localHelpInfo.ForwardHelpCategory = (HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand | HelpCategory.Workflow); } } WorkflowInfo workflowInfo = commandInfo as WorkflowInfo; if (workflowInfo != null) { bool common = DefaultCommandHelpObjectBuilder.HasCommonParameters(commandInfo.Parameters); bool commonWorkflow = ((commandInfo.CommandType & CommandTypes.Workflow) == CommandTypes.Workflow); localHelpInfo.FullHelp.Properties.Add(new PSNoteProperty("CommonParameters", common)); localHelpInfo.FullHelp.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow)); DefaultCommandHelpObjectBuilder.AddDetailsProperties(obj: localHelpInfo.FullHelp, name: workflowInfo.Name, noun: workflowInfo.Noun, verb: workflowInfo.Verb, typeNameForHelp: "MamlCommandHelpInfo", synopsis: localHelpInfo.Synopsis); DefaultCommandHelpObjectBuilder.AddSyntaxProperties(localHelpInfo.FullHelp, workflowInfo.Name, workflowInfo.ParameterSets, common, commonWorkflow, "MamlCommandHelpInfo"); } // Add HelpUri if necessary if (localHelpInfo.GetUriForOnlineHelp() == null) { DefaultCommandHelpObjectBuilder.AddRelatedLinksProperties(localHelpInfo.FullHelp, commandInfo.CommandMetadata.HelpUri); } } return localHelpInfo; } /// <summary> /// Analyze a block of comments to determine if it is a special help block. /// </summary> /// <param name="commentBlock">The block of comments to analyze.</param> /// <returns>true if the block is our special comment block for help, false otherwise.</returns> internal static bool IsCommentHelpText(List<Token> commentBlock) { if ((commentBlock == null) || (commentBlock.Count == 0)) return false; HelpCommentsParser generator = new HelpCommentsParser(); return generator.AnalyzeCommentBlock(commentBlock); } #region Collect comments from AST private static List<Language.Token> GetCommentBlock(Language.Token[] tokens, ref int startIndex) { var result = new List<Language.Token>(); // Any whitespace between the token and the first comment is allowed. int nextMaxStartLine = Int32.MaxValue; for (int i = startIndex; i < tokens.Length; i++) { Language.Token current = tokens[i]; // If the current token starts on a line beyond the current "chunk", // then we're done scanning. if (current.Extent.StartLineNumber > nextMaxStartLine) { startIndex = i; break; } if (current.Kind == TokenKind.Comment) { result.Add(current); // The next comment must be on either the same line as this comment ends, or // the next line, but nowhere else, otherwise it's not in the same "chunk". nextMaxStartLine = current.Extent.EndLineNumber + 1; } else if (current.Kind != TokenKind.NewLine) { // A non-comment, non-position token means we are no longer collecting comments startIndex = i; break; } } return result; } private static List<Language.Token> GetPrecedingCommentBlock(Language.Token[] tokens, int tokenIndex, int proximity) { var result = new List<Language.Token>(); int minEndLine = tokens[tokenIndex].Extent.StartLineNumber - proximity; for (int i = tokenIndex - 1; i >= 0; i--) { Language.Token current = tokens[i]; if (current.Extent.EndLineNumber < minEndLine) break; if (current.Kind == TokenKind.Comment) { result.Add(current); minEndLine = current.Extent.StartLineNumber - 1; } else if (current.Kind != TokenKind.NewLine) { break; } } result.Reverse(); return result; } private static int FirstTokenInExtent(Language.Token[] tokens, IScriptExtent extent, int startIndex = 0) { int index; for (index = startIndex; index < tokens.Length; ++index) { if (!tokens[index].Extent.IsBefore(extent)) { break; } } return index; } private static int LastTokenInExtent(Language.Token[] tokens, IScriptExtent extent, int startIndex) { int index; for (index = startIndex; index < tokens.Length; ++index) { if (tokens[index].Extent.IsAfter(extent)) { break; } } return index - 1; } internal const int CommentBlockProximity = 2; private static List<string> GetParameterComments(Language.Token[] tokens, IParameterMetadataProvider ipmp, int startIndex) { var result = new List<string>(); var parameters = ipmp.Parameters; if (parameters == null || parameters.Count == 0) { return result; } foreach (var parameter in parameters) { var commentLines = new List<string>(); var firstToken = FirstTokenInExtent(tokens, parameter.Extent, startIndex); var comments = GetPrecedingCommentBlock(tokens, firstToken, CommentBlockProximity); if (comments != null) { foreach (var comment in comments) { CollectCommentText(comment, commentLines); } } var lastToken = LastTokenInExtent(tokens, parameter.Extent, firstToken); for (int i = firstToken; i < lastToken; ++i) { if (tokens[i].Kind == TokenKind.Comment) { CollectCommentText(tokens[i], commentLines); } } lastToken += 1; comments = GetCommentBlock(tokens, ref lastToken); if (comments != null) { foreach (var comment in comments) { CollectCommentText(comment, commentLines); } } int n = -1; result.Add(GetSection(commentLines, ref n)); } return result; } internal static Tuple<List<Language.Token>, List<string>> GetHelpCommentTokens(IParameterMetadataProvider ipmp, Dictionary<Ast, Token[]> scriptBlockTokenCache) { Diagnostics.Assert(scriptBlockTokenCache != null, "scriptBlockTokenCache cannot be null"); var ast = (Ast)ipmp; var rootAst = ast; Ast configAst = null; while (rootAst.Parent != null) { rootAst = rootAst.Parent; if (rootAst is ConfigurationDefinitionAst) { configAst = rootAst; } } // tokens saved from reparsing the script. Language.Token[] tokens = null; scriptBlockTokenCache.TryGetValue(rootAst, out tokens); if (tokens == null) { ParseError[] errors; // storing all comment tokens Language.Parser.ParseInput(rootAst.Extent.Text, out tokens, out errors); scriptBlockTokenCache[rootAst] = tokens; } int savedStartIndex; int startTokenIndex; int lastTokenIndex; var funcDefnAst = ast as FunctionDefinitionAst; List<Language.Token> commentBlock; if (funcDefnAst != null || configAst != null) { // The first comment block preceding the function or configuration keyword is a candidate help comment block. var funcOrConfigTokenIndex = savedStartIndex = FirstTokenInExtent(tokens, configAst == null ? ast.Extent : configAst.Extent); commentBlock = GetPrecedingCommentBlock(tokens, funcOrConfigTokenIndex, CommentBlockProximity); if (HelpCommentsParser.IsCommentHelpText(commentBlock)) { return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex)); } // comment block is behind function definition // we don't suport it for configuration delaration as this style is rarely used if (funcDefnAst != null) { startTokenIndex = FirstTokenInExtent(tokens, funcDefnAst.Body.Extent) + 1; lastTokenIndex = LastTokenInExtent(tokens, ast.Extent, funcOrConfigTokenIndex); Diagnostics.Assert(tokens[startTokenIndex - 1].Kind == TokenKind.LCurly, "Unexpected first token in function"); Diagnostics.Assert(tokens[lastTokenIndex].Kind == TokenKind.RCurly, "Unexpected last token in function"); } else { return null; } } else if (ast == rootAst) { startTokenIndex = savedStartIndex = 0; lastTokenIndex = tokens.Length - 1; } else { // This case should be rare (but common with implicit remoting). // We have a script block that was used to generate a function like: // $sb = { } // set-item function:foo $sb // help foo startTokenIndex = savedStartIndex = FirstTokenInExtent(tokens, ast.Extent) - 1; lastTokenIndex = LastTokenInExtent(tokens, ast.Extent, startTokenIndex); Diagnostics.Assert(tokens[startTokenIndex + 1].Kind == TokenKind.LCurly, "Unexpected first token in script block"); Diagnostics.Assert(tokens[lastTokenIndex].Kind == TokenKind.RCurly, "Unexpected last token in script block"); } while (true) { commentBlock = GetCommentBlock(tokens, ref startTokenIndex); if (commentBlock.Count == 0) break; if (!HelpCommentsParser.IsCommentHelpText(commentBlock)) continue; if (ast == rootAst) { // One more check - make sure the comment doesn't belong to the first function in the script. var endBlock = ((ScriptBlockAst)ast).EndBlock; if (endBlock == null || !endBlock.Unnamed) { return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex)); } var firstStatement = endBlock.Statements.FirstOrDefault(); if (firstStatement is FunctionDefinitionAst) { int linesBetween = firstStatement.Extent.StartLineNumber - commentBlock.Last().Extent.EndLineNumber; if (linesBetween > CommentBlockProximity) { return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex)); } break; } } return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex)); } commentBlock = GetPrecedingCommentBlock(tokens, lastTokenIndex, tokens[lastTokenIndex].Extent.StartLineNumber); if (HelpCommentsParser.IsCommentHelpText(commentBlock)) { return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex)); } return null; } #endregion Collect comments from AST } }
// 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.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Text { internal ref partial struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span<char> _chars; private int _pos; public ValueStringBuilder(Span<char> initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _chars = _arrayToReturnToPool; _pos = 0; } public int Length { get => _pos; set { Debug.Assert(value >= 0); Debug.Assert(value <= _chars.Length); _pos = value; } } public int Capacity => _chars.Length; public void EnsureCapacity(int capacity) { if (capacity > _chars.Length) Grow(capacity - _chars.Length); } /// <summary> /// Get a pinnable reference to the builder. /// Does not ensure there is a null char after <see cref="Length"/> /// This overload is pattern matched in the C# 7.3+ compiler so you can omit /// the explicit method call, and write eg "fixed (char* c = builder)" /// </summary> public ref char GetPinnableReference() { return ref MemoryMarshal.GetReference(_chars); } /// <summary> /// Get a pinnable reference to the builder. /// </summary> /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param> public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference(_chars); } public ref char this[int index] { get { Debug.Assert(index < _pos); return ref _chars[index]; } } public override string ToString() { var s = _chars.Slice(0, _pos).ToString(); Dispose(); return s; } /// <summary>Returns the underlying storage of the builder.</summary> public Span<char> RawChars => _chars; /// <summary> /// Returns a span around the contents of the builder. /// </summary> /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param> public ReadOnlySpan<char> AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan() => _chars.Slice(0, _pos); public ReadOnlySpan<char> AsSpan(int start) => _chars.Slice(start, _pos - start); public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length); public bool TryCopyTo(Span<char> destination, out int charsWritten) { if (_chars.Slice(0, _pos).TryCopyTo(destination)) { charsWritten = _pos; Dispose(); return true; } else { charsWritten = 0; Dispose(); return false; } } public void Insert(int index, char value, int count) { if (_pos > _chars.Length - count) { Grow(count); } int remaining = _pos - index; _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count)); _chars.Slice(index, count).Fill(value); _pos += count; } public void Insert(int index, string s) { int count = s.Length; if (_pos > (_chars.Length - count)) { Grow(count); } int remaining = _pos - index; _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count)); s.AsSpan().CopyTo(_chars.Slice(index)); _pos += count; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; if ((uint)pos < (uint)_chars.Length) { _chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string s) { int pos = _pos; if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc. { _chars[pos] = s[0]; _pos = pos + 1; } else { AppendSlow(s); } } private void AppendSlow(string s) { int pos = _pos; if (pos > _chars.Length - s.Length) { Grow(s.Length); } s.AsSpan().CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } Span<char> dst = _chars.Slice(_pos, count); for (int i = 0; i < dst.Length; i++) { dst[i] = c; } _pos += count; } public unsafe void Append(char* value, int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } Span<char> dst = _chars.Slice(_pos, length); for (int i = 0; i < dst.Length; i++) { dst[i] = *value++; } _pos += length; } public unsafe void Append(ReadOnlySpan<char> value) { int pos = _pos; if (pos > _chars.Length - value.Length) { Grow(value.Length); } value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<char> AppendSpan(int length) { int origPos = _pos; if (origPos > _chars.Length - length) { Grow(length); } _pos = origPos + length; return _chars.Slice(origPos, length); } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowAndAppend(char c) { Grow(1); Append(c); } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow(int requiredAdditionalCapacity) { Debug.Assert(requiredAdditionalCapacity > 0); char[] poolArray = ArrayPool<char>.Shared.Rent(Math.Max(_pos + requiredAdditionalCapacity, _chars.Length * 2)); _chars.CopyTo(poolArray); char[] toReturn = _arrayToReturnToPool; _chars = _arrayToReturnToPool = poolArray; if (toReturn != null) { ArrayPool<char>.Shared.Return(toReturn); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { char[] toReturn = _arrayToReturnToPool; this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again if (toReturn != null) { ArrayPool<char>.Shared.Return(toReturn); } } } }
// 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 Xunit; namespace System.Linq.Expressions.Tests { public class Return : GotoExpressionTests { [Theory] [PerCompilationType(nameof(ConstantValueData))] public void JustReturnValue(object value, bool useInterpreter) { Type type = value.GetType(); LabelTarget target = Expression.Label(type); Expression block = Expression.Block( Expression.Return(target, Expression.Constant(value)), Expression.Label(target, Expression.Default(type)) ); Expression equals = Expression.Equal(Expression.Constant(value), block); Assert.True(Expression.Lambda<Func<bool>>(equals).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void ReturnToMiddle(bool useInterpreter) { // The behaviour is that return jumps to a label, but does not necessarily leave a block. LabelTarget target = Expression.Label(typeof(int)); Expression block = Expression.Block( Expression.Return(target, Expression.Constant(1)), Expression.Label(target, Expression.Constant(2)), Expression.Constant(3) ); Assert.Equal(3, Expression.Lambda<Func<int>>(block).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void ReturnJumps(object value, bool useInterpreter) { Type type = value.GetType(); LabelTarget target = Expression.Label(type); Expression block = Expression.Block( Expression.Return(target, Expression.Constant(value)), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value), block)).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(TypesData))] public void NonVoidTargetReturnHasNoValue(Type type) { LabelTarget target = Expression.Label(type); Assert.Throws<ArgumentException>("target", () => Expression.Return(target)); } [Theory] [MemberData(nameof(TypesData))] public void NonVoidTargetReturnHasNoValueTypeExplicit(Type type) { LabelTarget target = Expression.Label(type); Assert.Throws<ArgumentException>("target", () => Expression.Return(target, type)); } [Theory] [ClassData(typeof(CompilationTypes))] public void ReturnVoidNoValue(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression block = Expression.Block( Expression.Return(target), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target) ); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [ClassData(typeof(CompilationTypes))] public void ReturnExplicitVoidNoValue(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression block = Expression.Block( Expression.Return(target, typeof(void)), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target) ); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [MemberData(nameof(TypesData))] public void NullValueOnNonVoidReturn(Type type) { Assert.Throws<ArgumentException>("target", () => Expression.Return(Expression.Label(type))); Assert.Throws<ArgumentException>("target", () => Expression.Return(Expression.Label(type), default(Expression))); Assert.Throws<ArgumentException>("target", () => Expression.Return(Expression.Label(type), null, type)); } [Theory] [MemberData(nameof(ConstantValueData))] public void ExplicitNullTypeWithValue(object value) { Assert.Throws<ArgumentException>("target", () => Expression.Return(Expression.Label(value.GetType()), default(Type))); } [Fact] public void UnreadableLabel() { Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly"); LabelTarget target = Expression.Label(typeof(string)); Assert.Throws<ArgumentException>("value", () => Expression.Return(target, value)); Assert.Throws<ArgumentException>("value", () => Expression.Return(target, value, typeof(string))); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void CanAssignAnythingToVoid(object value, bool useInterpreter) { LabelTarget target = Expression.Label(); BlockExpression block = Expression.Block( Expression.Return(target, Expression.Constant(value)), Expression.Label(target) ); Assert.Equal(typeof(void), block.Type); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [MemberData(nameof(NonObjectAssignableConstantValueData))] public void CannotAssignValueTypesToObject(object value) { Assert.Throws<ArgumentException>(null, () => Expression.Return(Expression.Label(typeof(object)), Expression.Constant(value))); } [Theory] [PerCompilationType(nameof(ObjectAssignableConstantValueData))] public void ExplicitTypeAssigned(object value, bool useInterpreter) { LabelTarget target = Expression.Label(typeof(object)); BlockExpression block = Expression.Block( Expression.Return(target, Expression.Constant(value), typeof(object)), Expression.Label(target, Expression.Default(typeof(object))) ); Assert.Equal(typeof(object), block.Type); Assert.Equal(value, Expression.Lambda<Func<object>>(block).Compile(useInterpreter)()); } [Fact] public void ReturnQuotesIfNecessary() { LabelTarget target = Expression.Label(typeof(Expression<Func<int>>)); BlockExpression block = Expression.Block( Expression.Return(target, Expression.Lambda<Func<int>>(Expression.Constant(0))), Expression.Label(target, Expression.Default(typeof(Expression<Func<int>>))) ); Assert.Equal(typeof(Expression<Func<int>>), block.Type); } [Fact] public void UpdateSameIsSame() { LabelTarget target = Expression.Label(typeof(int)); Expression value = Expression.Constant(0); GotoExpression ret = Expression.Return(target, value); Assert.Same(ret, ret.Update(target, value)); Assert.Same(ret, NoOpVisitor.Instance.Visit(ret)); } [Fact] public void UpdateDiferentValueIsDifferent() { LabelTarget target = Expression.Label(typeof(int)); GotoExpression ret = Expression.Return(target, Expression.Constant(0)); Assert.NotSame(ret, ret.Update(target, Expression.Constant(0))); } [Fact] public void UpdateDifferentTargetIsDifferent() { Expression value = Expression.Constant(0); GotoExpression ret = Expression.Return(Expression.Label(typeof(int)), value); Assert.NotSame(ret, ret.Update(Expression.Label(typeof(int)), value)); } [Fact] public void OpenGenericType() { Assert.Throws<ArgumentException>("type", () => Expression.Return(Expression.Label(typeof(void)), typeof(List<>))); } [Fact] public static void TypeContainsGenericParameters() { Assert.Throws<ArgumentException>("type", () => Expression.Return(Expression.Label(typeof(void)), typeof(List<>.Enumerator))); Assert.Throws<ArgumentException>("type", () => Expression.Return(Expression.Label(typeof(void)), typeof(List<>).MakeGenericType(typeof(List<>)))); } [Fact] public void PointerType() { Assert.Throws<ArgumentException>("type", () => Expression.Return(Expression.Label(typeof(void)), typeof(int).MakePointerType())); } [Fact] public void ByRefType() { Assert.Throws<ArgumentException>("type", () => Expression.Return(Expression.Label(typeof(void)), typeof(int).MakeByRefType())); } [Theory, ClassData(typeof(CompilationTypes))] public void UndefinedLabel(bool useInterpreter) { Expression<Action> returnNowhere = Expression.Lambda<Action>(Expression.Return(Expression.Label())); Assert.Throws<InvalidOperationException>(() => returnNowhere.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void AmbiguousJump(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression<Action> exp = Expression.Lambda<Action>( Expression.Block( Expression.Return(target), Expression.Block(Expression.Label(target)), Expression.Block(Expression.Label(target)) ) ); Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void MultipleDefinitionsInSeparateBlocks(bool useInterpreter) { LabelTarget target = Expression.Label(typeof(int)); Func<int> add = Expression.Lambda<Func<int>>( Expression.Add( Expression.Add( Expression.Block( Expression.Return(target, Expression.Constant(6)), Expression.Throw(Expression.Constant(new Exception())), Expression.Label(target, Expression.Constant(0)) ), Expression.Block( Expression.Return(target, Expression.Constant(4)), Expression.Throw(Expression.Constant(new Exception())), Expression.Label(target, Expression.Constant(0)) ) ), Expression.Block( Expression.Return(target, Expression.Constant(5)), Expression.Throw(Expression.Constant(new Exception())), Expression.Label(target, Expression.Constant(0)) ) ) ).Compile(useInterpreter); Assert.Equal(15, add()); } [Theory, ClassData(typeof(CompilationTypes))] public void JumpIntoExpression(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression<Func<bool>> isInt = Expression.Lambda<Func<bool>>( Expression.Block( Expression.Return(target), Expression.TypeIs(Expression.Label(target), typeof(int)) ) ); Assert.Throws<InvalidOperationException>(() => isInt.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void JumpInWithValue(bool useInterpreter) { LabelTarget target = Expression.Label(typeof(int)); Expression<Func<int>> exp = Expression.Lambda<Func<int>>( Expression.Block( Expression.Return(target, Expression.Constant(2)), Expression.Block( Expression.Label(target, Expression.Constant(3))) ) ); Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter)); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudtrail-2013-11-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudTrail.Model { /// <summary> /// Returns the objects or data listed below if successful. Otherwise, returns an error. /// </summary> public partial class GetTrailStatusResponse : AmazonWebServiceResponse { private bool? _isLogging; private string _latestCloudWatchLogsDeliveryError; private DateTime? _latestCloudWatchLogsDeliveryTime; private string _latestDeliveryAttemptSucceeded; private string _latestDeliveryAttemptTime; private string _latestDeliveryError; private DateTime? _latestDeliveryTime; private string _latestDigestDeliveryError; private DateTime? _latestDigestDeliveryTime; private string _latestNotificationAttemptSucceeded; private string _latestNotificationAttemptTime; private string _latestNotificationError; private DateTime? _latestNotificationTime; private DateTime? _startLoggingTime; private DateTime? _stopLoggingTime; private string _timeLoggingStarted; private string _timeLoggingStopped; /// <summary> /// Gets and sets the property IsLogging. /// <para> /// Whether the CloudTrail is currently logging AWS API calls. /// </para> /// </summary> public bool IsLogging { get { return this._isLogging.GetValueOrDefault(); } set { this._isLogging = value; } } // Check to see if IsLogging property is set internal bool IsSetIsLogging() { return this._isLogging.HasValue; } /// <summary> /// Gets and sets the property LatestCloudWatchLogsDeliveryError. /// <para> /// Displays any CloudWatch Logs error that CloudTrail encountered when attempting to /// deliver logs to CloudWatch Logs. /// </para> /// </summary> public string LatestCloudWatchLogsDeliveryError { get { return this._latestCloudWatchLogsDeliveryError; } set { this._latestCloudWatchLogsDeliveryError = value; } } // Check to see if LatestCloudWatchLogsDeliveryError property is set internal bool IsSetLatestCloudWatchLogsDeliveryError() { return this._latestCloudWatchLogsDeliveryError != null; } /// <summary> /// Gets and sets the property LatestCloudWatchLogsDeliveryTime. /// <para> /// Displays the most recent date and time when CloudTrail delivered logs to CloudWatch /// Logs. /// </para> /// </summary> public DateTime LatestCloudWatchLogsDeliveryTime { get { return this._latestCloudWatchLogsDeliveryTime.GetValueOrDefault(); } set { this._latestCloudWatchLogsDeliveryTime = value; } } // Check to see if LatestCloudWatchLogsDeliveryTime property is set internal bool IsSetLatestCloudWatchLogsDeliveryTime() { return this._latestCloudWatchLogsDeliveryTime.HasValue; } /// <summary> /// Gets and sets the property LatestDeliveryAttemptSucceeded. /// <para> /// This field is deprecated. /// </para> /// </summary> public string LatestDeliveryAttemptSucceeded { get { return this._latestDeliveryAttemptSucceeded; } set { this._latestDeliveryAttemptSucceeded = value; } } // Check to see if LatestDeliveryAttemptSucceeded property is set internal bool IsSetLatestDeliveryAttemptSucceeded() { return this._latestDeliveryAttemptSucceeded != null; } /// <summary> /// Gets and sets the property LatestDeliveryAttemptTime. /// <para> /// This field is deprecated. /// </para> /// </summary> public string LatestDeliveryAttemptTime { get { return this._latestDeliveryAttemptTime; } set { this._latestDeliveryAttemptTime = value; } } // Check to see if LatestDeliveryAttemptTime property is set internal bool IsSetLatestDeliveryAttemptTime() { return this._latestDeliveryAttemptTime != null; } /// <summary> /// Gets and sets the property LatestDeliveryError. /// <para> /// Displays any Amazon S3 error that CloudTrail encountered when attempting to deliver /// log files to the designated bucket. For more information see the topic <a href="http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html">Error /// Responses</a> in the Amazon S3 API Reference. /// </para> /// <note>This error occurs only when there is a problem with the destination S3 bucket /// and will not occur for timeouts. To resolve the issue, create a new bucket and call /// <code>UpdateTrail</code> to specify the new bucket, or fix the existing objects so /// that CloudTrail can again write to the bucket. </note> /// </summary> public string LatestDeliveryError { get { return this._latestDeliveryError; } set { this._latestDeliveryError = value; } } // Check to see if LatestDeliveryError property is set internal bool IsSetLatestDeliveryError() { return this._latestDeliveryError != null; } /// <summary> /// Gets and sets the property LatestDeliveryTime. /// <para> /// Specifies the date and time that CloudTrail last delivered log files to an account's /// Amazon S3 bucket. /// </para> /// </summary> public DateTime LatestDeliveryTime { get { return this._latestDeliveryTime.GetValueOrDefault(); } set { this._latestDeliveryTime = value; } } // Check to see if LatestDeliveryTime property is set internal bool IsSetLatestDeliveryTime() { return this._latestDeliveryTime.HasValue; } /// <summary> /// Gets and sets the property LatestDigestDeliveryError. /// <para> /// Displays any Amazon S3 error that CloudTrail encountered when attempting to deliver /// a digest file to the designated bucket. For more information see the topic <a href="http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html">Error /// Responses</a> in the Amazon S3 API Reference. /// </para> /// <note>This error occurs only when there is a problem with the destination S3 bucket /// and will not occur for timeouts. To resolve the issue, create a new bucket and call /// <code>UpdateTrail</code> to specify the new bucket, or fix the existing objects so /// that CloudTrail can again write to the bucket. </note> /// </summary> public string LatestDigestDeliveryError { get { return this._latestDigestDeliveryError; } set { this._latestDigestDeliveryError = value; } } // Check to see if LatestDigestDeliveryError property is set internal bool IsSetLatestDigestDeliveryError() { return this._latestDigestDeliveryError != null; } /// <summary> /// Gets and sets the property LatestDigestDeliveryTime. /// <para> /// Specifies the date and time that CloudTrail last delivered a digest file to an account's /// Amazon S3 bucket. /// </para> /// </summary> public DateTime LatestDigestDeliveryTime { get { return this._latestDigestDeliveryTime.GetValueOrDefault(); } set { this._latestDigestDeliveryTime = value; } } // Check to see if LatestDigestDeliveryTime property is set internal bool IsSetLatestDigestDeliveryTime() { return this._latestDigestDeliveryTime.HasValue; } /// <summary> /// Gets and sets the property LatestNotificationAttemptSucceeded. /// <para> /// This field is deprecated. /// </para> /// </summary> public string LatestNotificationAttemptSucceeded { get { return this._latestNotificationAttemptSucceeded; } set { this._latestNotificationAttemptSucceeded = value; } } // Check to see if LatestNotificationAttemptSucceeded property is set internal bool IsSetLatestNotificationAttemptSucceeded() { return this._latestNotificationAttemptSucceeded != null; } /// <summary> /// Gets and sets the property LatestNotificationAttemptTime. /// <para> /// This field is deprecated. /// </para> /// </summary> public string LatestNotificationAttemptTime { get { return this._latestNotificationAttemptTime; } set { this._latestNotificationAttemptTime = value; } } // Check to see if LatestNotificationAttemptTime property is set internal bool IsSetLatestNotificationAttemptTime() { return this._latestNotificationAttemptTime != null; } /// <summary> /// Gets and sets the property LatestNotificationError. /// <para> /// Displays any Amazon SNS error that CloudTrail encountered when attempting to send /// a notification. For more information about Amazon SNS errors, see the <a href="http://docs.aws.amazon.com/sns/latest/dg/welcome.html">Amazon /// SNS Developer Guide</a>. /// </para> /// </summary> public string LatestNotificationError { get { return this._latestNotificationError; } set { this._latestNotificationError = value; } } // Check to see if LatestNotificationError property is set internal bool IsSetLatestNotificationError() { return this._latestNotificationError != null; } /// <summary> /// Gets and sets the property LatestNotificationTime. /// <para> /// Specifies the date and time of the most recent Amazon SNS notification that CloudTrail /// has written a new log file to an account's Amazon S3 bucket. /// </para> /// </summary> public DateTime LatestNotificationTime { get { return this._latestNotificationTime.GetValueOrDefault(); } set { this._latestNotificationTime = value; } } // Check to see if LatestNotificationTime property is set internal bool IsSetLatestNotificationTime() { return this._latestNotificationTime.HasValue; } /// <summary> /// Gets and sets the property StartLoggingTime. /// <para> /// Specifies the most recent date and time when CloudTrail started recording API calls /// for an AWS account. /// </para> /// </summary> public DateTime StartLoggingTime { get { return this._startLoggingTime.GetValueOrDefault(); } set { this._startLoggingTime = value; } } // Check to see if StartLoggingTime property is set internal bool IsSetStartLoggingTime() { return this._startLoggingTime.HasValue; } /// <summary> /// Gets and sets the property StopLoggingTime. /// <para> /// Specifies the most recent date and time when CloudTrail stopped recording API calls /// for an AWS account. /// </para> /// </summary> public DateTime StopLoggingTime { get { return this._stopLoggingTime.GetValueOrDefault(); } set { this._stopLoggingTime = value; } } // Check to see if StopLoggingTime property is set internal bool IsSetStopLoggingTime() { return this._stopLoggingTime.HasValue; } /// <summary> /// Gets and sets the property TimeLoggingStarted. /// <para> /// This field is deprecated. /// </para> /// </summary> public string TimeLoggingStarted { get { return this._timeLoggingStarted; } set { this._timeLoggingStarted = value; } } // Check to see if TimeLoggingStarted property is set internal bool IsSetTimeLoggingStarted() { return this._timeLoggingStarted != null; } /// <summary> /// Gets and sets the property TimeLoggingStopped. /// <para> /// This field is deprecated. /// </para> /// </summary> public string TimeLoggingStopped { get { return this._timeLoggingStopped; } set { this._timeLoggingStopped = value; } } // Check to see if TimeLoggingStopped property is set internal bool IsSetTimeLoggingStopped() { return this._timeLoggingStopped != null; } } }
/* * 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 Directory = Lucene.Net.Store.Directory; using CloseableThreadLocal = Lucene.Net.Util.CloseableThreadLocal; using SimpleLRUCache = Lucene.Net.Util.Cache.SimpleLRUCache; namespace Lucene.Net.Index { /// <summary>This stores a monotonically increasing set of &lt;Term, TermInfo&gt; pairs in a /// Directory. Pairs are accessed either by Term or by ordinal position the /// set. /// </summary> sealed class TermInfosReader { private Directory directory; private System.String segment; private FieldInfos fieldInfos; private CloseableThreadLocal threadResources = new CloseableThreadLocal(); private SegmentTermEnum origEnum; private long size; private Term[] indexTerms; private TermInfo[] indexInfos; private long[] indexPointers; private int totalIndexInterval; private const int DEFAULT_CACHE_SIZE = 1024; /// <summary> Per-thread resources managed by ThreadLocal</summary> private sealed class ThreadResources { internal SegmentTermEnum termEnum; // Used for caching the least recently looked-up Terms internal Lucene.Net.Util.Cache.Cache termInfoCache; } internal TermInfosReader(Directory dir, System.String seg, FieldInfos fis, int readBufferSize, int indexDivisor) { bool success = false; if (indexDivisor < 1 && indexDivisor != - 1) { throw new System.ArgumentException("indexDivisor must be -1 (don't load terms index) or greater than 0: got " + indexDivisor); } try { directory = dir; segment = seg; fieldInfos = fis; origEnum = new SegmentTermEnum(directory.OpenInput(segment + "." + IndexFileNames.TERMS_EXTENSION, readBufferSize), fieldInfos, false); size = origEnum.size; if (indexDivisor != - 1) { // Load terms index totalIndexInterval = origEnum.indexInterval * indexDivisor; SegmentTermEnum indexEnum = new SegmentTermEnum(directory.OpenInput(segment + "." + IndexFileNames.TERMS_INDEX_EXTENSION, readBufferSize), fieldInfos, true); try { int indexSize = 1 + ((int) indexEnum.size - 1) / indexDivisor; // otherwise read index indexTerms = new Term[indexSize]; indexInfos = new TermInfo[indexSize]; indexPointers = new long[indexSize]; for (int i = 0; indexEnum.Next(); i++) { indexTerms[i] = indexEnum.Term(); indexInfos[i] = indexEnum.TermInfo(); indexPointers[i] = indexEnum.indexPointer; for (int j = 1; j < indexDivisor; j++) if (!indexEnum.Next()) break; } } finally { indexEnum.Close(); } } else { // Do not load terms index: totalIndexInterval = - 1; indexTerms = null; indexInfos = null; indexPointers = null; } success = true; } finally { // With lock-less commits, it's entirely possible (and // fine) to hit a FileNotFound exception above. In // this case, we want to explicitly close any subset // of things that were opened so that we don't have to // wait for a GC to do so. if (!success) { Close(); } } } public int GetSkipInterval() { return origEnum.skipInterval; } public int GetMaxSkipLevels() { return origEnum.maxSkipLevels; } internal void Close() { if (origEnum != null) origEnum.Close(); threadResources.Close(); } /// <summary>Returns the number of term/value pairs in the set. </summary> internal long Size() { return size; } private ThreadResources GetThreadResources() { ThreadResources resources = (ThreadResources) threadResources.Get(); if (resources == null) { resources = new ThreadResources(); resources.termEnum = Terms(); // Cache does not have to be thread-safe, it is only used by one thread at the same time resources.termInfoCache = new SimpleLRUCache(DEFAULT_CACHE_SIZE); threadResources.Set(resources); } return resources; } /// <summary>Returns the offset of the greatest index entry which is less than or equal to term.</summary> private int GetIndexOffset(Term term) { int lo = 0; // binary search indexTerms[] int hi = indexTerms.Length - 1; while (hi >= lo) { int mid = SupportClass.Number.URShift((lo + hi), 1); int delta = term.CompareTo(indexTerms[mid]); if (delta < 0) hi = mid - 1; else if (delta > 0) lo = mid + 1; else return mid; } return hi; } private void SeekEnum(SegmentTermEnum enumerator, int indexOffset) { enumerator.Seek(indexPointers[indexOffset], ((long)indexOffset * totalIndexInterval) - 1, indexTerms[indexOffset], indexInfos[indexOffset]); } /// <summary>Returns the TermInfo for a Term in the set, or null. </summary> internal TermInfo Get(Term term) { return Get(term, true); } /// <summary>Returns the TermInfo for a Term in the set, or null. </summary> private TermInfo Get(Term term, bool useCache) { if (size == 0) return null; EnsureIndexIsRead(); TermInfo ti; ThreadResources resources = GetThreadResources(); Lucene.Net.Util.Cache.Cache cache = null; if (useCache) { cache = resources.termInfoCache; // check the cache first if the term was recently looked up ti = (TermInfo) cache.Get(term); if (ti != null) { return ti; } } // optimize sequential access: first try scanning cached enum w/o seeking SegmentTermEnum enumerator = resources.termEnum; if (enumerator.Term() != null && ((enumerator.Prev() != null && term.CompareTo(enumerator.Prev()) > 0) || term.CompareTo(enumerator.Term()) >= 0)) { int enumOffset = (int) (enumerator.position / totalIndexInterval) + 1; if (indexTerms.Length == enumOffset || term.CompareTo(indexTerms[enumOffset]) < 0) { // no need to seek int numScans = enumerator.ScanTo(term); if (enumerator.Term() != null && term.CompareTo(enumerator.Term()) == 0) { ti = enumerator.TermInfo(); if (cache != null && numScans > 1) { // we only want to put this TermInfo into the cache if // scanEnum skipped more than one dictionary entry. // This prevents RangeQueries or WildcardQueries to // wipe out the cache when they iterate over a large numbers // of terms in order cache.Put(term, ti); } } else { ti = null; } return ti; } } // random-access: must seek SeekEnum(enumerator, GetIndexOffset(term)); enumerator.ScanTo(term); if (enumerator.Term() != null && term.CompareTo(enumerator.Term()) == 0) { ti = enumerator.TermInfo(); if (cache != null) { cache.Put(term, ti); } } else { ti = null; } return ti; } private void EnsureIndexIsRead() { if (indexTerms == null) { throw new System.SystemException("terms index was not loaded when this reader was created"); } } /// <summary>Returns the position of a Term in the set or -1. </summary> internal long GetPosition(Term term) { if (size == 0) return - 1; EnsureIndexIsRead(); int indexOffset = GetIndexOffset(term); SegmentTermEnum enumerator = GetThreadResources().termEnum; SeekEnum(enumerator, indexOffset); while (term.CompareTo(enumerator.Term()) > 0 && enumerator.Next()) { } if (term.CompareTo(enumerator.Term()) == 0) return enumerator.position; else return - 1; } /// <summary>Returns an enumeration of all the Terms and TermInfos in the set. </summary> public SegmentTermEnum Terms() { return (SegmentTermEnum) origEnum.Clone(); } /// <summary>Returns an enumeration of terms starting at or after the named term. </summary> public SegmentTermEnum Terms(Term term) { // don't use the cache in this call because we want to reposition the // enumeration Get(term, false); return (SegmentTermEnum) GetThreadResources().termEnum.Clone(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Authorization { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// RoleDefinitionsOperations operations. /// </summary> internal partial class RoleDefinitionsOperations : IServiceOperations<AuthorizationManagementClient>, IRoleDefinitionsOperations { /// <summary> /// Initializes a new instance of the RoleDefinitionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RoleDefinitionsOperations(AuthorizationManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AuthorizationManagementClient /// </summary> public AuthorizationManagementClient Client { get; private set; } /// <summary> /// Deletes the role definition. /// </summary> /// <param name='scope'> /// Scope /// </param> /// <param name='roleDefinitionId'> /// Role definition id. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<RoleDefinition>> DeleteWithHttpMessagesAsync(string scope, string roleDefinitionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (scope == null) { throw new ValidationException(ValidationRules.CannotBeNull, "scope"); } if (roleDefinitionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "roleDefinitionId"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("scope", scope); tracingParameters.Add("roleDefinitionId", roleDefinitionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}").ToString(); _url = _url.Replace("{scope}", scope); _url = _url.Replace("{roleDefinitionId}", Uri.EscapeDataString(roleDefinitionId)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RoleDefinition>(); _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 = SafeJsonConvert.DeserializeObject<RoleDefinition>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get role definition by name (GUID). /// </summary> /// <param name='scope'> /// Scope /// </param> /// <param name='roleDefinitionId'> /// Role definition Id /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<RoleDefinition>> GetWithHttpMessagesAsync(string scope, string roleDefinitionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (scope == null) { throw new ValidationException(ValidationRules.CannotBeNull, "scope"); } if (roleDefinitionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "roleDefinitionId"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("scope", scope); tracingParameters.Add("roleDefinitionId", roleDefinitionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}").ToString(); _url = _url.Replace("{scope}", scope); _url = _url.Replace("{roleDefinitionId}", Uri.EscapeDataString(roleDefinitionId)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RoleDefinition>(); _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 = SafeJsonConvert.DeserializeObject<RoleDefinition>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a role definition. /// </summary> /// <param name='scope'> /// Scope /// </param> /// <param name='roleDefinitionId'> /// Role definition id. /// </param> /// <param name='roleDefinition'> /// Role definition. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<RoleDefinition>> CreateOrUpdateWithHttpMessagesAsync(string scope, string roleDefinitionId, RoleDefinition roleDefinition, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (scope == null) { throw new ValidationException(ValidationRules.CannotBeNull, "scope"); } if (roleDefinitionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "roleDefinitionId"); } if (roleDefinition == null) { throw new ValidationException(ValidationRules.CannotBeNull, "roleDefinition"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("scope", scope); tracingParameters.Add("roleDefinitionId", roleDefinitionId); tracingParameters.Add("roleDefinition", roleDefinition); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}").ToString(); _url = _url.Replace("{scope}", scope); _url = _url.Replace("{roleDefinitionId}", Uri.EscapeDataString(roleDefinitionId)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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 = SafeJsonConvert.SerializeObject(roleDefinition, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RoleDefinition>(); _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 == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<RoleDefinition>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get role definition by name (GUID). /// </summary> /// <param name='roleDefinitionId'> /// Fully qualified role definition Id /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<RoleDefinition>> GetByIdWithHttpMessagesAsync(string roleDefinitionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (roleDefinitionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "roleDefinitionId"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("roleDefinitionId", roleDefinitionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetById", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{roleDefinitionId}").ToString(); _url = _url.Replace("{roleDefinitionId}", roleDefinitionId); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RoleDefinition>(); _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 = SafeJsonConvert.DeserializeObject<RoleDefinition>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all role definitions that are applicable at scope and above. Use /// atScopeAndBelow filter to search below the given scope as well /// </summary> /// <param name='scope'> /// Scope /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<RoleDefinition>>> ListWithHttpMessagesAsync(string scope, ODataQuery<RoleDefinitionFilter> odataQuery = default(ODataQuery<RoleDefinitionFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (scope == null) { throw new ValidationException(ValidationRules.CannotBeNull, "scope"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("scope", scope); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{scope}/providers/Microsoft.Authorization/roleDefinitions").ToString(); _url = _url.Replace("{scope}", scope); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RoleDefinition>>(); _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 = SafeJsonConvert.DeserializeObject<Page<RoleDefinition>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all role definitions that are applicable at scope and above. Use /// atScopeAndBelow filter to search below the given scope as well /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<RoleDefinition>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RoleDefinition>>(); _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 = SafeJsonConvert.DeserializeObject<Page<RoleDefinition>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { internal sealed class PeWritingException : Exception { public PeWritingException(Exception inner) : base(inner.Message, inner) { } } internal sealed class PeWriter { private const string ResourceSectionName = ".rsrc"; private const string RelocationSectionName = ".reloc"; /// <summary> /// True if we should attempt to generate a deterministic output (no timestamps or random data). /// </summary> private readonly bool _deterministic; private readonly int _timeStamp; private readonly string _pdbPathOpt; private readonly bool _is32bit; private readonly ModulePropertiesForSerialization _properties; private readonly IEnumerable<IWin32Resource> _nativeResourcesOpt; private readonly ResourceSection _nativeResourceSectionOpt; private readonly BlobBuilder _win32ResourceWriter = new BlobBuilder(1024); private PeWriter( ModulePropertiesForSerialization properties, IEnumerable<IWin32Resource> nativeResourcesOpt, ResourceSection nativeResourceSectionOpt, string pdbPathOpt, bool deterministic) { _properties = properties; _pdbPathOpt = pdbPathOpt; _deterministic = deterministic; _nativeResourcesOpt = nativeResourcesOpt; _nativeResourceSectionOpt = nativeResourceSectionOpt; _is32bit = !_properties.Requires64bits; // In the PE File Header this is a "Time/Date Stamp" whose description is "Time and date // the file was created in seconds since January 1st 1970 00:00:00 or 0" // However, when we want to make it deterministic we fill it in (later) with bits from the hash of the full PE file. _timeStamp = _deterministic ? 0 : (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; } private bool EmitPdb => _pdbPathOpt != null; public static bool WritePeToStream( EmitContext context, CommonMessageProvider messageProvider, Func<Stream> getPeStream, Func<Stream> getPortablePdbStreamOpt, PdbWriter nativePdbWriterOpt, string pdbPathOpt, bool allowMissingMethodBodies, bool deterministic, CancellationToken cancellationToken) { // If PDB writer is given, we have to have PDB path. Debug.Assert(nativePdbWriterOpt == null || pdbPathOpt != null); var peWriter = new PeWriter(context.Module.Properties, context.Module.Win32Resources, context.Module.Win32ResourceSection, pdbPathOpt, deterministic); var mdWriter = FullMetadataWriter.Create(context, messageProvider, allowMissingMethodBodies, deterministic, getPortablePdbStreamOpt != null, cancellationToken); return peWriter.WritePeToStream(mdWriter, getPeStream, getPortablePdbStreamOpt, nativePdbWriterOpt); } private bool WritePeToStream(MetadataWriter mdWriter, Func<Stream> getPeStream, Func<Stream> getPortablePdbStreamOpt, PdbWriter nativePdbWriterOpt) { // TODO: we can precalculate the exact size of IL stream var ilWriter = new BlobBuilder(32 * 1024); var metadataWriter = new BlobBuilder(16 * 1024); var mappedFieldDataWriter = new BlobBuilder(); var managedResourceWriter = new BlobBuilder(1024); var debugMetadataWriterOpt = (getPortablePdbStreamOpt != null) ? new BlobBuilder(16 * 1024) : null; nativePdbWriterOpt?.SetMetadataEmitter(mdWriter); // Since we are producing a full assembly, we should not have a module version ID // imposed ahead-of time. Instead we will compute a deterministic module version ID // based on the contents of the generated stream. Debug.Assert(_properties.PersistentIdentifier == default(Guid)); int sectionCount = 1; if (_properties.RequiresStartupStub) sectionCount++; //.reloc if (!IteratorHelper.EnumerableIsEmpty(_nativeResourcesOpt) || _nativeResourceSectionOpt != null) sectionCount++; //.rsrc; int sizeOfPeHeaders = ComputeSizeOfPeHeaders(sectionCount); int textSectionRva = BitArithmeticUtilities.Align(sizeOfPeHeaders, _properties.SectionAlignment); int moduleVersionIdOffsetInMetadataStream; int methodBodyStreamRva = textSectionRva + OffsetToILStream; int entryPointToken; MetadataSizes metadataSizes; mdWriter.SerializeMetadataAndIL( metadataWriter, debugMetadataWriterOpt, nativePdbWriterOpt, ilWriter, mappedFieldDataWriter, managedResourceWriter, methodBodyStreamRva, mdSizes => CalculateMappedFieldDataStreamRva(textSectionRva, mdSizes), out moduleVersionIdOffsetInMetadataStream, out entryPointToken, out metadataSizes); ContentId nativePdbContentId; if (nativePdbWriterOpt != null) { if (entryPointToken != 0) { nativePdbWriterOpt.SetEntryPoint((uint)entryPointToken); } var assembly = mdWriter.Module.AsAssembly; if (assembly != null && assembly.Kind == OutputKind.WindowsRuntimeMetadata) { // Dev12: If compiling to winmdobj, we need to add to PDB source spans of // all types and members for better error reporting by WinMDExp. nativePdbWriterOpt.WriteDefinitionLocations(mdWriter.Module.GetSymbolToLocationMap()); } else { #if DEBUG // validate that all definitions are writable // if same scenario would happen in an winmdobj project nativePdbWriterOpt.AssertAllDefinitionsHaveTokens(mdWriter.Module.GetSymbolToLocationMap()); #endif } nativePdbContentId = nativePdbWriterOpt.GetContentId(); // the writer shall not be used after this point for writing: nativePdbWriterOpt = null; } else { nativePdbContentId = default(ContentId); } // write to Portable PDB stream: ContentId portablePdbContentId; Stream portablePdbStream = getPortablePdbStreamOpt?.Invoke(); if (portablePdbStream != null) { debugMetadataWriterOpt.WriteTo(portablePdbStream); if (_deterministic) { portablePdbContentId = ContentId.FromHash(CryptographicHashProvider.ComputeSha1(portablePdbStream)); } else { portablePdbContentId = new ContentId(Guid.NewGuid().ToByteArray(), BitConverter.GetBytes(_timeStamp)); } } else { portablePdbContentId = default(ContentId); } // Only the size of the fixed part of the debug table goes here. DirectoryEntry debugDirectory = default(DirectoryEntry); DirectoryEntry importTable = default(DirectoryEntry); DirectoryEntry importAddressTable = default(DirectoryEntry); int entryPointAddress = 0; if (EmitPdb) { debugDirectory = new DirectoryEntry(textSectionRva + ComputeOffsetToDebugTable(metadataSizes), ImageDebugDirectoryBaseSize); } if (_properties.RequiresStartupStub) { importAddressTable = new DirectoryEntry(textSectionRva, SizeOfImportAddressTable); entryPointAddress = CalculateMappedFieldDataStreamRva(textSectionRva, metadataSizes) - (_is32bit ? 6 : 10); // TODO: constants importTable = new DirectoryEntry(textSectionRva + ComputeOffsetToImportTable(metadataSizes), (_is32bit ? 66 : 70) + 13); // TODO: constants } var corHeaderDirectory = new DirectoryEntry(textSectionRva + SizeOfImportAddressTable, size: CorHeaderSize); long ntHeaderTimestampPosition; long metadataPosition; List<SectionHeader> sectionHeaders = CreateSectionHeaders(metadataSizes, sectionCount); CoffHeader coffHeader; NtHeader ntHeader; FillInNtHeader(sectionHeaders, entryPointAddress, corHeaderDirectory, importTable, importAddressTable, debugDirectory, out coffHeader, out ntHeader); Stream peStream = getPeStream(); if (peStream == null) { return false; } WriteHeaders(peStream, ntHeader, coffHeader, sectionHeaders, out ntHeaderTimestampPosition); WriteTextSection( peStream, sectionHeaders[0], importTable.RelativeVirtualAddress, importAddressTable.RelativeVirtualAddress, entryPointToken, metadataWriter, ilWriter, mappedFieldDataWriter, managedResourceWriter, metadataSizes, nativePdbContentId, portablePdbContentId, out metadataPosition); var resourceSection = sectionHeaders.FirstOrDefault(s => s.Name == ResourceSectionName); if (resourceSection != null) { WriteResourceSection(peStream, resourceSection); } var relocSection = sectionHeaders.FirstOrDefault(s => s.Name == RelocationSectionName); if (relocSection != null) { WriteRelocSection(peStream, relocSection, entryPointAddress); } if (_deterministic) { var mvidPosition = metadataPosition + moduleVersionIdOffsetInMetadataStream; WriteDeterministicGuidAndTimestamps(peStream, mvidPosition, ntHeaderTimestampPosition); } return true; } private List<SectionHeader> CreateSectionHeaders(MetadataSizes metadataSizes, int sectionCount) { var sectionHeaders = new List<SectionHeader>(); SectionHeader lastSection; int sizeOfPeHeaders = ComputeSizeOfPeHeaders(sectionCount); int sizeOfTextSection = ComputeSizeOfTextSection(metadataSizes); sectionHeaders.Add(lastSection = new SectionHeader( characteristics: SectionCharacteristics.MemRead | SectionCharacteristics.MemExecute | SectionCharacteristics.ContainsCode, name: ".text", numberOfLinenumbers: 0, numberOfRelocations: 0, pointerToLinenumbers: 0, pointerToRawData: BitArithmeticUtilities.Align(sizeOfPeHeaders, _properties.FileAlignment), pointerToRelocations: 0, relativeVirtualAddress: BitArithmeticUtilities.Align(sizeOfPeHeaders, _properties.SectionAlignment), sizeOfRawData: BitArithmeticUtilities.Align(sizeOfTextSection, _properties.FileAlignment), virtualSize: sizeOfTextSection )); int resourcesRva = BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, _properties.SectionAlignment); int sizeOfWin32Resources = this.ComputeSizeOfWin32Resources(resourcesRva); if (sizeOfWin32Resources > 0) { sectionHeaders.Add(lastSection = new SectionHeader( characteristics: SectionCharacteristics.MemRead | SectionCharacteristics.ContainsInitializedData, name: ResourceSectionName, numberOfLinenumbers: 0, numberOfRelocations: 0, pointerToLinenumbers: 0, pointerToRawData: lastSection.PointerToRawData + lastSection.SizeOfRawData, pointerToRelocations: 0, relativeVirtualAddress: resourcesRva, sizeOfRawData: BitArithmeticUtilities.Align(sizeOfWin32Resources, _properties.FileAlignment), virtualSize: sizeOfWin32Resources )); } if (_properties.RequiresStartupStub) { var size = (_properties.Requires64bits && !_properties.RequiresAmdInstructionSet) ? 14 : 12; // TODO: constants sectionHeaders.Add(lastSection = new SectionHeader( characteristics: SectionCharacteristics.MemRead | SectionCharacteristics.MemDiscardable | SectionCharacteristics.ContainsInitializedData, name: RelocationSectionName, numberOfLinenumbers: 0, numberOfRelocations: 0, pointerToLinenumbers: 0, pointerToRawData: lastSection.PointerToRawData + lastSection.SizeOfRawData, pointerToRelocations: 0, relativeVirtualAddress: BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, _properties.SectionAlignment), sizeOfRawData: BitArithmeticUtilities.Align(size, _properties.FileAlignment), virtualSize: size)); } Debug.Assert(sectionHeaders.Count == sectionCount); return sectionHeaders; } private const string CorEntryPointDll = "mscoree.dll"; private string CorEntryPointName => (_properties.ImageCharacteristics & Characteristics.Dll) != 0 ? "_CorDllMain" : "_CorExeMain"; private int SizeOfImportAddressTable => _properties.RequiresStartupStub ? (_is32bit ? 2 * sizeof(uint) : 2 * sizeof(ulong)) : 0; // (_is32bit ? 66 : 70); private int SizeOfImportTable => sizeof(uint) + // RVA sizeof(uint) + // 0 sizeof(uint) + // 0 sizeof(uint) + // name RVA sizeof(uint) + // import address table RVA 20 + // ? (_is32bit ? 3 * sizeof(uint) : 2 * sizeof(ulong)) + // import lookup table sizeof(ushort) + // hint CorEntryPointName.Length + 1; // NUL private static int SizeOfNameTable => CorEntryPointDll.Length + 1 + sizeof(ushort); private int SizeOfRuntimeStartupStub => _is32bit ? 8 : 16; private int CalculateOffsetToMappedFieldDataStream(MetadataSizes metadataSizes) { int result = ComputeOffsetToImportTable(metadataSizes); if (_properties.RequiresStartupStub) { result += SizeOfImportTable + SizeOfNameTable; result = BitArithmeticUtilities.Align(result, _is32bit ? 4 : 8); //optional padding to make startup stub's target address align on word or double word boundary result += SizeOfRuntimeStartupStub; } return result; } private int CalculateMappedFieldDataStreamRva(int textSectionRva, MetadataSizes metadataSizes) { return textSectionRva + CalculateOffsetToMappedFieldDataStream(metadataSizes); } /// <summary> /// Compute a deterministic Guid and timestamp based on the contents of the stream, and replace /// the 16 zero bytes at the given position and one or two 4-byte values with that computed Guid and timestamp. /// </summary> /// <param name="peStream">PE stream.</param> /// <param name="mvidPosition">Position in the stream of 16 zero bytes to be replaced by a Guid</param> /// <param name="ntHeaderTimestampPosition">Position in the stream of four zero bytes to be replaced by a timestamp</param> private static void WriteDeterministicGuidAndTimestamps( Stream peStream, long mvidPosition, long ntHeaderTimestampPosition) { Debug.Assert(mvidPosition != 0); Debug.Assert(ntHeaderTimestampPosition != 0); var previousPosition = peStream.Position; // Compute and write deterministic guid data over the relevant portion of the stream peStream.Position = 0; var contentId = ContentId.FromHash(CryptographicHashProvider.ComputeSha1(peStream)); // The existing Guid should be zero. CheckZeroDataInStream(peStream, mvidPosition, contentId.Guid.Length); peStream.Position = mvidPosition; peStream.Write(contentId.Guid, 0, contentId.Guid.Length); // The existing timestamp should be zero. CheckZeroDataInStream(peStream, ntHeaderTimestampPosition, contentId.Stamp.Length); peStream.Position = ntHeaderTimestampPosition; peStream.Write(contentId.Stamp, 0, contentId.Stamp.Length); peStream.Position = previousPosition; } [Conditional("DEBUG")] private static void CheckZeroDataInStream(Stream stream, long position, int bytes) { stream.Position = position; for (int i = 0; i < bytes; i++) { int value = stream.ReadByte(); Debug.Assert(value == 0); } } private int ComputeOffsetToDebugTable(MetadataSizes metadataSizes) { Debug.Assert(metadataSizes.MetadataSize % 4 == 0); Debug.Assert(metadataSizes.ResourceDataSize % 4 == 0); return ComputeOffsetToMetadata(metadataSizes.ILStreamSize) + metadataSizes.MetadataSize + metadataSizes.ResourceDataSize + metadataSizes.StrongNameSignatureSize; } private int ComputeOffsetToImportTable(MetadataSizes metadataSizes) { return ComputeOffsetToDebugTable(metadataSizes) + ComputeSizeOfDebugDirectory(); } private const int CorHeaderSize = sizeof(int) + // header size sizeof(short) + // major runtime version sizeof(short) + // minor runtime version sizeof(long) + // metadata directory sizeof(int) + // COR flags sizeof(int) + // entry point sizeof(long) + // resources directory sizeof(long) + // strong name signature directory sizeof(long) + // code manager table directory sizeof(long) + // vtable fixups directory sizeof(long) + // export address table jumps directory sizeof(long); // managed-native header directory private int OffsetToILStream => SizeOfImportAddressTable + CorHeaderSize; private int ComputeOffsetToMetadata(int ilStreamLength) { return OffsetToILStream + BitArithmeticUtilities.Align(ilStreamLength, 4); } private const int ImageDebugDirectoryBaseSize = sizeof(uint) + // Characteristics sizeof(uint) + // TimeDataStamp sizeof(uint) + // Version sizeof(uint) + // Type sizeof(uint) + // SizeOfData sizeof(uint) + // AddressOfRawData sizeof(uint); // PointerToRawData private int ComputeSizeOfDebugDirectoryData() { return 4 + // 4B signature "RSDS" 16 + // GUID sizeof(uint) + // Age Encoding.UTF8.GetByteCount(_pdbPathOpt) + 1; // Null terminator } private int ComputeSizeOfDebugDirectory() { return EmitPdb ? ImageDebugDirectoryBaseSize + ComputeSizeOfDebugDirectoryData() : 0; } private int ComputeSizeOfPeHeaders(int sectionCount) { int sizeOfPeHeaders = 128 + 4 + 20 + 224 + 40 * sectionCount; // TODO: constants if (!_is32bit) { sizeOfPeHeaders += 16; } return sizeOfPeHeaders; } private int ComputeSizeOfTextSection(MetadataSizes metadataSizes) { Debug.Assert(metadataSizes.MappedFieldDataSize % MetadataWriter.MappedFieldDataAlignment == 0); return CalculateOffsetToMappedFieldDataStream(metadataSizes) + metadataSizes.MappedFieldDataSize; } private int ComputeSizeOfWin32Resources(int resourcesRva) { this.SerializeWin32Resources(resourcesRva); int result = 0; if (_win32ResourceWriter.Length > 0) { result += BitArithmeticUtilities.Align(_win32ResourceWriter.Length, 4); } // result += Align(this.win32ResourceWriter.Length+1, 8); return result; } private CorHeader CreateCorHeader(MetadataSizes metadataSizes, int textSectionRva, int entryPointToken) { int metadataRva = textSectionRva + ComputeOffsetToMetadata(metadataSizes.ILStreamSize); int resourcesRva = metadataRva + metadataSizes.MetadataSize; int signatureRva = resourcesRva + metadataSizes.ResourceDataSize; return new CorHeader( entryPointTokenOrRelativeVirtualAddress: entryPointToken, flags: _properties.GetCorHeaderFlags(), metadataDirectory: new DirectoryEntry(metadataRva, metadataSizes.MetadataSize), resourcesDirectory: new DirectoryEntry(resourcesRva, metadataSizes.ResourceDataSize), strongNameSignatureDirectory: new DirectoryEntry(signatureRva, metadataSizes.StrongNameSignatureSize)); } private void FillInNtHeader( List<SectionHeader> sectionHeaders, int entryPointAddress, DirectoryEntry corHeader, DirectoryEntry importTable, DirectoryEntry importAddressTable, DirectoryEntry debugTable, out CoffHeader coffHeader, out NtHeader ntHeader) { short sectionCount = (short)sectionHeaders.Count; coffHeader = new CoffHeader( machine: (_properties.Machine == 0) ? Machine.I386 : _properties.Machine, numberOfSections: sectionCount, timeDateStamp: _timeStamp, pointerToSymbolTable: 0, numberOfSymbols: 0, sizeOfOptionalHeader: (short)(_is32bit ? 224 : 240), // TODO: constants characteristics: _properties.ImageCharacteristics); SectionHeader codeSection = sectionHeaders.FirstOrDefault(sh => (sh.Characteristics & SectionCharacteristics.ContainsCode) != 0); SectionHeader dataSection = sectionHeaders.FirstOrDefault(sh => (sh.Characteristics & SectionCharacteristics.ContainsInitializedData) != 0); ntHeader = new NtHeader(); ntHeader.Magic = _is32bit ? PEMagic.PE32 : PEMagic.PE32Plus; ntHeader.MajorLinkerVersion = _properties.LinkerMajorVersion; ntHeader.MinorLinkerVersion = _properties.LinkerMinorVersion; ntHeader.AddressOfEntryPoint = entryPointAddress; ntHeader.BaseOfCode = codeSection?.RelativeVirtualAddress ?? 0; ntHeader.BaseOfData = dataSection?.RelativeVirtualAddress ?? 0; ntHeader.ImageBase = _properties.BaseAddress; ntHeader.FileAlignment = _properties.FileAlignment; ntHeader.MajorSubsystemVersion = _properties.MajorSubsystemVersion; ntHeader.MinorSubsystemVersion = _properties.MinorSubsystemVersion; ntHeader.Subsystem = _properties.Subsystem; ntHeader.DllCharacteristics = _properties.DllCharacteristics; ntHeader.SizeOfStackReserve = _properties.SizeOfStackReserve; ntHeader.SizeOfStackCommit = _properties.SizeOfStackCommit; ntHeader.SizeOfHeapReserve = _properties.SizeOfHeapReserve; ntHeader.SizeOfHeapCommit = _properties.SizeOfHeapCommit; ntHeader.SizeOfCode = codeSection?.SizeOfRawData ?? 0; ntHeader.SizeOfInitializedData = sectionHeaders.Sum( sectionHeader => (sectionHeader.Characteristics & SectionCharacteristics.ContainsInitializedData) != 0 ? sectionHeader.SizeOfRawData : 0); ntHeader.SizeOfHeaders = BitArithmeticUtilities.Align(ComputeSizeOfPeHeaders(sectionCount), _properties.FileAlignment); var lastSection = sectionHeaders.Last(); ntHeader.SizeOfImage = BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, _properties.SectionAlignment); ntHeader.SizeOfUninitializedData = 0; ntHeader.ImportAddressTable = importAddressTable; ntHeader.CliHeaderTable = corHeader; ntHeader.ImportTable = importTable; var relocSection = sectionHeaders.FirstOrDefault(sectionHeader => sectionHeader.Name == RelocationSectionName); if (relocSection != null) { ntHeader.BaseRelocationTable = new DirectoryEntry(relocSection.RelativeVirtualAddress, relocSection.VirtualSize); } ntHeader.DebugTable = debugTable; var resourceSection = sectionHeaders.FirstOrDefault(sectionHeader => sectionHeader.Name == ResourceSectionName); if (resourceSection != null) { ntHeader.ResourceTable = new DirectoryEntry(resourceSection.RelativeVirtualAddress, resourceSection.VirtualSize); } } //// //// Resource Format. //// //// //// Resource directory consists of two counts, following by a variable length //// array of directory entries. The first count is the number of entries at //// beginning of the array that have actual names associated with each entry. //// The entries are in ascending order, case insensitive strings. The second //// count is the number of entries that immediately follow the named entries. //// This second count identifies the number of entries that have 16-bit integer //// Ids as their name. These entries are also sorted in ascending order. //// //// This structure allows fast lookup by either name or number, but for any //// given resource entry only one form of lookup is supported, not both. //// This is consistent with the syntax of the .RC file and the .RES file. //// //typedef struct _IMAGE_RESOURCE_DIRECTORY { // DWORD Characteristics; // DWORD TimeDateStamp; // WORD MajorVersion; // WORD MinorVersion; // WORD NumberOfNamedEntries; // WORD NumberOfIdEntries; //// IMAGE_RESOURCE_DIRECTORY_ENTRY DirectoryEntries[]; //} IMAGE_RESOURCE_DIRECTORY, *PIMAGE_RESOURCE_DIRECTORY; //#define IMAGE_RESOURCE_NAME_IS_STRING 0x80000000 //#define IMAGE_RESOURCE_DATA_IS_DIRECTORY 0x80000000 //// //// Each directory contains the 32-bit Name of the entry and an offset, //// relative to the beginning of the resource directory of the data associated //// with this directory entry. If the name of the entry is an actual text //// string instead of an integer Id, then the high order bit of the name field //// is set to one and the low order 31-bits are an offset, relative to the //// beginning of the resource directory of the string, which is of type //// IMAGE_RESOURCE_DIRECTORY_STRING. Otherwise the high bit is clear and the //// low-order 16-bits are the integer Id that identify this resource directory //// entry. If the directory entry is yet another resource directory (i.e. a //// subdirectory), then the high order bit of the offset field will be //// set to indicate this. Otherwise the high bit is clear and the offset //// field points to a resource data entry. //// //typedef struct _IMAGE_RESOURCE_DIRECTORY_ENTRY { // union { // struct { // DWORD NameOffset:31; // DWORD NameIsString:1; // } DUMMYSTRUCTNAME; // DWORD Name; // WORD Id; // } DUMMYUNIONNAME; // union { // DWORD OffsetToData; // struct { // DWORD OffsetToDirectory:31; // DWORD DataIsDirectory:1; // } DUMMYSTRUCTNAME2; // } DUMMYUNIONNAME2; //} IMAGE_RESOURCE_DIRECTORY_ENTRY, *PIMAGE_RESOURCE_DIRECTORY_ENTRY; //// //// For resource directory entries that have actual string names, the Name //// field of the directory entry points to an object of the following type. //// All of these string objects are stored together after the last resource //// directory entry and before the first resource data object. This minimizes //// the impact of these variable length objects on the alignment of the fixed //// size directory entry objects. //// //typedef struct _IMAGE_RESOURCE_DIRECTORY_STRING { // WORD Length; // CHAR NameString[ 1 ]; //} IMAGE_RESOURCE_DIRECTORY_STRING, *PIMAGE_RESOURCE_DIRECTORY_STRING; //typedef struct _IMAGE_RESOURCE_DIR_STRING_U { // WORD Length; // WCHAR NameString[ 1 ]; //} IMAGE_RESOURCE_DIR_STRING_U, *PIMAGE_RESOURCE_DIR_STRING_U; //// //// Each resource data entry describes a leaf node in the resource directory //// tree. It contains an offset, relative to the beginning of the resource //// directory of the data for the resource, a size field that gives the number //// of bytes of data at that offset, a CodePage that should be used when //// decoding code point values within the resource data. Typically for new //// applications the code page would be the unicode code page. //// //typedef struct _IMAGE_RESOURCE_DATA_ENTRY { // DWORD OffsetToData; // DWORD Size; // DWORD CodePage; // DWORD Reserved; //} IMAGE_RESOURCE_DATA_ENTRY, *PIMAGE_RESOURCE_DATA_ENTRY; private class Directory { internal readonly string Name; internal readonly int ID; internal ushort NumberOfNamedEntries; internal ushort NumberOfIdEntries; internal readonly List<object> Entries; internal Directory(string name, int id) { this.Name = name; this.ID = id; this.Entries = new List<object>(); } } private static int CompareResources(IWin32Resource left, IWin32Resource right) { int result = CompareResourceIdentifiers(left.TypeId, left.TypeName, right.TypeId, right.TypeName); return (result == 0) ? CompareResourceIdentifiers(left.Id, left.Name, right.Id, right.Name) : result; } //when comparing a string vs ordinal, the string should always be less than the ordinal. Per the spec, //entries identified by string must precede those identified by ordinal. private static int CompareResourceIdentifiers(int xOrdinal, string xString, int yOrdinal, string yString) { if (xString == null) { if (yString == null) { return xOrdinal - yOrdinal; } else { return 1; } } else if (yString == null) { return -1; } else { return String.Compare(xString, yString, StringComparison.OrdinalIgnoreCase); } } //sort the resources by ID least to greatest then by NAME. //Where strings and ordinals are compared, strings are less than ordinals. internal static IEnumerable<IWin32Resource> SortResources(IEnumerable<IWin32Resource> resources) { return resources.OrderBy(CompareResources); } //Win32 resources are supplied to the compiler in one of two forms, .RES (the output of the resource compiler), //or .OBJ (the output of running cvtres.exe on a .RES file). A .RES file is parsed and processed into //a set of objects implementing IWin32Resources. These are then ordered and the final image form is constructed //and written to the resource section. Resources in .OBJ form are already very close to their final output //form. Rather than reading them and parsing them into a set of objects similar to those produced by //processing a .RES file, we process them like the native linker would, copy the relevant sections from //the .OBJ into our output and apply some fixups. private void SerializeWin32Resources(int resourcesRva) { if (_nativeResourceSectionOpt != null) { SerializeWin32Resources(_nativeResourceSectionOpt, resourcesRva); return; } if (IteratorHelper.EnumerableIsEmpty(_nativeResourcesOpt)) { return; } SerializeWin32Resources(_nativeResourcesOpt, resourcesRva); } private void SerializeWin32Resources(IEnumerable<IWin32Resource> theResources, int resourcesRva) { theResources = SortResources(theResources); Directory typeDirectory = new Directory(string.Empty, 0); Directory nameDirectory = null; Directory languageDirectory = null; int lastTypeID = int.MinValue; string lastTypeName = null; int lastID = int.MinValue; string lastName = null; uint sizeOfDirectoryTree = 16; //EDMAURER note that this list is assumed to be sorted lowest to highest //first by typeId, then by Id. foreach (IWin32Resource r in theResources) { bool typeDifferent = (r.TypeId < 0 && r.TypeName != lastTypeName) || r.TypeId > lastTypeID; if (typeDifferent) { lastTypeID = r.TypeId; lastTypeName = r.TypeName; if (lastTypeID < 0) { Debug.Assert(typeDirectory.NumberOfIdEntries == 0, "Not all Win32 resources with types encoded as strings precede those encoded as ints"); typeDirectory.NumberOfNamedEntries++; } else { typeDirectory.NumberOfIdEntries++; } sizeOfDirectoryTree += 24; typeDirectory.Entries.Add(nameDirectory = new Directory(lastTypeName, lastTypeID)); } if (typeDifferent || (r.Id < 0 && r.Name != lastName) || r.Id > lastID) { lastID = r.Id; lastName = r.Name; if (lastID < 0) { Debug.Assert(nameDirectory.NumberOfIdEntries == 0, "Not all Win32 resources with names encoded as strings precede those encoded as ints"); nameDirectory.NumberOfNamedEntries++; } else { nameDirectory.NumberOfIdEntries++; } sizeOfDirectoryTree += 24; nameDirectory.Entries.Add(languageDirectory = new Directory(lastName, lastID)); } languageDirectory.NumberOfIdEntries++; sizeOfDirectoryTree += 8; languageDirectory.Entries.Add(r); } var dataWriter = BlobBuilder.GetInstance(); //'dataWriter' is where opaque resource data goes as well as strings that are used as type or name identifiers this.WriteDirectory(typeDirectory, _win32ResourceWriter, 0, 0, sizeOfDirectoryTree, resourcesRva, dataWriter); dataWriter.WriteTo(_win32ResourceWriter); _win32ResourceWriter.WriteByte(0); while ((_win32ResourceWriter.Length % 4) != 0) { _win32ResourceWriter.WriteByte(0); } dataWriter.Free(); } private void WriteDirectory(Directory directory, BlobBuilder writer, uint offset, uint level, uint sizeOfDirectoryTree, int virtualAddressBase, BlobBuilder dataWriter) { writer.WriteUInt32(0); // Characteristics writer.WriteUInt32(0); // Timestamp writer.WriteUInt32(0); // Version writer.WriteUInt16(directory.NumberOfNamedEntries); writer.WriteUInt16(directory.NumberOfIdEntries); uint n = (uint)directory.Entries.Count; uint k = offset + 16 + n * 8; for (int i = 0; i < n; i++) { int id; string name; uint nameOffset = (uint)dataWriter.Position + sizeOfDirectoryTree; uint directoryOffset = k; Directory subDir = directory.Entries[i] as Directory; if (subDir != null) { id = subDir.ID; name = subDir.Name; if (level == 0) { k += SizeOfDirectory(subDir); } else { k += 16 + 8 * (uint)subDir.Entries.Count; } } else { //EDMAURER write out an IMAGE_RESOURCE_DATA_ENTRY followed //immediately by the data that it refers to. This results //in a layout different than that produced by pulling the resources //from an OBJ. In that case all of the data bits of a resource are //contiguous in .rsrc$02. After processing these will end up at //the end of .rsrc following all of the directory //info and IMAGE_RESOURCE_DATA_ENTRYs IWin32Resource r = (IWin32Resource)directory.Entries[i]; id = level == 0 ? r.TypeId : level == 1 ? r.Id : (int)r.LanguageId; name = level == 0 ? r.TypeName : level == 1 ? r.Name : null; dataWriter.WriteUInt32((uint)(virtualAddressBase + sizeOfDirectoryTree + 16 + dataWriter.Position)); byte[] data = new List<byte>(r.Data).ToArray(); dataWriter.WriteUInt32((uint)data.Length); dataWriter.WriteUInt32(r.CodePage); dataWriter.WriteUInt32(0); dataWriter.WriteBytes(data); while ((dataWriter.Length % 4) != 0) { dataWriter.WriteByte(0); } } if (id >= 0) { writer.WriteInt32(id); } else { if (name == null) { name = string.Empty; } writer.WriteUInt32(nameOffset | 0x80000000); dataWriter.WriteUInt16((ushort)name.Length); dataWriter.WriteUTF16(name); } if (subDir != null) { writer.WriteUInt32(directoryOffset | 0x80000000); } else { writer.WriteUInt32(nameOffset); } } k = offset + 16 + n * 8; for (int i = 0; i < n; i++) { Directory subDir = directory.Entries[i] as Directory; if (subDir != null) { this.WriteDirectory(subDir, writer, k, level + 1, sizeOfDirectoryTree, virtualAddressBase, dataWriter); if (level == 0) { k += SizeOfDirectory(subDir); } else { k += 16 + 8 * (uint)subDir.Entries.Count; } } } } private static uint SizeOfDirectory(Directory/*!*/ directory) { uint n = (uint)directory.Entries.Count; uint size = 16 + 8 * n; for (int i = 0; i < n; i++) { Directory subDir = directory.Entries[i] as Directory; if (subDir != null) { size += 16 + 8 * (uint)subDir.Entries.Count; } } return size; } private void SerializeWin32Resources(ResourceSection resourceSections, int resourcesRva) { _win32ResourceWriter.WriteBytes(resourceSections.SectionBytes); var savedPosition = _win32ResourceWriter.Position; var readStream = new MemoryStream(resourceSections.SectionBytes); var reader = new BinaryReader(readStream); foreach (int addressToFixup in resourceSections.Relocations) { _win32ResourceWriter.SetPosition(addressToFixup); reader.BaseStream.Position = addressToFixup; _win32ResourceWriter.WriteUInt32(reader.ReadUInt32() + (uint)resourcesRva); } _win32ResourceWriter.SetPosition(savedPosition); } //#define IMAGE_FILE_RELOCS_STRIPPED 0x0001 // Relocation info stripped from file. //#define IMAGE_FILE_EXECUTABLE_IMAGE 0x0002 // File is executable (i.e. no unresolved external references). //#define IMAGE_FILE_LINE_NUMS_STRIPPED 0x0004 // Line numbers stripped from file. //#define IMAGE_FILE_LOCAL_SYMS_STRIPPED 0x0008 // Local symbols stripped from file. //#define IMAGE_FILE_AGGRESIVE_WS_TRIM 0x0010 // Aggressively trim working set //#define IMAGE_FILE_LARGE_ADDRESS_AWARE 0x0020 // App can handle >2gb addresses //#define IMAGE_FILE_BYTES_REVERSED_LO 0x0080 // Bytes of machine word are reversed. //#define IMAGE_FILE_32BIT_MACHINE 0x0100 // 32 bit word machine. //#define IMAGE_FILE_DEBUG_STRIPPED 0x0200 // Debugging info stripped from file in .DBG file //#define IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP 0x0400 // If Image is on removable media, copy and run from the swap file. //#define IMAGE_FILE_NET_RUN_FROM_SWAP 0x0800 // If Image is on Net, copy and run from the swap file. //#define IMAGE_FILE_SYSTEM 0x1000 // System File. //#define IMAGE_FILE_DLL 0x2000 // File is a DLL. //#define IMAGE_FILE_UP_SYSTEM_ONLY 0x4000 // File should only be run on a UP machine //#define IMAGE_FILE_BYTES_REVERSED_HI 0x8000 // Bytes of machine word are reversed. private static readonly byte[] s_dosHeader = new byte[] { 0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; private void WriteHeaders(Stream peStream, NtHeader ntHeader, CoffHeader coffHeader, List<SectionHeader> sectionHeaders, out long ntHeaderTimestampPosition) { var writer = new BlobBuilder(1024); // MS-DOS stub (128 bytes) writer.WriteBytes(s_dosHeader); // PE Signature "PE\0\0" writer.WriteUInt32(0x00004550); // COFF Header (20 bytes) writer.WriteUInt16((ushort)coffHeader.Machine); writer.WriteUInt16((ushort)coffHeader.NumberOfSections); ntHeaderTimestampPosition = writer.Position + peStream.Position; writer.WriteUInt32((uint)coffHeader.TimeDateStamp); writer.WriteUInt32((uint)coffHeader.PointerToSymbolTable); writer.WriteUInt32((uint)coffHeader.NumberOfSymbols); writer.WriteUInt16((ushort)(_is32bit ? 224 : 240)); // SizeOfOptionalHeader writer.WriteUInt16((ushort)coffHeader.Characteristics); // PE Headers: writer.WriteUInt16((ushort)(_is32bit ? PEMagic.PE32 : PEMagic.PE32Plus)); // 2 writer.WriteByte(ntHeader.MajorLinkerVersion); // 3 writer.WriteByte(ntHeader.MinorLinkerVersion); // 4 writer.WriteUInt32((uint)ntHeader.SizeOfCode); // 8 writer.WriteUInt32((uint)ntHeader.SizeOfInitializedData); // 12 writer.WriteUInt32((uint)ntHeader.SizeOfUninitializedData); // 16 writer.WriteUInt32((uint)ntHeader.AddressOfEntryPoint); // 20 writer.WriteUInt32((uint)ntHeader.BaseOfCode); // 24 if (_is32bit) { writer.WriteUInt32((uint)ntHeader.BaseOfData); // 28 writer.WriteUInt32((uint)ntHeader.ImageBase); // 32 } else { writer.WriteUInt64(ntHeader.ImageBase); // 32 } // NT additional fields: writer.WriteUInt32((uint)ntHeader.SectionAlignment); // 36 writer.WriteUInt32((uint)ntHeader.FileAlignment); // 40 writer.WriteUInt16(ntHeader.MajorOperatingSystemVersion); // 42 writer.WriteUInt16(ntHeader.MinorOperatingSystemVersion); // 44 writer.WriteUInt16(ntHeader.MajorImageVersion); // 46 writer.WriteUInt16(ntHeader.MinorImageVersion); // 48 writer.WriteUInt16(ntHeader.MajorSubsystemVersion); // MajorSubsystemVersion 50 writer.WriteUInt16(ntHeader.MinorSubsystemVersion); // MinorSubsystemVersion 52 // Win32VersionValue (reserved, should be 0) writer.WriteUInt32(0); // 56 writer.WriteUInt32((uint)ntHeader.SizeOfImage); // 60 writer.WriteUInt32((uint)ntHeader.SizeOfHeaders); // 64 writer.WriteUInt32(ntHeader.Checksum); // 68 writer.WriteUInt16((ushort)ntHeader.Subsystem); // 70 writer.WriteUInt16((ushort)ntHeader.DllCharacteristics); if (_is32bit) { writer.WriteUInt32((uint)ntHeader.SizeOfStackReserve); // 76 writer.WriteUInt32((uint)ntHeader.SizeOfStackCommit); // 80 writer.WriteUInt32((uint)ntHeader.SizeOfHeapReserve); // 84 writer.WriteUInt32((uint)ntHeader.SizeOfHeapCommit); // 88 } else { writer.WriteUInt64(ntHeader.SizeOfStackReserve); // 80 writer.WriteUInt64(ntHeader.SizeOfStackCommit); // 88 writer.WriteUInt64(ntHeader.SizeOfHeapReserve); // 96 writer.WriteUInt64(ntHeader.SizeOfHeapCommit); // 104 } // LoaderFlags writer.WriteUInt32(0); // 92|108 // The number of data-directory entries in the remainder of the header. writer.WriteUInt32(16); // 96|112 // directory entries: writer.WriteUInt32((uint)ntHeader.ExportTable.RelativeVirtualAddress); // 100|116 writer.WriteUInt32((uint)ntHeader.ExportTable.Size); // 104|120 writer.WriteUInt32((uint)ntHeader.ImportTable.RelativeVirtualAddress); // 108|124 writer.WriteUInt32((uint)ntHeader.ImportTable.Size); // 112|128 writer.WriteUInt32((uint)ntHeader.ResourceTable.RelativeVirtualAddress); // 116|132 writer.WriteUInt32((uint)ntHeader.ResourceTable.Size); // 120|136 writer.WriteUInt32((uint)ntHeader.ExceptionTable.RelativeVirtualAddress); // 124|140 writer.WriteUInt32((uint)ntHeader.ExceptionTable.Size); // 128|144 writer.WriteUInt32((uint)ntHeader.CertificateTable.RelativeVirtualAddress); // 132|148 writer.WriteUInt32((uint)ntHeader.CertificateTable.Size); // 136|152 writer.WriteUInt32((uint)ntHeader.BaseRelocationTable.RelativeVirtualAddress); // 140|156 writer.WriteUInt32((uint)ntHeader.BaseRelocationTable.Size); // 144|160 writer.WriteUInt32((uint)ntHeader.DebugTable.RelativeVirtualAddress); // 148|164 writer.WriteUInt32((uint)ntHeader.DebugTable.Size); // 152|168 writer.WriteUInt32((uint)ntHeader.CopyrightTable.RelativeVirtualAddress); // 156|172 writer.WriteUInt32((uint)ntHeader.CopyrightTable.Size); // 160|176 writer.WriteUInt32((uint)ntHeader.GlobalPointerTable.RelativeVirtualAddress); // 164|180 writer.WriteUInt32((uint)ntHeader.GlobalPointerTable.Size); // 168|184 writer.WriteUInt32((uint)ntHeader.ThreadLocalStorageTable.RelativeVirtualAddress); // 172|188 writer.WriteUInt32((uint)ntHeader.ThreadLocalStorageTable.Size); // 176|192 writer.WriteUInt32((uint)ntHeader.LoadConfigTable.RelativeVirtualAddress); // 180|196 writer.WriteUInt32((uint)ntHeader.LoadConfigTable.Size); // 184|200 writer.WriteUInt32((uint)ntHeader.BoundImportTable.RelativeVirtualAddress); // 188|204 writer.WriteUInt32((uint)ntHeader.BoundImportTable.Size); // 192|208 writer.WriteUInt32((uint)ntHeader.ImportAddressTable.RelativeVirtualAddress); // 196|212 writer.WriteUInt32((uint)ntHeader.ImportAddressTable.Size); // 200|216 writer.WriteUInt32((uint)ntHeader.DelayImportTable.RelativeVirtualAddress); // 204|220 writer.WriteUInt32((uint)ntHeader.DelayImportTable.Size); // 208|224 writer.WriteUInt32((uint)ntHeader.CliHeaderTable.RelativeVirtualAddress); // 212|228 writer.WriteUInt32((uint)ntHeader.CliHeaderTable.Size); // 216|232 writer.WriteUInt64(0); // 224|240 // Section Headers foreach (var sectionHeader in sectionHeaders) { WriteSectionHeader(sectionHeader, writer); } writer.WriteTo(peStream); } private static void WriteSectionHeader(SectionHeader sectionHeader, BlobBuilder writer) { if (sectionHeader.VirtualSize == 0) { return; } for (int j = 0, m = sectionHeader.Name.Length; j < 8; j++) { if (j < m) { writer.WriteByte((byte)sectionHeader.Name[j]); } else { writer.WriteByte(0); } } writer.WriteUInt32((uint)sectionHeader.VirtualSize); writer.WriteUInt32((uint)sectionHeader.RelativeVirtualAddress); writer.WriteUInt32((uint)sectionHeader.SizeOfRawData); writer.WriteUInt32((uint)sectionHeader.PointerToRawData); writer.WriteUInt32((uint)sectionHeader.PointerToRelocations); writer.WriteUInt32((uint)sectionHeader.PointerToLinenumbers); writer.WriteUInt16(sectionHeader.NumberOfRelocations); writer.WriteUInt16(sectionHeader.NumberOfLinenumbers); writer.WriteUInt32((uint)sectionHeader.Characteristics); } private void WriteTextSection( Stream peStream, SectionHeader textSection, int importTableRva, int importAddressTableRva, int entryPointToken, BlobBuilder metadataWriter, BlobBuilder ilWriter, BlobBuilder mappedFieldDataWriter, BlobBuilder managedResourceWriter, MetadataSizes metadataSizes, ContentId nativePdbContentId, ContentId portablePdbContentId, out long metadataPosition) { // TODO: zero out all bytes: peStream.Position = textSection.PointerToRawData; if (_properties.RequiresStartupStub) { WriteImportAddressTable(peStream, importTableRva); } var corHeader = CreateCorHeader(metadataSizes, textSection.RelativeVirtualAddress, entryPointToken); WriteCorHeader(peStream, corHeader); // IL: ilWriter.Align(4); ilWriter.WriteTo(peStream); // metadata: metadataPosition = peStream.Position; Debug.Assert(metadataWriter.Length % 4 == 0); metadataWriter.WriteTo(peStream); // managed resources: Debug.Assert(managedResourceWriter.Length % 4 == 0); managedResourceWriter.WriteTo(peStream); // strong name signature: WriteSpaceForHash(peStream, metadataSizes.StrongNameSignatureSize); if (EmitPdb) { WriteDebugTable(peStream, textSection, nativePdbContentId, portablePdbContentId, metadataSizes); } if (_properties.RequiresStartupStub) { WriteImportTable(peStream, importTableRva, importAddressTableRva); WriteNameTable(peStream); WriteRuntimeStartupStub(peStream, importAddressTableRva); } // mapped field data: mappedFieldDataWriter.WriteTo(peStream); // TODO: zero out all bytes: int alignedPosition = textSection.PointerToRawData + textSection.SizeOfRawData; if (peStream.Position != alignedPosition) { peStream.Position = alignedPosition - 1; peStream.WriteByte(0); } } private void WriteImportAddressTable(Stream peStream, int importTableRva) { var writer = new BlobBuilder(SizeOfImportAddressTable); int ilRVA = importTableRva + 40; int hintRva = ilRVA + (_is32bit ? 12 : 16); // Import Address Table if (_is32bit) { writer.WriteUInt32((uint)hintRva); // 4 writer.WriteUInt32(0); // 8 } else { writer.WriteUInt64((uint)hintRva); // 8 writer.WriteUInt64(0); // 16 } Debug.Assert(writer.Length == SizeOfImportAddressTable); writer.WriteTo(peStream); } private void WriteImportTable(Stream peStream, int importTableRva, int importAddressTableRva) { var writer = new BlobBuilder(SizeOfImportTable); int ilRVA = importTableRva + 40; int hintRva = ilRVA + (_is32bit ? 12 : 16); int nameRva = hintRva + 12 + 2; // Import table writer.WriteUInt32((uint)ilRVA); // 4 writer.WriteUInt32(0); // 8 writer.WriteUInt32(0); // 12 writer.WriteUInt32((uint)nameRva); // 16 writer.WriteUInt32((uint)importAddressTableRva); // 20 writer.WriteBytes(0, 20); // 40 // Import Lookup table if (_is32bit) { writer.WriteUInt32((uint)hintRva); // 44 writer.WriteUInt32(0); // 48 writer.WriteUInt32(0); // 52 } else { writer.WriteUInt64((uint)hintRva); // 48 writer.WriteUInt64(0); // 56 } // Hint table writer.WriteUInt16(0); // Hint 54|58 foreach (char ch in CorEntryPointName) { writer.WriteByte((byte)ch); // 65|69 } writer.WriteByte(0); // 66|70 Debug.Assert(writer.Length == SizeOfImportTable); writer.WriteTo(peStream); } private static void WriteNameTable(Stream peStream) { var writer = new BlobBuilder(SizeOfNameTable); foreach (char ch in CorEntryPointDll) { writer.WriteByte((byte)ch); } writer.WriteByte(0); writer.WriteUInt16(0); Debug.Assert(writer.Length == SizeOfNameTable); writer.WriteTo(peStream); } private static void WriteCorHeader(Stream peStream, CorHeader corHeader) { var writer = new BlobBuilder(CorHeaderSize); writer.WriteUInt32(CorHeaderSize); writer.WriteUInt16(corHeader.MajorRuntimeVersion); writer.WriteUInt16(corHeader.MinorRuntimeVersion); writer.WriteUInt32((uint)corHeader.MetadataDirectory.RelativeVirtualAddress); writer.WriteUInt32((uint)corHeader.MetadataDirectory.Size); writer.WriteUInt32((uint)corHeader.Flags); writer.WriteUInt32((uint)corHeader.EntryPointTokenOrRelativeVirtualAddress); writer.WriteUInt32((uint)(corHeader.ResourcesDirectory.Size == 0 ? 0 : corHeader.ResourcesDirectory.RelativeVirtualAddress)); // 28 writer.WriteUInt32((uint)corHeader.ResourcesDirectory.Size); writer.WriteUInt32((uint)(corHeader.StrongNameSignatureDirectory.Size == 0 ? 0 : corHeader.StrongNameSignatureDirectory.RelativeVirtualAddress)); // 36 writer.WriteUInt32((uint)corHeader.StrongNameSignatureDirectory.Size); writer.WriteUInt32((uint)corHeader.CodeManagerTableDirectory.RelativeVirtualAddress); writer.WriteUInt32((uint)corHeader.CodeManagerTableDirectory.Size); writer.WriteUInt32((uint)corHeader.VtableFixupsDirectory.RelativeVirtualAddress); writer.WriteUInt32((uint)corHeader.VtableFixupsDirectory.Size); writer.WriteUInt32((uint)corHeader.ExportAddressTableJumpsDirectory.RelativeVirtualAddress); writer.WriteUInt32((uint)corHeader.ExportAddressTableJumpsDirectory.Size); writer.WriteUInt64(0); Debug.Assert(writer.Length == CorHeaderSize); Debug.Assert(writer.Length % 4 == 0); writer.WriteTo(peStream); } private static void WriteSpaceForHash(Stream peStream, int strongNameSignatureSize) { while (strongNameSignatureSize > 0) { peStream.WriteByte(0); strongNameSignatureSize--; } } private void WriteDebugTable(Stream peStream, SectionHeader textSection, ContentId nativePdbContentId, ContentId portablePdbContentId, MetadataSizes metadataSizes) { Debug.Assert(nativePdbContentId.IsDefault ^ portablePdbContentId.IsDefault); var writer = new BlobBuilder(); // characteristics: writer.WriteUInt32(0); // PDB stamp & version if (portablePdbContentId.IsDefault) { writer.WriteBytes(nativePdbContentId.Stamp); writer.WriteUInt32(0); } else { writer.WriteBytes(portablePdbContentId.Stamp); writer.WriteUInt32('P' << 24 | 'M' << 16 | 0x00 << 8 | 0x01); } // type: const int ImageDebugTypeCodeView = 2; writer.WriteUInt32(ImageDebugTypeCodeView); // size of data: writer.WriteUInt32((uint)ComputeSizeOfDebugDirectoryData()); uint dataOffset = (uint)ComputeOffsetToDebugTable(metadataSizes) + ImageDebugDirectoryBaseSize; // PointerToRawData (RVA of the data): writer.WriteUInt32((uint)textSection.RelativeVirtualAddress + dataOffset); // AddressOfRawData (position of the data in the PE stream): writer.WriteUInt32((uint)textSection.PointerToRawData + dataOffset); writer.WriteByte((byte)'R'); writer.WriteByte((byte)'S'); writer.WriteByte((byte)'D'); writer.WriteByte((byte)'S'); // PDB id: writer.WriteBytes(nativePdbContentId.Guid ?? portablePdbContentId.Guid); // age writer.WriteUInt32(PdbWriter.Age); // UTF-8 encoded zero-terminated path to PDB writer.WriteUTF8(_pdbPathOpt); writer.WriteByte(0); writer.WriteTo(peStream); writer.Free(); } private void WriteRuntimeStartupStub(Stream peStream, int importAddressTableRva) { var writer = new BlobBuilder(16); // entry point code, consisting of a jump indirect to _CorXXXMain if (_is32bit) { //emit 0's (nops) to pad the entry point code so that the target address is aligned on a 4 byte boundary. for (uint i = 0, n = (uint)(BitArithmeticUtilities.Align((uint)peStream.Position, 4) - peStream.Position); i < n; i++) { writer.WriteByte(0); } writer.WriteUInt16(0); writer.WriteByte(0xff); writer.WriteByte(0x25); //4 writer.WriteUInt32((uint)importAddressTableRva + (uint)_properties.BaseAddress); //8 } else { //emit 0's (nops) to pad the entry point code so that the target address is aligned on a 8 byte boundary. for (uint i = 0, n = (uint)(BitArithmeticUtilities.Align((uint)peStream.Position, 8) - peStream.Position); i < n; i++) { writer.WriteByte(0); } writer.WriteUInt32(0); writer.WriteUInt16(0); writer.WriteByte(0xff); writer.WriteByte(0x25); //8 writer.WriteUInt64((ulong)importAddressTableRva + _properties.BaseAddress); //16 } writer.WriteTo(peStream); } private void WriteRelocSection(Stream peStream, SectionHeader relocSection, int entryPointAddress) { peStream.Position = relocSection.PointerToRawData; var writer = new BlobBuilder(relocSection.SizeOfRawData); writer.WriteUInt32((((uint)entryPointAddress + 2) / 0x1000) * 0x1000); writer.WriteUInt32(_properties.Requires64bits && !_properties.RequiresAmdInstructionSet ? 14u : 12u); uint offsetWithinPage = ((uint)entryPointAddress + 2) % 0x1000; uint relocType = _properties.Requires64bits ? 10u : 3u; ushort s = (ushort)((relocType << 12) | offsetWithinPage); writer.WriteUInt16(s); if (_properties.Requires64bits && !_properties.RequiresAmdInstructionSet) { writer.WriteUInt32(relocType << 12); } writer.WriteUInt16(0); // next chunk's RVA writer.PadTo(relocSection.SizeOfRawData); writer.WriteTo(peStream); } private void WriteResourceSection(Stream peStream, SectionHeader resourceSection) { peStream.Position = resourceSection.PointerToRawData; _win32ResourceWriter.PadTo(resourceSection.SizeOfRawData); _win32ResourceWriter.WriteTo(peStream); } } }
using UnityEngine; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; [CanEditMultipleObjects] [CustomEditor(typeof(SgtFlareMesh))] public class SgtFlareMesh_Editor : SgtEditor<SgtFlareMesh> { protected override void OnInspector() { var updateMesh = false; var updateApply = false; BeginError(Any(t => t.Flare == null)); DrawDefault("Flare", ref updateApply); EndError(); BeginError(Any(t => t.Detail <= 2)); DrawDefault("Detail", ref updateMesh); EndError(); BeginError(Any(t => t.Radius <= 0.0f)); DrawDefault("Radius", ref updateMesh); EndError(); Separator(); DrawDefault("Wave", ref updateMesh); if (Any(t => t.Wave == true)) { BeginIndent(); DrawDefault("WaveStrength", ref updateMesh); BeginError(Any(t => t.WavePoints < 0)); DrawDefault("WavePoints", ref updateMesh); EndError(); BeginError(Any(t => t.WavePower < 1.0f)); DrawDefault("WavePower", ref updateMesh); EndError(); DrawDefault("WavePhase", ref updateMesh); EndIndent(); } Separator(); DrawDefault("Noise", ref updateMesh); if (Any(t => t.Noise == true)) { BeginIndent(); BeginError(Any(t => t.NoiseStrength < 0.0f)); DrawDefault("NoiseStrength", ref updateMesh); EndError(); BeginError(Any(t => t.NoisePoints <= 0)); DrawDefault("NoisePoints", ref updateMesh); EndError(); DrawDefault("NoisePhase", ref updateMesh); DrawDefault("NoiseSeed", ref updateMesh); EndIndent(); } if (updateMesh == true) DirtyEach(t => t.UpdateMesh ()); if (updateApply == true) DirtyEach(t => t.UpdateApply()); } } #endif [ExecuteInEditMode] [AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Flare Mesh")] public class SgtFlareMesh : MonoBehaviour { [Tooltip("The flare this mesh will be applied to")] public SgtFlare Flare; [Tooltip("The amount of points used to make the flare mesh")] public int Detail = 512; [Tooltip("The base radius of the flare in local space")] public float Radius = 2.0f; [Tooltip("Deform the flare based on cosine wave?")] public bool Wave; [Tooltip("The strength of the wave in local space")] public float WaveStrength = 5.0f; [Tooltip("The amount of wave peaks")] public int WavePoints = 4; [Tooltip("The sharpness of the waves")] public float WavePower = 5.0f; [Tooltip("The angle offset of the waves")] public float WavePhase; [Tooltip("Deform the flare based on noise?")] public bool Noise; [Tooltip("The strength of the noise in local space")] public float NoiseStrength = 5.0f; [Tooltip("The amount of noise points")] public int NoisePoints = 50; [Tooltip("The sharpness of the noise")] public float NoisePower = 5.0f; [Tooltip("The angle offset of the noise")] public float NoisePhase; [Tooltip("The random seed used for the random noise")] [SgtSeed] public int NoiseSeed; [System.NonSerialized] private Mesh generatedMesh; [SerializeField] [HideInInspector] private bool startCalled; private static List<float> points = new List<float>(); public Mesh GeneratedMesh { get { return generatedMesh; } } #if UNITY_EDITOR [ContextMenu("Export Mesh")] public void ExportMesh() { SgtHelper.ExportAssetDialog(generatedMesh, "Flare Mesh"); } #endif [ContextMenu("Update Mesh")] public void UpdateMesh() { if (Detail > 2) { if (generatedMesh == null) { generatedMesh = SgtHelper.CreateTempMesh("Flare Mesh (Generated)"); UpdateApply(); } var total = Detail + 1; var positions = new Vector3[total]; var coords1 = new Vector2[total]; var indices = new int[Detail * 3]; var angleStep = (Mathf.PI * 2.0f) / Detail; var noiseStep = 0.0f; if (Noise == true && NoisePoints > 0) { SgtHelper.BeginRandomSeed(NoiseSeed); { points.Clear(); for (var i = 0; i < NoisePoints; i++) { points.Add(Random.value); } noiseStep = NoisePoints / (float)Detail; } SgtHelper.EndRandomSeed(); } for (var point = 0; point < Detail; point++) { var v = point + 1; var angle = angleStep * point; var x = Mathf.Sin(angle); var y = Mathf.Cos(angle); var r = Radius; if (Wave == true) { var waveAngle = (angle + WavePhase * Mathf.Deg2Rad) * WavePoints; r += Mathf.Pow(Mathf.Cos(waveAngle) * 0.5f + 0.5f, WavePower * WavePower) * WaveStrength; } if (Noise == true && NoisePoints > 0) { //var noise = Mathf.Repeat(noiseStep * point + NoisePhase, NoisePoints); var noise = point * noiseStep; var index = (int)noise; var frac = noise % 1.0f; var pointA = points[(index + 0) % NoisePoints]; var pointB = points[(index + 1) % NoisePoints]; var pointC = points[(index + 2) % NoisePoints]; var pointD = points[(index + 3) % NoisePoints]; r += SgtHelper.CubicInterpolate(pointA, pointB, pointC, pointD, frac) * NoiseStrength; } positions[v] = new Vector3(x * r, y * r, 0.0f); coords1[v] = new Vector2(1.0f, 0.0f); } for (var tri = 0; tri < Detail; tri++) { var i = tri * 3; var v0 = tri + 1; var v1 = tri + 2; if (v1 >= total) { v1 = 1; } indices[i + 0] = 0; indices[i + 1] = v0; indices[i + 2] = v1; } generatedMesh.Clear(false); generatedMesh.vertices = positions; generatedMesh.uv = coords1; generatedMesh.triangles = indices; generatedMesh.RecalculateNormals(); generatedMesh.RecalculateBounds(); } } [ContextMenu("Update Apply")] public void UpdateApply() { if (Flare != null) { Flare.Mesh = generatedMesh; Flare.UpdateMesh(); } } protected virtual void OnEnable() { if (startCalled == true) { CheckUpdateCalls(); } } protected virtual void Start() { if (startCalled == false) { startCalled = true; if (Flare == null) { Flare = GetComponent<SgtFlare>(); } CheckUpdateCalls(); } } protected virtual void OnDestroy() { if (generatedMesh != null) { generatedMesh.Clear(false); SgtObjectPool<Mesh>.Add(generatedMesh); } } private void CheckUpdateCalls() { if (generatedMesh == null) { UpdateMesh(); } UpdateApply(); } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections; using System.Collections.Generic; namespace Encog.Util.KMeans { /// <summary> /// Generic KMeans clustering object. /// </summary> /// <typeparam name="TK">The type to cluster</typeparam> public class KMeansUtil<TK> where TK : class { /// <summary> /// The clusters. /// </summary> private readonly IList<Cluster<TK>> _clusters; /// <summary> /// The number of clusters. /// </summary> private readonly int _k; /// <summary> /// Construct the clusters. Call process to perform the cluster. /// </summary> /// <param name="theK">The number of clusters.</param> /// <param name="theElements">The elements to cluster.</param> public KMeansUtil(int theK, IList theElements) { _k = theK; _clusters = new List<Cluster<TK>>(theK); InitRandomClusters(theElements); } /// <summary> /// The number of clusters. /// </summary> public int Count { get { return _clusters.Count; } } /// <summary> /// Create random clusters. /// </summary> /// <param name="elements">The elements to cluster.</param> private void InitRandomClusters(IList elements) { int clusterIndex = 0; int elementIndex = 0; // first simply fill out the clusters, until we run out of clusters while ((elementIndex < elements.Count) && (clusterIndex < _k) && (elements.Count - elementIndex > _k - clusterIndex)) { var element = elements[elementIndex]; bool added = false; // if this element is identical to another, add it to this cluster for (int i = 0; i < clusterIndex; i++) { Cluster<TK> cluster = _clusters[i]; if (cluster.Centroid().Distance((TK) element) == 0) { cluster.Add(element as TK); added = true; break; } } if (!added) { _clusters.Add(new Cluster<TK>(elements[elementIndex] as TK)); clusterIndex++; } elementIndex++; } // create while (clusterIndex < _k && elementIndex < elements.Count) { _clusters.Add(new Cluster<TK>(elements[elementIndex] as TK)); elementIndex++; clusterIndex++; } // handle case where there were not enough clusters created, // create empty ones. while (clusterIndex < _k) { _clusters.Add(new Cluster<TK>()); clusterIndex++; } // otherwise, handle case where there were still unassigned elements // add them to the nearest clusters. while (elementIndex < elements.Count) { var element = elements[elementIndex]; NearestCluster(element as TK).Add(element as TK); elementIndex++; } } /// <summary> /// Perform the cluster. /// </summary> public void Process() { bool done; do { done = true; for (int i = 0; i < _k; i++) { Cluster<TK> thisCluster = _clusters[i]; var thisElements = thisCluster.Contents as List<TK>; for (int j = 0; j < thisElements.Count; j++) { TK thisElement = thisElements[j]; // don't make a cluster empty if (thisCluster.Centroid().Distance(thisElement) > 0) { Cluster<TK> nearestCluster = NearestCluster(thisElement); // move to nearer cluster if (thisCluster != nearestCluster) { nearestCluster.Add(thisElement); thisCluster.Remove(j); done = false; } } } } } while (!done); } /// <summary> /// Find the nearest cluster to the element. /// </summary> /// <param name="element">The element.</param> /// <returns>The nearest cluster.</returns> private Cluster<TK> NearestCluster(TK element) { double distance = Double.PositiveInfinity; Cluster<TK> result = null; foreach (Cluster<TK> t in _clusters) { double thisDistance = t.Centroid().Distance(element); if (distance > thisDistance) { distance = thisDistance; result = t; } } return result; } /// <summary> /// Get a cluster by index. /// </summary> /// <param name="index">The index to get.</param> /// <returns>The cluster.</returns> public ICollection<TK> Get(int index) { return _clusters[index].Contents; } /// <summary> /// Get a cluster by index. /// </summary> /// <param name="i">The index to get.</param> /// <returns>The cluster.</returns> public Cluster<TK> GetCluster(int i) { return _clusters[i]; } } }