context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Web.Http; using System.Web.Http.ModelBinding; using AutoMapper; using Examine.LuceneEngine; using Newtonsoft.Json; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models.Membership; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Mvc; using System.Linq; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models; using Umbraco.Web.WebApi.Filters; using umbraco.cms.businesslogic.packager; using Constants = Umbraco.Core.Constants; using Examine; using Examine.LuceneEngine.SearchCriteria; using Examine.SearchCriteria; using Umbraco.Web.Dynamics; using umbraco; namespace Umbraco.Web.Editors { /// <summary> /// The API controller used for getting entity objects, basic name, icon, id representation of umbraco objects that are based on CMSNode /// </summary> /// <remarks> /// Some objects such as macros are not based on CMSNode /// </remarks> [EntityControllerConfiguration] [PluginController("UmbracoApi")] public class EntityController : UmbracoAuthorizedJsonController { [HttpGet] public IEnumerable<EntityBasic> Search(string query, UmbracoEntityTypes type) { if (string.IsNullOrEmpty(query)) return Enumerable.Empty<EntityBasic>(); return ExamineSearch(query, type); } /// <summary> /// Searches for all content that the user is allowed to see (based on their allowed sections) /// </summary> /// <param name="query"></param> /// <returns></returns> /// <remarks> /// Even though a normal entity search will allow any user to search on a entity type that they may not have access to edit, we need /// to filter these results to the sections they are allowed to edit since this search function is explicitly for the global search /// so if we showed entities that they weren't allowed to edit they would get errors when clicking on the result. /// /// The reason a user is allowed to search individual entity types that they are not allowed to edit is because those search /// methods might be used in things like pickers in the content editor. /// </remarks> [HttpGet] public IEnumerable<EntityTypeSearchResult> SearchAll(string query) { if (string.IsNullOrEmpty(query)) return Enumerable.Empty<EntityTypeSearchResult>(); var allowedSections = Security.CurrentUser.AllowedSections.ToArray(); var result = new List<EntityTypeSearchResult>(); if (allowedSections.InvariantContains(Constants.Applications.Content)) { result.Add(new EntityTypeSearchResult { Results = ExamineSearch(query, UmbracoEntityTypes.Document), EntityType = UmbracoEntityTypes.Document.ToString() }); } if (allowedSections.InvariantContains(Constants.Applications.Media)) { result.Add(new EntityTypeSearchResult { Results = ExamineSearch(query, UmbracoEntityTypes.Media), EntityType = UmbracoEntityTypes.Media.ToString() }); } if (allowedSections.InvariantContains(Constants.Applications.Members)) { result.Add(new EntityTypeSearchResult { Results = ExamineSearch(query, UmbracoEntityTypes.Member), EntityType = UmbracoEntityTypes.Member.ToString() }); } return result; } /// <summary> /// Gets the path for a given node ID /// </summary> /// <param name="id"></param> /// <param name="type"></param> /// <returns></returns> public IEnumerable<int> GetPath(int id, UmbracoEntityTypes type) { var foundContent = GetResultForId(id, type); return foundContent.Path.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse); } /// <summary> /// Gets an entity by it's unique id if the entity supports that /// </summary> /// <param name="id"></param> /// <param name="type"></param> /// <returns></returns> public EntityBasic GetByKey(Guid id, UmbracoEntityTypes type) { return GetResultForKey(id, type); } /// <summary> /// Gets an entity by a xpath query /// </summary> /// <param name="query"></param> /// <param name="nodeContextId"></param> /// <param name="type"></param> /// <returns></returns> public EntityBasic GetByQuery(string query, int nodeContextId, UmbracoEntityTypes type) { if (type != UmbracoEntityTypes.Document) throw new ArgumentException("Get by query is only compatible with enitities of type Document"); var q = ParseXPathQuery(query, nodeContextId); var node = Umbraco.TypedContentSingleAtXPath(q); if (node == null) return null; return GetById(node.Id, type); } //PP: wip in progress on the query parser private string ParseXPathQuery(string query, int id) { //no need to parse it if (!query.StartsWith("$")) return query; //get full path Func<int, IEnumerable<string>> getPath = delegate(int nodeid){ var ent = Services.EntityService.Get(nodeid); return ent.Path.Split(',').Reverse(); }; //get nearest published item Func<IEnumerable<string>, int> getClosestPublishedAncestor = (path => { foreach (var _id in path) { var item = Umbraco.TypedContent(int.Parse(_id)); if (item != null) return item.Id; } return -1; }); var rootXpath = "descendant::*[@id={0}]"; //parseable items: var vars = new Dictionary<string, Func<string, string>>(); vars.Add("$current", q => { var _id = getClosestPublishedAncestor(getPath(id)); return q.Replace("$current", string.Format(rootXpath, _id)); }); vars.Add("$parent", q => { //remove the first item in the array if its the current node //this happens when current is published, but we are looking for its parent specifically var path = getPath(id); if(path.ElementAt(0) == id.ToString()){ path = path.Skip(1); } var _id = getClosestPublishedAncestor(path); return q.Replace("$parent", string.Format(rootXpath, _id)); }); vars.Add("$site", q => { var _id = getClosestPublishedAncestor(getPath(id)); return q.Replace("$site", string.Format(rootXpath, _id) + "/ancestor-or-self::*[@level = 1]"); }); vars.Add("$root", q => { return q.Replace("$root", string.Empty); }); foreach (var varible in vars) { if (query.StartsWith(varible.Key)) { query = varible.Value.Invoke(query); break; } } return query; } public EntityBasic GetById(int id, UmbracoEntityTypes type) { return GetResultForId(id, type); } public IEnumerable<EntityBasic> GetByIds([FromUri]int[] ids, UmbracoEntityTypes type) { if (ids == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return GetResultForIds(ids, type); } public IEnumerable<EntityBasic> GetByKeys([FromUri]Guid[] ids, UmbracoEntityTypes type) { if (ids == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return GetResultForKeys(ids, type); } public IEnumerable<EntityBasic> GetChildren(int id, UmbracoEntityTypes type) { return GetResultForChildren(id, type); } public IEnumerable<EntityBasic> GetAncestors(int id, UmbracoEntityTypes type) { return GetResultForAncestors(id, type); } public IEnumerable<EntityBasic> GetAll(UmbracoEntityTypes type, string postFilter, [FromUri]IDictionary<string, object> postFilterParams) { return GetResultForAll(type, postFilter, postFilterParams); } private IEnumerable<EntityBasic> ExamineSearch(string query, UmbracoEntityTypes entityType) { string type; var searcher = Constants.Examine.InternalSearcher; var fields = new[] { "id", "bodyText" }; //TODO: WE should really just allow passing in a lucene raw query switch (entityType) { case UmbracoEntityTypes.Member: searcher = Constants.Examine.InternalMemberSearcher; type = "member"; fields = new[] { "id", "email", "loginName"}; break; case UmbracoEntityTypes.Media: type = "media"; break; case UmbracoEntityTypes.Document: type = "content"; break; default: throw new NotSupportedException("The " + typeof(EntityController) + " currently does not support searching against object type " + entityType); } var internalSearcher = ExamineManager.Instance.SearchProviderCollection[searcher]; //build a lucene query: // the __nodeName will be boosted 10x without wildcards // then __nodeName will be matched normally with wildcards // the rest will be normal without wildcards var sb = new StringBuilder(); //node name exactly boost x 10 sb.Append("+(__nodeName:"); sb.Append(query.ToLower()); sb.Append("^10.0 "); //node name normally with wildcards sb.Append(" __nodeName:"); sb.Append(query.ToLower()); sb.Append("* "); foreach (var f in fields) { //additional fields normally sb.Append(f); sb.Append(":"); sb.Append(query); sb.Append(" "); } //must match index type sb.Append(") +__IndexType:"); sb.Append(type); var raw = internalSearcher.CreateSearchCriteria().RawQuery(sb.ToString()); var result = internalSearcher.Search(raw); switch (entityType) { case UmbracoEntityTypes.Member: return MemberFromSearchResults(result); case UmbracoEntityTypes.Media: return MediaFromSearchResults(result); case UmbracoEntityTypes.Document: return ContentFromSearchResults(result); default: throw new NotSupportedException("The " + typeof(EntityController) + " currently does not support searching against object type " + entityType); } } /// <summary> /// Returns a collection of entities for media based on search results /// </summary> /// <param name="results"></param> /// <returns></returns> private IEnumerable<EntityBasic> MemberFromSearchResults(ISearchResults results) { var mapped = Mapper.Map<IEnumerable<EntityBasic>>(results).ToArray(); //add additional data foreach (var m in mapped) { m.Icon = "icon-user"; var searchResult = results.First(x => x.Id.ToInvariantString() == m.Id.ToString()); if (searchResult.Fields.ContainsKey("email") && searchResult.Fields["email"] != null) { m.AdditionalData["Email"] = results.First(x => x.Id.ToInvariantString() == m.Id.ToString()).Fields["email"]; } if (searchResult.Fields.ContainsKey("__key") && searchResult.Fields["__key"] != null) { Guid key; if (Guid.TryParse(searchResult.Fields["__key"], out key)) { m.Key = key; } } } return mapped; } /// <summary> /// Returns a collection of entities for media based on search results /// </summary> /// <param name="results"></param> /// <returns></returns> private IEnumerable<EntityBasic> MediaFromSearchResults(ISearchResults results) { var mapped = Mapper.Map<IEnumerable<EntityBasic>>(results).ToArray(); //add additional data foreach (var m in mapped) { m.Icon = "icon-picture"; } return mapped; } /// <summary> /// Returns a collection of entities for content based on search results /// </summary> /// <param name="results"></param> /// <returns></returns> private IEnumerable<EntityBasic> ContentFromSearchResults(ISearchResults results) { var mapped = Mapper.Map<ISearchResults, IEnumerable<EntityBasic>>(results).ToArray(); //add additional data foreach (var m in mapped) { var intId = m.Id.TryConvertTo<int>(); if (intId.Success) { m.AdditionalData["Url"] = Umbraco.NiceUrl(intId.Result); } } return mapped; } private IEnumerable<EntityBasic> GetResultForChildren(int id, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { //TODO: Need to check for Object types that support heirarchy here, some might not. return Services.EntityService.GetChildren(id, objectType.Value).Select(Mapper.Map<EntityBasic>) .WhereNotNull(); } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private IEnumerable<EntityBasic> GetResultForAncestors(int id, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { //TODO: Need to check for Object types that support heirarchy here, some might not. var ids = Services.EntityService.Get(id).Path.Split(',').Select(int.Parse); return ids.Select(m => Mapper.Map<EntityBasic>(Services.EntityService.Get(m, objectType.Value))) .WhereNotNull(); } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.PropertyType: case UmbracoEntityTypes.PropertyGroup: case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } /// <summary> /// Gets the result for the entity list based on the type /// </summary> /// <param name="entityType"></param> /// <param name="postFilter">A string where filter that will filter the results dynamically with linq - optional</param> /// <param name="postFilterParams">the parameters to fill in the string where filter - optional</param> /// <returns></returns> private IEnumerable<EntityBasic> GetResultForAll(UmbracoEntityTypes entityType, string postFilter = null, IDictionary<string, object> postFilterParams = null) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { //TODO: Should we order this by something ? var entities = Services.EntityService.GetAll(objectType.Value).WhereNotNull().Select(Mapper.Map<EntityBasic>); return ExecutePostFilter(entities, postFilter, postFilterParams); } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.Macro: //Get all macros from the macro service var macros = Services.MacroService.GetAll().WhereNotNull().OrderBy(x => x.Name); var filteredMacros = ExecutePostFilter(macros, postFilter, postFilterParams); return filteredMacros.Select(Mapper.Map<EntityBasic>); case UmbracoEntityTypes.PropertyType: //get all document types, then combine all property types into one list var propertyTypes = Services.ContentTypeService.GetAllContentTypes().Cast<IContentTypeComposition>() .Concat(Services.ContentTypeService.GetAllMediaTypes()) .ToArray() .SelectMany(x => x.PropertyTypes) .DistinctBy(composition => composition.Alias); var filteredPropertyTypes = ExecutePostFilter(propertyTypes, postFilter, postFilterParams); return Mapper.Map<IEnumerable<PropertyType>, IEnumerable<EntityBasic>>(filteredPropertyTypes); case UmbracoEntityTypes.PropertyGroup: //get all document types, then combine all property types into one list var propertyGroups = Services.ContentTypeService.GetAllContentTypes().Cast<IContentTypeComposition>() .Concat(Services.ContentTypeService.GetAllMediaTypes()) .ToArray() .SelectMany(x => x.PropertyGroups) .DistinctBy(composition => composition.Name); var filteredpropertyGroups = ExecutePostFilter(propertyGroups, postFilter, postFilterParams); return Mapper.Map<IEnumerable<PropertyGroup>, IEnumerable<EntityBasic>>(filteredpropertyGroups); case UmbracoEntityTypes.User: int total; var users = Services.UserService.GetAll(0, int.MaxValue, out total); var filteredUsers = ExecutePostFilter(users, postFilter, postFilterParams); return Mapper.Map<IEnumerable<IUser>, IEnumerable<EntityBasic>>(filteredUsers); case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private IEnumerable<EntityBasic> GetResultForKeys(IEnumerable<Guid> keys, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { return keys.Select(id => Mapper.Map<EntityBasic>(Services.EntityService.GetByKey(id, objectType.Value))) .WhereNotNull(); } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.PropertyType: case UmbracoEntityTypes.PropertyGroup: case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private IEnumerable<EntityBasic> GetResultForIds(IEnumerable<int> ids, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { var result = ids.Select(id => Mapper.Map<EntityBasic>(Services.EntityService.Get(id, objectType.Value))) .WhereNotNull(); return result; } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.PropertyType: case UmbracoEntityTypes.PropertyGroup: case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private EntityBasic GetResultForKey(Guid key, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { var found = Services.EntityService.GetByKey(key, objectType.Value); if (found == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return Mapper.Map<EntityBasic>(found); } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.PropertyType: case UmbracoEntityTypes.PropertyGroup: case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private EntityBasic GetResultForId(int id, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { var found = Services.EntityService.Get(id, objectType.Value); if (found == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return Mapper.Map<EntityBasic>(found); } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.PropertyType: case UmbracoEntityTypes.PropertyGroup: case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private static UmbracoObjectTypes? ConvertToObjectType(UmbracoEntityTypes entityType) { switch (entityType) { case UmbracoEntityTypes.Document: return UmbracoObjectTypes.Document; case UmbracoEntityTypes.Media: return UmbracoObjectTypes.Media; case UmbracoEntityTypes.MemberType: return UmbracoObjectTypes.MediaType; case UmbracoEntityTypes.Template: return UmbracoObjectTypes.Template; case UmbracoEntityTypes.MemberGroup: return UmbracoObjectTypes.MemberGroup; case UmbracoEntityTypes.ContentItem: return UmbracoObjectTypes.ContentItem; case UmbracoEntityTypes.MediaType: return UmbracoObjectTypes.MediaType; case UmbracoEntityTypes.DocumentType: return UmbracoObjectTypes.DocumentType; case UmbracoEntityTypes.Stylesheet: return UmbracoObjectTypes.Stylesheet; case UmbracoEntityTypes.Member: return UmbracoObjectTypes.Member; case UmbracoEntityTypes.DataType: return UmbracoObjectTypes.DataType; default: //There is no UmbracoEntity conversion (things like Macros, Users, etc...) return null; } } /// <summary> /// Executes the post filter against a collection of objects /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entities"></param> /// <param name="postFilter"></param> /// <param name="postFilterParams"></param> /// <returns></returns> private IEnumerable<T> ExecutePostFilter<T>(IEnumerable<T> entities, string postFilter, IDictionary<string, object> postFilterParams) { //if a post filter is assigned then try to execute it if (postFilter.IsNullOrWhiteSpace() == false) { return postFilterParams == null ? entities.AsQueryable().Where(postFilter).ToArray() : entities.AsQueryable().Where(postFilter, postFilterParams).ToArray(); } return entities; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using Windows.Foundation; using Windows.UI; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using Microsoft.Graphics.Canvas; using Microsoft.Graphics.Canvas.Effects; #if WINDOWS_UAP using Windows.Graphics.DirectX; using Windows.Graphics.Effects; using System.Numerics; #else using Microsoft.Graphics.Canvas.DirectX; using Microsoft.Graphics.Canvas.Numerics; #endif using NativeComponent; namespace test.managed { [TestClass] public class EffectTests { // TODO: reenable ReflectOverAllEffects test for UAP when fix for DevDiv:1166515 is flighted #if !WINDOWS_UAP [TestMethod] public void ReflectOverAllEffects() { var assembly = typeof(GaussianBlurEffect).GetTypeInfo().Assembly; var effectTypes = from type in assembly.DefinedTypes where type.ImplementedInterfaces.Contains(typeof(IGraphicsEffect)) select type; foreach (var effectType in effectTypes) { IGraphicsEffect effect = (IGraphicsEffect)Activator.CreateInstance(effectType.AsType()); TestEffectSources(effectType, effect); TestEffectProperties(effectType, effect); } } #endif static void TestEffectSources(TypeInfo effectType, IGraphicsEffect effect) { var sourceProperties = (from property in effectType.DeclaredProperties where property.PropertyType == typeof(IGraphicsEffectSource) select property).ToList(); // Should have the same number of strongly typed properties as the effect has sources. Assert.AreEqual(sourceProperties.Count, EffectAccessor.GetSourceCount(effect)); // Initial source values should all be null. for (int i = 0; i < EffectAccessor.GetSourceCount(effect); i++) { Assert.IsNull(EffectAccessor.GetSource(effect, i)); Assert.IsNull(sourceProperties[i].GetValue(effect)); } var testValue1 = new GaussianBlurEffect(); var testValue2 = new ShadowEffect(); var whichIndexIsProperty = new List<int>(); // Changing strongly typed properties should change the sources reported by IGraphicsEffectD2D1Interop. for (int i = 0; i < EffectAccessor.GetSourceCount(effect); i++) { // Change a property value, and see which source changes. sourceProperties[i].SetValue(effect, testValue1); int whichIndexIsThis = 0; while (EffectAccessor.GetSource(effect, whichIndexIsThis) != testValue1) { whichIndexIsThis++; Assert.IsTrue(whichIndexIsThis < EffectAccessor.GetSourceCount(effect)); } whichIndexIsProperty.Add(whichIndexIsThis); // Change the same property value again, and make sure the same source changes. sourceProperties[i].SetValue(effect, testValue2); Assert.AreSame(testValue2, EffectAccessor.GetSource(effect, whichIndexIsThis)); // Change the property value to null. sourceProperties[i].SetValue(effect, null); Assert.IsNull(EffectAccessor.GetSource(effect, whichIndexIsThis)); } // Should not have any duplicate property mappings. Assert.AreEqual(whichIndexIsProperty.Count, whichIndexIsProperty.Distinct().Count()); } static void TestEffectProperties(TypeInfo effectType, IGraphicsEffect effect) { var properties = (from property in effectType.DeclaredProperties where property.Name != "Name" where property.Name != "Sources" where property.PropertyType != typeof(IGraphicsEffectSource) select property).ToList(); IList<object> effectProperties = new ViewIndexerAsList<object>(() => EffectAccessor.GetPropertyCount(effect), i => EffectAccessor.GetProperty(effect, i)); FilterOutCustomizedEffectProperties(effectType.AsType(), ref properties, ref effectProperties); // Should have the same number of strongly typed properties as elements in the properties collection. Assert.AreEqual(properties.Count, effectProperties.Count); // Store the initial property values. var initialValues = effectProperties.ToList(); var whichIndexIsProperty = new List<int>(); // Changing strongly typed properties should change the properties collection. for (int i = 0; i < effectProperties.Count; i++) { object testValue1 = GetArbitraryTestValue(properties[i].PropertyType, true); object testValue2 = GetArbitraryTestValue(properties[i].PropertyType, false); // Change a property value, and see which collection properties match the result. properties[i].SetValue(effect, testValue1); var matches1 = (from j in Enumerable.Range(0, effectProperties.Count) where BoxedValuesAreEqual(effectProperties[j], Box(testValue1, properties[i]), properties[i]) select j).ToList(); // Change the same property to a different value, and see which collection properties match now. properties[i].SetValue(effect, testValue2); var matches2 = (from j in Enumerable.Range(0, effectProperties.Count) where BoxedValuesAreEqual(effectProperties[j], Box(testValue2, properties[i]), properties[i]) select j).ToList(); // There should be one and only one property that matched both times. If not, // either we don't have 1 <-> 1 mapping between strongly typed properties and // collection indices, or something went wrong during the boxing type conversions. var intersection = matches1.Intersect(matches2); Assert.AreEqual(1, intersection.Count()); int whichIndexIsThis = intersection.Single(); whichIndexIsProperty.Add(whichIndexIsThis); // Change the property value back to its initial state. properties[i].SetValue(effect, Unbox(initialValues[whichIndexIsThis], properties[i])); Assert.IsTrue(BoxedValuesAreEqual(initialValues[whichIndexIsThis], effectProperties[whichIndexIsThis], properties[i])); // Validate that IGraphicsEffectD2D1Interop agrees with what we think the type and index of this property is. int mappingIndex; EffectPropertyMapping mapping; EffectAccessor.GetNamedPropertyMapping(effect, properties[i].Name, out mappingIndex, out mapping); int expectedMappingIndex = whichIndexIsThis; if (effectProperties is FilteredViewOfList<object>) expectedMappingIndex = ((FilteredViewOfList<object>)effectProperties).GetOriginalIndex(expectedMappingIndex); Assert.AreEqual(expectedMappingIndex, mappingIndex); var expectedMapping = GetExpectedPropertyMapping(properties[i], effectProperties[whichIndexIsThis]); Assert.AreEqual(expectedMapping, mapping); } // Should not have any duplicate property mappings. Assert.AreEqual(whichIndexIsProperty.Count, whichIndexIsProperty.Distinct().Count()); } static object Box(object value, PropertyInfo property) { if (value is int || value is bool || value is float[]) { return value; } else if (value is float) { if (NeedsRadianToDegreeConversion(property)) { return (float)value * 180f / (float)Math.PI; } else { return value; } } else if (value is Enum) { return (uint)(int)value; } else if (value is Vector2) { var v = (Vector2)value; return new float[] { v.X, v.Y }; } else if (value is Vector3) { var v = (Vector3)value; return new float[] { v.X, v.Y, v.Z }; } else if (value is Vector4) { var v = (Vector4)value; return new float[] { v.X, v.Y, v.Z, v.W }; } else if (value is Matrix3x2) { var m = (Matrix3x2)value; return new float[] { m.M11, m.M12, m.M21, m.M22, m.M31, m.M32 }; } else if (value is Matrix4x4) { var m = (Matrix4x4)value; return new float[] { m.M11, m.M12, m.M13, m.M14, m.M21, m.M22, m.M23, m.M24, m.M31, m.M32, m.M33, m.M34, m.M41, m.M42, m.M43, m.M44, }; } else if (value is Matrix5x4) { var m = (Matrix5x4)value; return new float[] { m.M11, m.M12, m.M13, m.M14, m.M21, m.M22, m.M23, m.M24, m.M31, m.M32, m.M33, m.M34, m.M41, m.M42, m.M43, m.M44, m.M51, m.M52, m.M53, m.M54, }; } else if (value is Rect) { var r = (Rect)value; return new float[] { (float)r.Left, (float)r.Top, (float)r.Right, (float)r.Bottom, }; } else if (value is Color) { var c = (Color)value; return new float[] { (float)c.R / 255, (float)c.G / 255, (float)c.B / 255, (float)c.A / 255, }; } else { throw new NotSupportedException("Unsupported Box type " + value.GetType()); } } static object Unbox(object value, PropertyInfo property) { Type type = property.PropertyType; if (type == typeof(int) || type == typeof(bool) || type == typeof(float[])) { return value; } else if (type == typeof(float)) { if (NeedsRadianToDegreeConversion(property)) { return (float)value * (float)Math.PI / 180f; } else { return value; } } else if (type.GetTypeInfo().IsEnum) { return Enum.GetValues(type).GetValue((int)(uint)value); } else if (type == typeof(Vector2)) { var a = (float[])value; Assert.AreEqual(2, a.Length); return new Vector2 { X = a[0], Y = a[1], }; } else if (type == typeof(Vector3)) { var a = (float[])value; Assert.AreEqual(3, a.Length); return new Vector3 { X = a[0], Y = a[1], Z = a[2], }; } else if (type == typeof(Vector4)) { var a = (float[])value; Assert.AreEqual(4, a.Length); return new Vector4 { X = a[0], Y = a[1], Z = a[2], W = a[3], }; } else if (type == typeof(Matrix3x2)) { var a = (float[])value; Assert.AreEqual(6, a.Length); return new Matrix3x2 { M11 = a[0], M12 = a[1], M21 = a[2], M22 = a[3], M31 = a[4], M32 = a[5], }; } else if (type == typeof(Matrix4x4)) { var a = (float[])value; Assert.AreEqual(16, a.Length); return new Matrix4x4 { M11 = a[0], M12 = a[1], M13 = a[2], M14 = a[3], M21 = a[4], M22 = a[5], M23 = a[6], M24 = a[7], M31 = a[8], M32 = a[9], M33 = a[10], M34 = a[11], M41 = a[12], M42 = a[13], M43 = a[14], M44 = a[15], }; } else if (type == typeof(Matrix5x4)) { var a = (float[])value; Assert.AreEqual(20, a.Length); return new Matrix5x4 { M11 = a[0], M12 = a[1], M13 = a[2], M14 = a[3], M21 = a[4], M22 = a[5], M23 = a[6], M24 = a[7], M31 = a[8], M32 = a[9], M33 = a[10], M34 = a[11], M41 = a[12], M42 = a[13], M43 = a[14], M44 = a[15], M51 = a[16], M52 = a[17], M53 = a[18], M54 = a[19], }; } else if (type == typeof(Rect)) { var a = (float[])value; Assert.AreEqual(4, a.Length); return new Rect(new Point(a[0], a[1]), new Point(a[2], a[3])); } else if (type == typeof(Color)) { var a = ConvertRgbToRgba((float[])value); Assert.AreEqual(4, a.Length); return Color.FromArgb((byte)(a[3] * 255), (byte)(a[0] * 255), (byte)(a[1] * 255), (byte)(a[2] * 255)); } else { throw new NotSupportedException("Unsupported Unbox type " + type); } } static bool BoxedValuesAreEqual(object value1, object value2, PropertyInfo property) { if (value1.GetType() != value2.GetType()) { return false; } if (value1 is int || value1 is uint || value1 is bool) { return value1.Equals(value2); } else if (value1 is float) { return Math.Abs((float)value1 - (float)value2) < 0.000001; } else if (value1 is float[]) { float[] a1 = (float[])value1; float[] a2 = (float[])value2; if (property.PropertyType == typeof(Color)) { a1 = ConvertRgbToRgba(a1); a2 = ConvertRgbToRgba(a2); } return a1.SequenceEqual(a2); } else { throw new NotSupportedException("Unsupported BoxedValuesAreEqual type " + value1.GetType()); } } static void AssertPropertyValuesAreEqual(object value1, object value2) { if (value1 is float[] && value2 is float[]) { Assert.IsTrue((value1 as float[]).SequenceEqual(value2 as float[])); } else if (value1 is float) { Assert.IsTrue(Math.Abs((float)value1 - (float)value2) < 0.000001); } else { Assert.AreEqual(value1, value2); } } static float[] ConvertRgbToRgba(float[] value) { if (value.Length == 3) { return value.Concat(new float[] { 1 }).ToArray(); } else { return value; } } static float[] ConvertRgbaToRgb(float[] value) { return value.Take(3).ToArray(); } static bool NeedsRadianToDegreeConversion(PropertyInfo property) { string[] anglePropertyNames = { "Angle", "Azimuth", "Elevation", "LimitingConeAngle", }; return anglePropertyNames.Contains(property.Name); } static EffectPropertyMapping GetExpectedPropertyMapping(PropertyInfo property, object propertyValue) { if (NeedsRadianToDegreeConversion(property)) { return EffectPropertyMapping.RadiansToDegrees; } else if (property.PropertyType == typeof(Rect)) { return EffectPropertyMapping.RectToVector4; } else if (property.PropertyType == typeof(Color)) { return ((float[])propertyValue).Length == 3 ? EffectPropertyMapping.ColorToVector3 : EffectPropertyMapping.ColorToVector4; } else { return EffectPropertyMapping.Direct; } } static object GetArbitraryTestValue(Type type, bool whichOne) { if (type == typeof(int)) { return whichOne ? 2 : 7; } else if (type == typeof(float)) { return whichOne ? 0.5f : 0.75f; } else if (type == typeof(bool)) { return whichOne; } else if (type.GetTypeInfo().IsEnum) { return Enum.GetValues(type).GetValue(whichOne ? 0 : 1); } else if (type == typeof(Vector2)) { return whichOne ? new Vector2 { X = 0.25f, Y = 0.75f } : new Vector2 { X = 0.5f, Y = 0.125f }; } else if (type == typeof(Vector3)) { return whichOne ? new Vector3 { X = 1, Y = 2, Z = 3 } : new Vector3 { X = 4, Y = 5, Z = 6 }; } else if (type == typeof(Vector4)) { return whichOne ? new Vector4 { X = 1, Y = 2, Z = 3, W = 4 } : new Vector4 { X = 5, Y = 6, Z = 7, W = 8 }; } else if (type == typeof(Matrix3x2)) { return whichOne ? new Matrix3x2 { M11 = 1, M12 = 2, M21 = 3, M22 = 4, M31 = 5, M32 = 6 } : new Matrix3x2 { M11 = 7, M12 = 8, M21 = 9, M22 = 10, M31 = 11, M32 = 12 }; } else if (type == typeof(Matrix4x4)) { return whichOne ? new Matrix4x4 { M11 = 1, M12 = 2, M13 = 3, M14 = 4, M21 = 5, M22 = 6, M23 = 7, M24 = 8, M31 = 9, M32 = 10, M33 = 11, M34 = 12, M41 = 13, M42 = 14, M43 = 15, M44 = 16 } : new Matrix4x4 { M11 = 11, M12 = 12, M13 = 13, M14 = 14, M21 = 15, M22 = 16, M23 = 17, M24 = 18, M31 = 19, M32 = 20, M33 = 21, M34 = 22, M41 = 23, M42 = 24, M43 = 25, M44 = 26 }; } else if (type == typeof(Matrix5x4)) { return whichOne ? new Matrix5x4 { M11 = 1, M12 = 2, M13 = 3, M14 = 4, M21 = 5, M22 = 6, M23 = 7, M24 = 8, M31 = 9, M32 = 10, M33 = 11, M34 = 12, M41 = 13, M42 = 14, M43 = 15, M44 = 16, M51 = 17, M52 = 18, M53 = 19, M54 = 20 } : new Matrix5x4 { M11 = 11, M12 = 12, M13 = 13, M14 = 14, M21 = 15, M22 = 16, M23 = 17, M24 = 18, M31 = 19, M32 = 20, M33 = 21, M34 = 22, M41 = 23, M42 = 24, M43 = 25, M44 = 26, M51 = 27, M52 = 28, M53 = 29, M54 = 30 }; } else if (type == typeof(Rect)) { return whichOne ? new Rect(1, 2, 3, 4) : new Rect(10, 20, 5, 6); } else if (type == typeof(Color)) { return whichOne ? Colors.CornflowerBlue : Colors.Crimson; } else if (type == typeof(float[])) { return whichOne ? new float[] { 1, 2, 3 } : new float[] { 4, 5, 6, 7, 8, 9 }; } else { throw new NotSupportedException("Unsupported GetArbitraryTestValue type " + type); } } static void FilterOutCustomizedEffectProperties(Type effectType, ref List<PropertyInfo> properties, ref IList<object> effectProperties) { // Customized properties that our general purpose reflection based property test won't understand. string[] propertiesToRemove; int[] indexMapping; if (effectType == typeof(ArithmeticCompositeEffect)) { // ArithmeticCompositeEffect has strange customized properties. // Win2D exposes what D2D treats as a single Vector4 as 4 separate float properties. propertiesToRemove = new string[] { "MultiplyAmount", "Source1Amount", "Source2Amount", "Offset" }; indexMapping = new int[] { 1 }; } else if (effectType == typeof(ColorMatrixEffect)) { // ColorMatrixEffect.AlphaMode has special logic to remap enum values between WinRT and D2D. propertiesToRemove = new string[] { "AlphaMode", }; indexMapping = new int[] { 0, 2 }; } #if WINDOWS_UAP else if (effectType == typeof(SepiaEffect)) { // SepiaEffect.AlphaMode has special logic to remap enum values between WinRT and D2D. propertiesToRemove = new string[] { "AlphaMode", }; indexMapping = new int[] { 0 }; } else if (effectType == typeof(EdgeDetectionEffect)) { // EdgeDetectionEffect.AlphaMode has special logic to remap enum values between WinRT and D2D. propertiesToRemove = new string[] { "AlphaMode", }; indexMapping = new int[] { 0, 1, 2, 3 }; } else if (effectType == typeof(HighlightsAndShadowsEffect)) { // HighlightsAndShadowsEffect.SourceIsLinearGamma projects an enum value as a bool. propertiesToRemove = new string[] { "SourceIsLinearGamma", }; indexMapping = new int[] { 0, 1, 2, 4 }; } #endif // WINDOWS_UAP else { // Other effects do not need special filtering. return; } // Hide the customized properties, so ReflectOverAllEffects test won't see them. properties = properties.Where(p => !propertiesToRemove.Contains(p.Name)).ToList(); effectProperties = new FilteredViewOfList<object>(effectProperties, indexMapping); } class FilteredViewOfList<T> : IList<T> { IList<T> underlyingList; IList<int> indexMapping; public FilteredViewOfList(IList<T> underlyingList, IList<int> indexMapping) { this.underlyingList = underlyingList; this.indexMapping = indexMapping; } public int Count { get { return indexMapping.Count; } } public T this[int index] { get { return underlyingList[indexMapping[index]]; } set { underlyingList[indexMapping[index]] = value; } } public void CopyTo(T[] array, int arrayIndex) { for (int i = 0; i < Count; i++) { array[arrayIndex + i] = this[i]; } } public int GetOriginalIndex(int index) { return indexMapping[index]; } public void Add(T item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(T item) { throw new NotImplementedException(); } public int IndexOf(T item) { throw new NotImplementedException(); } public void Insert(int index, T item) { throw new NotImplementedException(); } public bool IsReadOnly { get { throw new NotImplementedException(); } } public bool Remove(T item) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } public IEnumerator<T> GetEnumerator() { throw new NotImplementedException(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class ViewIndexerAsList<T> : IList<T> { Func<int> getCount; Func<int, T> getItem; public ViewIndexerAsList(Func<int> getCount, Func<int, T> getItem) { this.getCount = getCount; this.getItem = getItem; } public int Count { get { return getCount(); } } public T this[int index] { get { return getItem(index); } set { throw new NotImplementedException(); } } public void CopyTo(T[] array, int arrayIndex) { for (int i = 0; i < Count; i++) { array[arrayIndex + i] = getItem(i); } } public void Add(T item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(T item) { throw new NotImplementedException(); } public int IndexOf(T item) { throw new NotImplementedException(); } public void Insert(int index, T item) { throw new NotImplementedException(); } public bool IsReadOnly { get { throw new NotImplementedException(); } } public bool Remove(T item) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } public IEnumerator<T> GetEnumerator() { throw new NotImplementedException(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } [TestMethod] public void ArithmeticCompositeEffectCustomizations() { var effect = new ArithmeticCompositeEffect(); // Verify defaults. Assert.AreEqual(1.0f, effect.MultiplyAmount); Assert.AreEqual(0.0f, effect.Source1Amount); Assert.AreEqual(0.0f, effect.Source2Amount); Assert.AreEqual(0.0f, effect.Offset); Assert.IsTrue(((float[])EffectAccessor.GetProperty(effect, 0)).SequenceEqual(new float[] { 1, 0, 0, 0 })); // Change properties one at a time, and verify that the boxed value changes to match. effect.MultiplyAmount = 23; Assert.IsTrue(((float[])EffectAccessor.GetProperty(effect, 0)).SequenceEqual(new float[] { 23, 0, 0, 0 })); effect.Source1Amount = 42; Assert.IsTrue(((float[])EffectAccessor.GetProperty(effect, 0)).SequenceEqual(new float[] { 23, 42, 0, 0 })); effect.Source2Amount = -1; Assert.IsTrue(((float[])EffectAccessor.GetProperty(effect, 0)).SequenceEqual(new float[] { 23, 42, -1, 0 })); effect.Offset = 100; Assert.IsTrue(((float[])EffectAccessor.GetProperty(effect, 0)).SequenceEqual(new float[] { 23, 42, -1, 100 })); // Validate that IGraphicsEffectD2D1Interop reports the right customizations. int index; EffectPropertyMapping mapping; EffectAccessor.GetNamedPropertyMapping(effect, "MultiplyAmount", out index, out mapping); Assert.AreEqual(0, index); Assert.AreEqual(EffectPropertyMapping.VectorX, mapping); EffectAccessor.GetNamedPropertyMapping(effect, "Source1Amount", out index, out mapping); Assert.AreEqual(0, index); Assert.AreEqual(EffectPropertyMapping.VectorY, mapping); EffectAccessor.GetNamedPropertyMapping(effect, "Source2Amount", out index, out mapping); Assert.AreEqual(0, index); Assert.AreEqual(EffectPropertyMapping.VectorZ, mapping); EffectAccessor.GetNamedPropertyMapping(effect, "Offset", out index, out mapping); Assert.AreEqual(0, index); Assert.AreEqual(EffectPropertyMapping.VectorW, mapping); } const uint D2D1_ALPHA_MODE_PREMULTIPLIED = 1; const uint D2D1_ALPHA_MODE_STRAIGHT = 2; [TestMethod] public void ColorMatrixEffectCustomizations() { var effect = new ColorMatrixEffect(); // Verify defaults. Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode); Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 1)); // Change the property, and verify that the boxed value changes to match. effect.AlphaMode = CanvasAlphaMode.Straight; Assert.AreEqual(D2D1_ALPHA_MODE_STRAIGHT, EffectAccessor.GetProperty(effect, 1)); effect.AlphaMode = CanvasAlphaMode.Premultiplied; Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 1)); // Verify unsupported value throws. Assert.ThrowsException<ArgumentException>(() => { effect.AlphaMode = CanvasAlphaMode.Ignore; }); Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode); // Validate that IGraphicsEffectD2D1Interop reports the right customizations. int index; EffectPropertyMapping mapping; EffectAccessor.GetNamedPropertyMapping(effect, "AlphaMode", out index, out mapping); Assert.AreEqual(1, index); Assert.AreEqual(EffectPropertyMapping.ColorMatrixAlphaMode, mapping); } #if WINDOWS_UAP [TestMethod] public void SepiaEffectCustomizations() { var effect = new SepiaEffect(); // Verify defaults. Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode); Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 1)); // Change the property, and verify that the boxed value changes to match. effect.AlphaMode = CanvasAlphaMode.Straight; Assert.AreEqual(D2D1_ALPHA_MODE_STRAIGHT, EffectAccessor.GetProperty(effect, 1)); effect.AlphaMode = CanvasAlphaMode.Premultiplied; Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 1)); // Verify unsupported value throws. Assert.ThrowsException<ArgumentException>(() => { effect.AlphaMode = CanvasAlphaMode.Ignore; }); Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode); // Validate that IGraphicsEffectD2D1Interop reports the right customizations. int index; EffectPropertyMapping mapping; EffectAccessor.GetNamedPropertyMapping(effect, "AlphaMode", out index, out mapping); Assert.AreEqual(1, index); Assert.AreEqual(EffectPropertyMapping.ColorMatrixAlphaMode, mapping); } [TestMethod] public void EdgeDetectionEffectCustomizations() { var effect = new EdgeDetectionEffect(); // Verify defaults. Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode); Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 4)); // Change the property, and verify that the boxed value changes to match. effect.AlphaMode = CanvasAlphaMode.Straight; Assert.AreEqual(D2D1_ALPHA_MODE_STRAIGHT, EffectAccessor.GetProperty(effect, 4)); effect.AlphaMode = CanvasAlphaMode.Premultiplied; Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 4)); // Verify unsupported value throws. Assert.ThrowsException<ArgumentException>(() => { effect.AlphaMode = CanvasAlphaMode.Ignore; }); Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode); // Validate that IGraphicsEffectD2D1Interop reports the right customizations. int index; EffectPropertyMapping mapping; EffectAccessor.GetNamedPropertyMapping(effect, "AlphaMode", out index, out mapping); Assert.AreEqual(4, index); Assert.AreEqual(EffectPropertyMapping.ColorMatrixAlphaMode, mapping); } [TestMethod] public void HighlightsAndShadowsEffectCustomizations() { const uint D2D1_HIGHLIGHTSANDSHADOWS_INPUT_GAMMA_LINEAR = 0; const uint D2D1_HIGHLIGHTSANDSHADOWS_INPUT_GAMMA_SRGB = 1; var effect = new HighlightsAndShadowsEffect(); // Verify defaults. Assert.IsFalse(effect.SourceIsLinearGamma); Assert.AreEqual(D2D1_HIGHLIGHTSANDSHADOWS_INPUT_GAMMA_SRGB, EffectAccessor.GetProperty(effect, 3)); // Change the property, and verify that the boxed value changes to match. effect.SourceIsLinearGamma = true; Assert.IsTrue(effect.SourceIsLinearGamma); Assert.AreEqual(D2D1_HIGHLIGHTSANDSHADOWS_INPUT_GAMMA_LINEAR, EffectAccessor.GetProperty(effect, 3)); effect.SourceIsLinearGamma = false; Assert.IsFalse(effect.SourceIsLinearGamma); Assert.AreEqual(D2D1_HIGHLIGHTSANDSHADOWS_INPUT_GAMMA_SRGB, EffectAccessor.GetProperty(effect, 3)); // Validate that IGraphicsEffectD2D1Interop reports the right customizations. int index; EffectPropertyMapping mapping; EffectAccessor.GetNamedPropertyMapping(effect, "SourceIsLinearGamma", out index, out mapping); Assert.AreEqual(3, index); Assert.AreEqual(EffectPropertyMapping.Unknown, mapping); } [TestMethod] public void StraightenEffectDoesNotSupportHighQualityInterpolation() { var effect = new StraightenEffect(); var supportedModes = from mode in Enum.GetValues(typeof(CanvasImageInterpolation)).Cast<CanvasImageInterpolation>() where mode != CanvasImageInterpolation.HighQualityCubic select mode; foreach (var interpolationMode in supportedModes) { effect.InterpolationMode = interpolationMode; Assert.AreEqual(interpolationMode, effect.InterpolationMode); } Assert.ThrowsException<ArgumentException>(() => { effect.InterpolationMode = CanvasImageInterpolation.HighQualityCubic; }); } #endif // WINDOWS_UAP [TestMethod] public void Transform3DEffectDoesNotSupportHighQualityInterpolation() { var effect = new Transform3DEffect(); var supportedModes = from mode in Enum.GetValues(typeof(CanvasImageInterpolation)).Cast<CanvasImageInterpolation>() where mode != CanvasImageInterpolation.HighQualityCubic select mode; foreach (var interpolationMode in supportedModes) { effect.InterpolationMode = interpolationMode; Assert.AreEqual(interpolationMode, effect.InterpolationMode); } Assert.ThrowsException<ArgumentException>(() => { effect.InterpolationMode = CanvasImageInterpolation.HighQualityCubic; }); } [TestMethod] public void Transform2DEffectSupportsAllInterpolationModes() { var effect = new Transform2DEffect(); foreach (var interpolationMode in Enum.GetValues(typeof(CanvasImageInterpolation)).Cast<CanvasImageInterpolation>()) { effect.InterpolationMode = interpolationMode; Assert.AreEqual(interpolationMode, effect.InterpolationMode); } } class NotACanvasImage : IGraphicsEffectSource { } void VerifyExceptionMessage(string expected, string sourceMessage) { // Exception messages contain something like // "Invalid pointer\r\n\r\nEffect source #0 is null", // The 'invalid pointer' part is locale // dependent and is stripped out. string delimiterString = "\r\n\r\n"; int delimiterPosition = sourceMessage.LastIndexOf(delimiterString); string exceptionMessage = sourceMessage.Substring(delimiterPosition + delimiterString.Length); Assert.AreEqual(expected, exceptionMessage); } [TestMethod] public void EffectExceptionMessages() { var effect = new GaussianBlurEffect(); using (var device = new CanvasDevice()) using (var renderTarget = new CanvasRenderTarget(device, 1, 1, 96)) using (var drawingSession = renderTarget.CreateDrawingSession()) { // Null source. try { drawingSession.DrawImage(effect); Assert.Fail("should throw"); } catch (NullReferenceException e) { VerifyExceptionMessage("Effect source #0 is null.", e.Message); } // Invalid source type. effect.Source = new NotACanvasImage(); try { drawingSession.DrawImage(effect); Assert.Fail("should throw"); } catch (InvalidCastException e) { VerifyExceptionMessage("Effect source #0 is an unsupported type. To draw an effect using Win2D, all its sources must be Win2D ICanvasImage objects.", e.Message); } } } [TestMethod] public void EffectPropertyDefaults() { // We have customised the default value of DpiCompensationEffect border mode property. Assert.AreEqual(EffectBorderMode.Hard, new DpiCompensationEffect().BorderMode); // Other effects should still have the standard D2D default value. Assert.AreEqual(EffectBorderMode.Soft, new GaussianBlurEffect().BorderMode); Assert.AreEqual(EffectBorderMode.Soft, new Transform3DEffect().BorderMode); } [TestMethod] public void EffectName() { var effect = new GaussianBlurEffect(); Assert.AreEqual(string.Empty, effect.Name); effect.Name = "hello"; Assert.AreEqual("hello", effect.Name); effect.Name = "world"; Assert.AreEqual("world", effect.Name); effect.Name = string.Empty; Assert.AreEqual(string.Empty, effect.Name); Assert.ThrowsException<ArgumentNullException>(() => { effect.Name = null; }); } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Drawing; using System.Globalization; using System.Text.RegularExpressions; using System.IO; using System.Reflection; using System.Diagnostics; using System.Resources; using System.Linq; using ToolBelt; namespace Tools { [CommandLineTitle("Strongly Typed String Resource Class Wrapper Generator")] [CommandLineDescription("Generates wrapper methods to make parameterized string resources safer")] [CommandLineCopyright("Copyright (c) John Lyon-Smith 2015")] public class StrapperTool : ToolBase { #region Classes private class ResourceItem { #region Fields private Type dataType; private string name; private string valueString; #endregion #region Constructors public ResourceItem(string name, string stringResourceValue) : this(name, typeof(string)) { this.valueString = stringResourceValue; } public ResourceItem(string name, Type dataType) { this.name = name; this.dataType = dataType; } #endregion #region Properties public Type DataType { get { return this.dataType; } } public string Name { get { return this.name; } } public string ValueString { get { return this.valueString; } } #endregion } #endregion #region Fields private List<ResourceItem> resources = new List<ResourceItem>(); private StreamWriter writer; private readonly char[] InvalidNameCharacters = new char[] { '.', '$', '*', '{', '}', '|', '<', '>' }; private bool haveDrawingResources = false; #endregion [DefaultCommandLineArgument(ValueHint="INPUTFILE", Description="Input .resx or .strings file.")] public string InputFileName { get; set; } [CommandLineArgument("resources", ShortName="r", ValueHint="RESFILE", Description="Specify different name for .resources file.")] public string ResourcesFileName { get; set; } [CommandLineArgument("output", ShortName="o", ValueHint="CSFILE", Description="Specify different name for .cs file.")] public string CsFileName { get; set; } [CommandLineArgument("namespace", ShortName="n", ValueHint="NAMESPACE", Description="Namespace to use in generated C#.")] public string Namespace { get; set; } [CommandLineArgument("basename", ShortName="b", Description="The root name of the resource file without its extension but including any " + "fully qualified namespace name. For example, the root name for the resource file named MyApplication.MyResource.en-US.resources " + "is MyApplication.MyResource. See ResourceManager constructor documentation for details. If not provided the fully qualified type name of the " + "generated class is used as the file name of the resource. For example, given a type named MyCompany.MyProduct.MyType, the resource manager looks " + "for a .resources file named MyCompany.MyProduct.MyType.resources in the assembly that defines MyType.")] public string BaseName { get; set; } [CommandLineArgument("access", ShortName="a", Description="Access modifier of the wrapper class. Must be internal or public. Default is public.", Initializer=typeof(StrapperTool), MethodName="ParseModifier")] public string AccessModifier { get; set; } [CommandLineArgument("help", ShortName="?", Description="Shows this help")] public bool ShowUsage { get; set; } [CommandLineArgument("incremental", ShortName="i", Description="Only update output files if the input files have changed")] public bool Incremental { get; set; } public static string ParseModifier(string arg) { if (arg == "public" || arg == "internal") return arg; throw new CommandLineArgumentException("Modifier must be public or internal"); } #region Methods public override void Execute() { if (ShowUsage) { WriteMessage(this.Parser.LogoBanner); WriteMessage(this.Parser.Usage); return; } if (InputFileName == null) { WriteError("A .resx file must be specified"); return; } if (CsFileName == null) { CsFileName = Path.ChangeExtension(InputFileName, ".cs"); } if (ResourcesFileName == null) { ResourcesFileName = Path.ChangeExtension(InputFileName, ".resources"); } if (String.IsNullOrEmpty(AccessModifier)) { AccessModifier = "public"; } DateTime resxLastWriteTime = File.GetLastWriteTime(InputFileName); if (Incremental && resxLastWriteTime < File.GetLastWriteTime(CsFileName) && resxLastWriteTime < File.GetLastWriteTime(ResourcesFileName)) { return; } string ext = Path.GetExtension(InputFileName); if (ext == ".resx") ReadResXResources(); else if (ext == ".strings") ReadStringsFile(); else { WriteError("Expected file ending in .strings or .resx"); return; } WriteMessage("Read file '{0}'", InputFileName); using (this.writer = new StreamWriter(CsFileName, false, Encoding.ASCII)) { WriteCsFile(); } WriteResourcesFile(); WriteMessage("Generated file '{0}'", ResourcesFileName); } private void WriteResourcesFile() { IResourceWriter resourceWriter = new ResourceWriter(ResourcesFileName); foreach (var resource in resources) { resourceWriter.AddResource(resource.Name, resource.ValueString); } resourceWriter.Close(); } private void WriteCsFile() { WriteNamespaceStart(); WriteClassStart(); int num = 0; foreach (ResourceItem item in resources) { if (item.DataType.IsPublic) { num++; this.WriteResourceMethod(item); } else { WriteWarning("Resource skipped. Type {0} is not public.", item.DataType); } } WriteClassEnd(); WriteNamespaceEnd(); WriteMessage("Generated wrapper class '{0}' for {1} resource(s)", CsFileName, num); } private void WriteNamespaceStart() { DateTime now = DateTime.Now; writer.Write(String.Format(CultureInfo.InvariantCulture, @"// // This file genenerated by the Buckle tool on {0} at {1}. // // Contains strongly typed wrappers for resources in {2} // " , now.ToShortDateString(), now.ToShortTimeString(), Path.GetFileName(InputFileName))); if ((Namespace != null) && (Namespace.Length != 0)) { writer.Write(String.Format(CultureInfo.InvariantCulture, @"namespace {0} {{ " , Namespace)); } writer.Write( @"using System; using System.Reflection; using System.Resources; using System.Diagnostics; using System.Globalization; " ); if (haveDrawingResources) { writer.Write( @"using System.Drawing; " ); } writer.WriteLine(); } private void WriteNamespaceEnd() { if ((Namespace != null) && (Namespace.Length != 0)) { writer.Write( @"} " ); } } private void WriteClassStart() { writer.Write(string.Format(CultureInfo.InvariantCulture, @" /// <summary> /// Strongly typed resource wrappers generated from {0}. /// </summary> {1} class {2} {{ internal static readonly ResourceManager ResourceManager = new ResourceManager(" , Path.GetFileName(InputFileName), AccessModifier, Path.GetFileNameWithoutExtension(CsFileName))); if (String.IsNullOrWhiteSpace(this.BaseName)) { writer.Write(string.Format(CultureInfo.InvariantCulture, @"typeof({0})); " , Path.GetFileNameWithoutExtension(CsFileName))); } else { writer.Write(string.Format(CultureInfo.InvariantCulture, @"""{0}"", Assembly.GetExecutingAssembly()); " , this.BaseName)); } } private void WriteClassEnd() { writer.Write( @"} "); } private void CheckNameCharacters(string name) { for (int i = 0; i < name.Length; i++) { if (name.IndexOfAny(InvalidNameCharacters) != -1) throw new FormatException(String.Format("Characters '{0}' are invalid in name", InvalidNameCharacters)); } } private void WriteResourceMethod(ResourceItem item) { StringBuilder builder = new StringBuilder(item.Name); if (item.DataType == typeof(string)) { string parametersWithTypes = string.Empty; string parameters = string.Empty; int paramCount = 0; try { paramCount = this.GetNumberOfParametersForStringResource(item.ValueString); } catch (ApplicationException exception) { WriteError("Resource has been skipped: {0}", exception.Message); } for (int j = 0; j < paramCount; j++) { string str3 = string.Empty; if (j > 0) { str3 = ", "; } parametersWithTypes = parametersWithTypes + str3 + "object param" + j.ToString(CultureInfo.InvariantCulture); parameters = parameters + str3 + "param" + j.ToString(CultureInfo.InvariantCulture); } if ((item.ValueString != null) && (item.ValueString.Length != 0)) { writer.Write( @" /// <summary>" ); foreach (string str4 in item.ValueString.Replace("\r", string.Empty).Split("\n".ToCharArray())) { writer.Write(string.Format(CultureInfo.InvariantCulture, @" /// {0}" , str4)); } writer.Write( @" /// </summary>" ); } WriteMethodBody(item, Path.GetFileNameWithoutExtension(CsFileName), builder.ToString(), paramCount, parameters, parametersWithTypes); } else { writer.Write(string.Format(CultureInfo.InvariantCulture, @" public static {0} {1} {{ get {{ return ({0})ResourceManager.GetObject(""{2}""); }} }}" , item.DataType, builder, item.Name)); } } private void WriteMethodBody( ResourceItem item, string resourceClassName, string methodName, int paramCount, string parameters, string parametersWithTypes) { if (paramCount == 0) { writer.Write(string.Format(CultureInfo.InvariantCulture, @" public static string {0} {{ get {{ return ResourceManager.GetString(""{1}"", CultureInfo.CurrentUICulture); }} }} " , methodName, item.Name)); } else { writer.Write(string.Format(CultureInfo.InvariantCulture, @" public static string {0}({1}) {{ string format = ResourceManager.GetString(""{2}"", CultureInfo.CurrentUICulture); return string.Format(CultureInfo.CurrentCulture, format, {3}); }} " , methodName, parametersWithTypes, item.Name, parameters)); } } public int GetNumberOfParametersForStringResource(string resourceValue) { string input = resourceValue.Replace("{{", "").Replace("}}", ""); string pattern = "{(?<value>[^{}]*)}"; int num = -1; for (Match match = Regex.Match(input, pattern); match.Success; match = match.NextMatch()) { string str3 = null; try { str3 = match.Groups["value"].Value; } catch { } if ((str3 == null) || (str3.Length == 0)) { throw new ApplicationException( string.Format(CultureInfo.InvariantCulture, "\"{0}\": Empty format string at position {1}", new object[] { input, match.Index })); } string s = str3; int length = str3.IndexOfAny(",:".ToCharArray()); if (length > 0) { s = str3.Substring(0, length); } int num3 = -1; try { num3 = (int)uint.Parse(s, CultureInfo.InvariantCulture); } catch (Exception exception) { throw new ApplicationException(string.Format(CultureInfo.InvariantCulture, "\"{0}\": {1}: {{{2}}}", new object[] { input, exception.Message, str3 }), exception); } if (num3 > num) { num = num3; } } return (num + 1); } private void ReadResXResources() { XmlDocument document = new XmlDocument(); document.Load(this.InputFileName); Dictionary<string, string> assemblyDict = new Dictionary<string, string>(); foreach (XmlElement element in document.DocumentElement.SelectNodes("assembly")) { assemblyDict.Add(element.GetAttribute("alias"), element.GetAttribute("name")); } resources.Clear(); foreach (XmlElement element in document.DocumentElement.SelectNodes("data")) { string name = element.GetAttribute("name"); // This can happen... if ((name == null) || (name.Length == 0)) { WriteWarning("Resource skipped. Empty name attribute: {0}", element.OuterXml); continue; } CheckNameCharacters(name); Type dataType = null; string typeName = element.GetAttribute("type"); if ((typeName != null) && (typeName.Length != 0)) { string[] parts = typeName.Split(','); // Replace assembly alias with full name typeName = parts[0] + ", " + assemblyDict[parts[1].Trim()]; try { dataType = Type.GetType(typeName, true); } catch (Exception exception) { WriteWarning("Resource skipped. Could not load type {0}: {1}", typeName, exception.Message); continue; } } ResourceItem item = null; // String resources typically have no type name if ((dataType == null) || (dataType == typeof(string))) { string stringResourceValue = null; XmlNode node = element.SelectSingleNode("value"); if (node != null) { stringResourceValue = node.InnerXml; } if (stringResourceValue == null) { WriteWarning("Resource skipped. Empty value attribute: {0}", element.OuterXml); continue; } item = new ResourceItem(name, stringResourceValue); } else { if (dataType == typeof(Icon) || dataType == typeof(Bitmap)) haveDrawingResources = true; item = new ResourceItem(name, dataType); } this.resources.Add(item); } } private void ReadStringsFile() { resources.Clear(); using (StreamReader reader = new StreamReader(InputFileName)) { string line; int lineNum = 1; while ((line = reader.ReadLine()) != null) { int i = 0; while (i < line.Length && line[i] == ' ' || line[i] == '\t') i++; if (i >= line.Length) // Ignore empty lines continue; if (line.StartsWith("#")) continue; int j = line.IndexOf(':'); if (j == -1) throw new FormatException(String.Format("Expected a colon at line {0}", lineNum)); string name = line.Substring(i, j - i); CheckNameCharacters(name); i = j + 1; while (i < line.Length && line[i] != '"') i++; if (i >= line.Length) throw new FormatException(String.Format("Missing opening quote at line {0}", lineNum)); i++; StringBuilder value = new StringBuilder(); while (i < line.Length) { if (line[i] == '\\') { i++; if (i >= line.Length) break; value.Append(line[i++]); continue; } else if (line[i] == '"') break; value.Append(line[i++]); } if (i >= line.Length) throw new FormatException(String.Format("String is missing closing quote at line {0}", lineNum)); resources.Add(new ResourceItem(name, value.ToString())); } } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// The configuration for compute nodes in a pool based on the Azure Virtual Machines infrastructure. /// </summary> public partial class VirtualMachineConfiguration : ITransportObjectProvider<Models.VirtualMachineConfiguration>, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<ContainerConfiguration> ContainerConfigurationProperty; public readonly PropertyAccessor<IList<DataDisk>> DataDisksProperty; public readonly PropertyAccessor<ImageReference> ImageReferenceProperty; public readonly PropertyAccessor<string> LicenseTypeProperty; public readonly PropertyAccessor<string> NodeAgentSkuIdProperty; public readonly PropertyAccessor<WindowsConfiguration> WindowsConfigurationProperty; public PropertyContainer() : base(BindingState.Unbound) { this.ContainerConfigurationProperty = this.CreatePropertyAccessor<ContainerConfiguration>(nameof(ContainerConfiguration), BindingAccess.Read | BindingAccess.Write); this.DataDisksProperty = this.CreatePropertyAccessor<IList<DataDisk>>(nameof(DataDisks), BindingAccess.Read | BindingAccess.Write); this.ImageReferenceProperty = this.CreatePropertyAccessor<ImageReference>(nameof(ImageReference), BindingAccess.Read | BindingAccess.Write); this.LicenseTypeProperty = this.CreatePropertyAccessor<string>(nameof(LicenseType), BindingAccess.Read | BindingAccess.Write); this.NodeAgentSkuIdProperty = this.CreatePropertyAccessor<string>(nameof(NodeAgentSkuId), BindingAccess.Read | BindingAccess.Write); this.WindowsConfigurationProperty = this.CreatePropertyAccessor<WindowsConfiguration>(nameof(WindowsConfiguration), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.VirtualMachineConfiguration protocolObject) : base(BindingState.Bound) { this.ContainerConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ContainerConfiguration, o => new ContainerConfiguration(o)), nameof(ContainerConfiguration), BindingAccess.Read | BindingAccess.Write); this.DataDisksProperty = this.CreatePropertyAccessor( DataDisk.ConvertFromProtocolCollection(protocolObject.DataDisks), nameof(DataDisks), BindingAccess.Read | BindingAccess.Write); this.ImageReferenceProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ImageReference, o => new ImageReference(o)), nameof(ImageReference), BindingAccess.Read | BindingAccess.Write); this.LicenseTypeProperty = this.CreatePropertyAccessor( protocolObject.LicenseType, nameof(LicenseType), BindingAccess.Read | BindingAccess.Write); this.NodeAgentSkuIdProperty = this.CreatePropertyAccessor( protocolObject.NodeAgentSKUId, nameof(NodeAgentSkuId), BindingAccess.Read | BindingAccess.Write); this.WindowsConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.WindowsConfiguration, o => new WindowsConfiguration(o)), nameof(WindowsConfiguration), BindingAccess.Read | BindingAccess.Write); } } private readonly PropertyContainer propertyContainer; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="VirtualMachineConfiguration"/> class. /// </summary> /// <param name='imageReference'>A reference to the Azure Virtual Machines Marketplace Image or the custom Virtual Machine Image to use.</param> /// <param name='nodeAgentSkuId'>The SKU of Batch Node Agent to be provisioned on the compute node.</param> public VirtualMachineConfiguration( ImageReference imageReference, string nodeAgentSkuId) { this.propertyContainer = new PropertyContainer(); this.ImageReference = imageReference; this.NodeAgentSkuId = nodeAgentSkuId; } internal VirtualMachineConfiguration(Models.VirtualMachineConfiguration protocolObject) { this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region VirtualMachineConfiguration /// <summary> /// Gets or sets the container configuration for the pool. /// </summary> /// <remarks> /// If specified, setup is performed on each node in the pool to allow tasks to run in containers. All regular tasks /// and job manager tasks run on this pool must specify <see cref="TaskContainerSettings" />, and all other tasks /// may specify it. /// </remarks> public ContainerConfiguration ContainerConfiguration { get { return this.propertyContainer.ContainerConfigurationProperty.Value; } set { this.propertyContainer.ContainerConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the configuration for data disks attached to the Comptue Nodes in the pool. /// </summary> /// <remarks> /// This property must be specified if the Compute Nodes in the pool need to have empty data disks attached to them. /// This cannot be updated. /// </remarks> public IList<DataDisk> DataDisks { get { return this.propertyContainer.DataDisksProperty.Value; } set { this.propertyContainer.DataDisksProperty.Value = ConcurrentChangeTrackedModifiableList<DataDisk>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets a reference to the Azure Virtual Machines Marketplace Image or the custom Virtual Machine Image /// to use. /// </summary> public ImageReference ImageReference { get { return this.propertyContainer.ImageReferenceProperty.Value; } set { this.propertyContainer.ImageReferenceProperty.Value = value; } } /// <summary> /// Gets or sets the type of on-premises license to be used when deploying the operating system. /// </summary> /// <remarks> /// This only applies to images that contain the Windows operating system, and should only be used when you hold /// valid on-premises licenses for the nodes which will be deployed. If omitted, no on-premises licensing discount /// is applied. Values are: 'Windows_Server' - The on-premises license is for Windows Server. 'Windows_Client' - /// The on-premises license is for Windows Client. /// </remarks> public string LicenseType { get { return this.propertyContainer.LicenseTypeProperty.Value; } set { this.propertyContainer.LicenseTypeProperty.Value = value; } } /// <summary> /// Gets or sets the SKU of Batch Node Agent to be provisioned on the compute node. /// </summary> /// <remarks> /// The Batch node agent is a program that runs on each node in the pool, and provides the command-and-control interface /// between the node and the Batch service. There are different implementations of the node agent, known as SKUs, /// for different operating systems. /// </remarks> public string NodeAgentSkuId { get { return this.propertyContainer.NodeAgentSkuIdProperty.Value; } set { this.propertyContainer.NodeAgentSkuIdProperty.Value = value; } } /// <summary> /// Gets or sets windows operating system settings on the virtual machine. This property must not be specified if /// the ImageReference property specifies a Linux OS image. /// </summary> public WindowsConfiguration WindowsConfiguration { get { return this.propertyContainer.WindowsConfigurationProperty.Value; } set { this.propertyContainer.WindowsConfigurationProperty.Value = value; } } #endregion // VirtualMachineConfiguration #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.VirtualMachineConfiguration ITransportObjectProvider<Models.VirtualMachineConfiguration>.GetTransportObject() { Models.VirtualMachineConfiguration result = new Models.VirtualMachineConfiguration() { ContainerConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.ContainerConfiguration, (o) => o.GetTransportObject()), DataDisks = UtilitiesInternal.ConvertToProtocolCollection(this.DataDisks), ImageReference = UtilitiesInternal.CreateObjectWithNullCheck(this.ImageReference, (o) => o.GetTransportObject()), LicenseType = this.LicenseType, NodeAgentSKUId = this.NodeAgentSkuId, WindowsConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.WindowsConfiguration, (o) => o.GetTransportObject()), }; return result; } #endregion // Internal/private methods } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class HttpClientFailureExtensions { /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head400(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head400Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head400Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get400(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get400Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get400Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Put400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Patch400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Patch400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Post400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Post400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Delete400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Delete400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 401 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head401(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head401Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 401 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head401Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head401WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 402 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get402(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get402Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 402 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get402Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get402WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 403 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get403(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get403Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 403 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get403Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get403WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 404 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put404(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put404Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 404 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put404Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Put404WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 405 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch405(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch405Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 405 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Patch405Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Patch405WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 406 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post406(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post406Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 406 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Post406Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Post406WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 407 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete407(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete407Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 407 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Delete407Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Delete407WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 409 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put409(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put409Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 409 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put409Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Put409WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 410 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head410(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head410Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 410 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head410Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head410WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 411 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get411(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get411Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 411 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get411Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get411WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 412 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get412(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get412Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 412 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get412Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get412WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 413 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put413(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put413Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 413 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put413Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Put413WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 414 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch414(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch414Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 414 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Patch414Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Patch414WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 415 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post415(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post415Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 415 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Post415Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Post415WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 416 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get416(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get416Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 416 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get416Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get416WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 417 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete417(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete417Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 417 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Delete417Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Delete417WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 429 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head429(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head429Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 429 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head429Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Head429WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="" file="ExpressionWriter.cs"> // // </copyright> // <summary> // The expression writer. // </summary> // -------------------------------------------------------------------------------------------------------------------- #region using directives using System; using System.Collections; using System.Linq; using System.Linq.Expressions; using System.Text; using RabbitDB.Contracts.Expressions; using RabbitDB.Mapping; #endregion namespace RabbitDB.Expressions { /// <summary> /// The expression writer. /// </summary> /// <typeparam name="T"> /// </typeparam> internal class ExpressionWriter<T> : ExpressionVisitor { #region Fields /// <summary> /// The _expression build helper. /// </summary> private readonly IDbProviderExpressionBuildHelper _expressionBuildHelper; /// <summary> /// The _parameter collection. /// </summary> private readonly ExpressionParameterCollection _parameterCollection; /// <summary> /// The sql builder. /// </summary> private readonly StringBuilder _sqlBuilder = new StringBuilder(); /// <summary> /// The _table info. /// </summary> private readonly TableInfo _tableInfo; #endregion #region Construction /// <summary> /// Initializes a new instance of the <see cref="ExpressionWriter{T}" /> class. /// </summary> /// <param name="expressionBuildHelper"> /// The expression build helper. /// </param> /// <param name="parameterCollection"> /// The parameter collection. /// </param> internal ExpressionWriter( IDbProviderExpressionBuildHelper expressionBuildHelper, ExpressionParameterCollection parameterCollection) { _expressionBuildHelper = expressionBuildHelper; _tableInfo = TableInfo<T>.GetTableInfo; _parameterCollection = parameterCollection ?? new ExpressionParameterCollection(); } #endregion #region Properties /// <summary> /// Gets the parameters. /// </summary> internal object[] Parameters => _parameterCollection.ToArray(); #endregion #region Public Methods /// <summary> /// The write. /// </summary> /// <param name="criteria"> /// The criteria. /// </param> /// <returns> /// The <see cref="string" />. /// </returns> public string Write(Expression<Func<T, object>> criteria) { Visit(criteria); return _sqlBuilder.ToString(); } #endregion #region Internal Methods /// <summary> /// The write. /// </summary> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="string" />. /// </returns> internal string Write(Expression<Func<T, bool>> expression) { Visit(expression); return _sqlBuilder.ToString(); } #endregion #region Protected Methods /// <summary> /// The visit binary. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The <see cref="Expression" />. /// </returns> /// <exception cref="NotSupportedException"> /// </exception> protected override Expression VisitBinary(BinaryExpression node) { _sqlBuilder.Append("("); Visit(node.Left); switch (node.NodeType) { case ExpressionType.And: case ExpressionType.AndAlso: _sqlBuilder.Append(" AND "); break; case ExpressionType.Or: case ExpressionType.OrElse: _sqlBuilder.Append(" OR"); break; case ExpressionType.Equal: // wenn das rechts daneben null ist, dann "is" if (node.Right.IsNullOrEmpty()) { _sqlBuilder.Append(" IS "); break; } _sqlBuilder.Append(" = "); break; case ExpressionType.NotEqual: // wenn das rechts daneben null ist, dann "is not" if (node.Right.IsNullOrEmpty()) { _sqlBuilder.Append(" IS NOT "); break; } _sqlBuilder.Append(" <> "); break; case ExpressionType.LessThan: _sqlBuilder.Append(" < "); break; case ExpressionType.LessThanOrEqual: _sqlBuilder.Append(" <= "); break; case ExpressionType.GreaterThan: _sqlBuilder.Append(" > "); break; case ExpressionType.GreaterThanOrEqual: _sqlBuilder.Append(" >= "); break; case ExpressionType.Add: _sqlBuilder.Append(" + "); break; case ExpressionType.Subtract: _sqlBuilder.Append(" - "); break; case ExpressionType.Multiply: _sqlBuilder.Append(" * "); break; case ExpressionType.Divide: _sqlBuilder.Append(" / "); break; default: throw new NotSupportedException($"The binary operator '{node.NodeType}' is not supported"); } Visit(node.Right); _sqlBuilder.Append(")"); return node; } /// <summary> /// The visit constant. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The <see cref="Expression" />. /// </returns> /// <exception cref="NotSupportedException"> /// </exception> protected override Expression VisitConstant(ConstantExpression node) { IQueryable queryable = node.Value as IQueryable; if (queryable == null && node.Value == null) { _sqlBuilder.Append("NULL"); } else if (queryable == null) { switch (Type.GetTypeCode(node.Value.GetType())) { case TypeCode.Boolean: _sqlBuilder.Append(((bool)node.Value) ? 1 : 0); break; case TypeCode.DateTime: case TypeCode.String: _sqlBuilder.AppendFormat("'{0}'", node.Value); break; case TypeCode.Object: throw new NotSupportedException($"The constant for '{node.Value}' is not supported"); default: _sqlBuilder.Append(node.Value); break; } } return node; } /// <summary> /// The visit member. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The <see cref="Expression" />. /// </returns> protected override Expression VisitMember(MemberExpression node) { if (node.InvolvesParameter()) { HandleParameter(node); } else { _sqlBuilder.Append("@" + _parameterCollection.NextIndex); _parameterCollection.Add(node.GetValue()); } return node; } /// <summary> /// The visit method call. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The <see cref="Expression" />. /// </returns> protected override Expression VisitMethodCall(MethodCallExpression node) { if (node.InvolvesParameter()) { HandleParameter(node); } else { _sqlBuilder.Append("@" + _parameterCollection.NextIndex); _parameterCollection.Add(node.GetValue()); } return node; } /// <summary> /// The visit unary. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The <see cref="Expression" />. /// </returns> /// <exception cref="NotSupportedException"> /// </exception> protected override Expression VisitUnary(UnaryExpression node) { switch (node.NodeType) { case ExpressionType.Not: if (node.Operand.BelongsToParameter() && node.Operand.NodeType == ExpressionType.MemberAccess) { MemberExpression operand = node.Operand as MemberExpression; if (operand != null && operand.Type != typeof(bool)) { break; } Expression nex = EqualityFromUnary(node); Visit(nex); break; } _sqlBuilder.Append("NOT "); Visit(node.Operand); break; case ExpressionType.Convert: Visit(node.Operand); break; default: throw new NotSupportedException($"The unary operator '{node.NodeType}' is not supported"); } return node; } #endregion #region Private Methods /// <summary> /// The equality from unary. /// </summary> /// <param name="node"> /// The node. /// </param> /// <returns> /// The <see cref="Expression" />. /// </returns> private static Expression EqualityFromUnary(UnaryExpression node) { return Expression.Equal(node.Operand, Expression.Constant(node.NodeType != ExpressionType.Not)); } /// <summary> /// The handle contains. /// </summary> /// <param name="meth"> /// The meth. /// </param> /// <exception cref="NotSupportedException"> /// </exception> private void HandleContains(MethodCallExpression meth) { IList list; var pIdx = 1; if (meth.Arguments.Count == 1) { list = meth.Object.GetValue() as IList; pIdx = 0; } else { list = meth.Arguments[0].GetValue() as IList; } if (list == null) { throw new NotSupportedException("Contains must be invoked on a IList (array or List)"); } var param = meth.Arguments[pIdx] as MemberExpression; _sqlBuilder.Append(_expressionBuildHelper.EscapeName(param.Member.Name)) .AppendFormat(" in (@{0})", _parameterCollection.NextIndex); _parameterCollection.Add(list); } /// <summary> /// The handle parameter. /// </summary> /// <param name="node"> /// The node. /// </param> /// <exception cref="NotSupportedException"> /// </exception> private void HandleParameter(MethodCallExpression node) { if (node.HasParameterArgument()) { if (node.Method.Name != "Contains") { throw new NotSupportedException(); } HandleContains(node); return; } if (!node.BelongsToParameter()) { return; } if (node.Object != null && node.Object.Type == typeof(string)) { HandleParamStringFunctions(node); } } /// <summary> /// The handle parameter. /// </summary> /// <param name="node"> /// The node. /// </param> /// <param name="isSingle"> /// The is single. /// </param> private void HandleParameter(MemberExpression node, bool isSingle = false) { if (!node.BelongsToParameter()) { return; } if (!isSingle) { if (node.Expression.NodeType == ExpressionType.Parameter) { var propertyInfo = _tableInfo.Columns.FirstOrDefault(column => column.Name == node.Member.Name); if (propertyInfo != null) { _sqlBuilder.Append( _expressionBuildHelper.EscapeName(propertyInfo.ColumnAttribute.ColumnName)); } } else { HandleParameterSubProperty(node); } return; } if (node.Type != typeof(bool)) { return; } var equalExpression = Expression.Equal(node, Expression.Constant(true)); Visit(equalExpression); } /// <summary> /// The handle parameter sub property. /// </summary> /// <param name="node"> /// The node. /// </param> private void HandleParameterSubProperty(MemberExpression node) { if (node.Expression.Type == typeof(string)) { HandleStringProperties(node); } } /// <summary> /// The handle param string functions. /// </summary> /// <param name="node"> /// The node. /// </param> private void HandleParamStringFunctions(MethodCallExpression node) { var memberExpression = (MemberExpression)node.Object; if (memberExpression == null) { return; } var memberName = memberExpression.Member.Name; var arg = node.Arguments[0].GetValue(); string value = null; switch (node.Method.Name) { case "StartsWith": value = string.Format("{0} like '{1}%'", _expressionBuildHelper.EscapeName(memberName), arg); break; case "EndsWith": value = string.Format("{0} like '%{1}'", _expressionBuildHelper.EscapeName(memberName), arg); break; case "Contains": value = string.Format("{0} like '%{1}%'", _expressionBuildHelper.EscapeName(memberName), arg); break; case "ToUpper": case "ToUpperInvariant": value = _expressionBuildHelper.ToUpper(memberName); break; case "ToLower": case "ToLowerInvariant": value = _expressionBuildHelper.ToLower(memberName); break; case "Substring": value = _expressionBuildHelper.Substring( memberName, (int)arg, (int)node.Arguments[1].GetValue()); break; } _sqlBuilder.Append(value); } /// <summary> /// The handle string properties. /// </summary> /// <param name="node"> /// The node. /// </param> private void HandleStringProperties(MemberExpression node) { var name = ((MemberExpression)node.Expression).Member.Name; switch (node.Member.Name) { case "Length": _sqlBuilder.Append(_expressionBuildHelper.Length(name)); break; } } /// <summary> /// The strip quotes. /// </summary> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="Expression" />. /// </returns> private static Expression StripQuotes(Expression expression) { while (expression.NodeType == ExpressionType.Quote) { expression = ((UnaryExpression)expression).Operand; } return expression; } #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.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // enum identifying all predefined methods used in the C# compiler // // Naming convention is PREDEFMETH.PM_ <Predefined CType> _ < Predefined Name of Method> // if methods can only be disambiguated by signature, then follow the // above with _ <argument types> // // Keep this list sorted by containing type and name. internal enum PREDEFMETH { PM_FIRST = 0, PM_DECIMAL_OPDECREMENT, PM_DECIMAL_OPDIVISION, PM_DECIMAL_OPEQUALITY, PM_DECIMAL_OPGREATERTHAN, PM_DECIMAL_OPGREATERTHANOREQUAL, PM_DECIMAL_OPINCREMENT, PM_DECIMAL_OPINEQUALITY, PM_DECIMAL_OPLESSTHAN, PM_DECIMAL_OPLESSTHANOREQUAL, PM_DECIMAL_OPMINUS, PM_DECIMAL_OPMODULUS, PM_DECIMAL_OPMULTIPLY, PM_DECIMAL_OPPLUS, PM_DECIMAL_OPUNARYMINUS, PM_DECIMAL_OPUNARYPLUS, PM_DELEGATE_COMBINE, PM_DELEGATE_OPEQUALITY, PM_DELEGATE_OPINEQUALITY, PM_DELEGATE_REMOVE, PM_EXPRESSION_ADD, PM_EXPRESSION_ADD_USER_DEFINED, PM_EXPRESSION_ADDCHECKED, PM_EXPRESSION_ADDCHECKED_USER_DEFINED, PM_EXPRESSION_AND, PM_EXPRESSION_AND_USER_DEFINED, PM_EXPRESSION_ANDALSO, PM_EXPRESSION_ANDALSO_USER_DEFINED, PM_EXPRESSION_ARRAYINDEX, PM_EXPRESSION_ARRAYINDEX2, PM_EXPRESSION_ASSIGN, PM_EXPRESSION_CONDITION, PM_EXPRESSION_CONSTANT_OBJECT_TYPE, PM_EXPRESSION_CONVERT, PM_EXPRESSION_CONVERT_USER_DEFINED, PM_EXPRESSION_CONVERTCHECKED, PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED, PM_EXPRESSION_DIVIDE, PM_EXPRESSION_DIVIDE_USER_DEFINED, PM_EXPRESSION_EQUAL, PM_EXPRESSION_EQUAL_USER_DEFINED, PM_EXPRESSION_EXCLUSIVEOR, PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED, PM_EXPRESSION_FIELD, PM_EXPRESSION_GREATERTHAN, PM_EXPRESSION_GREATERTHAN_USER_DEFINED, PM_EXPRESSION_GREATERTHANOREQUAL, PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED, PM_EXPRESSION_LAMBDA, PM_EXPRESSION_LEFTSHIFT, PM_EXPRESSION_LEFTSHIFT_USER_DEFINED, PM_EXPRESSION_LESSTHAN, PM_EXPRESSION_LESSTHAN_USER_DEFINED, PM_EXPRESSION_LESSTHANOREQUAL, PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED, PM_EXPRESSION_MODULO, PM_EXPRESSION_MODULO_USER_DEFINED, PM_EXPRESSION_MULTIPLY, PM_EXPRESSION_MULTIPLY_USER_DEFINED, PM_EXPRESSION_MULTIPLYCHECKED, PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED, PM_EXPRESSION_NOTEQUAL, PM_EXPRESSION_NOTEQUAL_USER_DEFINED, PM_EXPRESSION_OR, PM_EXPRESSION_OR_USER_DEFINED, PM_EXPRESSION_ORELSE, PM_EXPRESSION_ORELSE_USER_DEFINED, PM_EXPRESSION_PARAMETER, PM_EXPRESSION_RIGHTSHIFT, PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED, PM_EXPRESSION_SUBTRACT, PM_EXPRESSION_SUBTRACT_USER_DEFINED, PM_EXPRESSION_SUBTRACTCHECKED, PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED, PM_EXPRESSION_UNARYPLUS_USER_DEFINED, PM_EXPRESSION_NEGATE, PM_EXPRESSION_NEGATE_USER_DEFINED, PM_EXPRESSION_NEGATECHECKED, PM_EXPRESSION_NEGATECHECKED_USER_DEFINED, PM_EXPRESSION_CALL, PM_EXPRESSION_NEW, PM_EXPRESSION_NEW_MEMBERS, PM_EXPRESSION_NEW_TYPE, PM_EXPRESSION_QUOTE, PM_EXPRESSION_ARRAYLENGTH, PM_EXPRESSION_NOT, PM_EXPRESSION_NOT_USER_DEFINED, PM_EXPRESSION_NEWARRAYINIT, PM_EXPRESSION_PROPERTY, PM_EXPRESSION_INVOKE, PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT, PM_G_OPTIONAL_CTOR, PM_G_OPTIONAL_GETHASVALUE, PM_G_OPTIONAL_GETVALUE, PM_G_OPTIONAL_GET_VALUE_OR_DEF, PM_STRING_CONCAT_OBJECT_1, // NOTE: these 3 must be sequential. See RealizeConcats PM_STRING_CONCAT_OBJECT_2, PM_STRING_CONCAT_OBJECT_3, PM_STRING_CONCAT_STRING_1, // NOTE: these 4 must be sequential. See RealizeConcats PM_STRING_CONCAT_STRING_2, PM_STRING_CONCAT_STRING_3, PM_STRING_CONCAT_STRING_4, PM_STRING_CONCAT_SZ_OBJECT, PM_STRING_CONCAT_SZ_STRING, PM_STRING_GETCHARS, PM_STRING_GETLENGTH, PM_STRING_OPEQUALITY, PM_STRING_OPINEQUALITY, PM_COUNT } // enum identifying all predefined properties used in the C# compiler // Naming convention is PREDEFMETH.PM_ <Predefined CType> _ < Predefined Name of Property> // Keep this list sorted by containing type and name. internal enum PREDEFPROP { PP_FIRST = 0, PP_G_OPTIONAL_VALUE, PP_COUNT, }; internal enum MethodRequiredEnum { Required, Optional } internal enum MethodCallingConventionEnum { Static, Virtual, Instance } // Enum used to encode a method signature // A signature is encoded as a sequence of int values. // The grammar for signatures is: // // signature // return_type count_of_parameters parameter_types // // type // any predefined type (ex: PredefinedType.PT_OBJECT, PredefinedType.PT_VOID) type_args // MethodSignatureEnum.SIG_CLASS_TYVAR index_of_class_tyvar // MethodSignatureEnum.SIG_METH_TYVAR index_of_method_tyvar // MethodSignatureEnum.SIG_SZ_ARRAY type // MethodSignatureEnum.SIG_REF type // MethodSignatureEnum.SIG_OUT type // internal enum MethodSignatureEnum { // Values 0 to PredefinedType.PT_VOID are reserved for predefined types in signatures // start next value at PredefinedType.PT_VOID + 1, SIG_CLASS_TYVAR = (int)PredefinedType.PT_VOID + 1, // next element in signature is index of class tyvar SIG_METH_TYVAR, // next element in signature is index of method tyvar SIG_SZ_ARRAY, // must be followed by signature type of array elements SIG_REF, // must be followed by signature of ref type SIG_OUT, // must be followed by signature of out type } // A description of a method the compiler uses while compiling. internal sealed class PredefinedMethodInfo { public PREDEFMETH method; public PredefinedType type; public PredefinedName name; public MethodCallingConventionEnum callingConvention; public ACCESS access; // ACCESS.ACC_UNKNOWN means any accessibility is ok public int cTypeVars; public int[] signature; // Size 8. expand this if a new method has a signature which doesn't fit in the current space public PredefinedMethodInfo(PREDEFMETH method, MethodRequiredEnum required, PredefinedType type, PredefinedName name, MethodCallingConventionEnum callingConvention, ACCESS access, int cTypeVars, int[] signature) { this.method = method; this.type = type; this.name = name; this.callingConvention = callingConvention; this.access = access; this.cTypeVars = cTypeVars; this.signature = signature; } } // A description of a method the compiler uses while compiling. internal sealed class PredefinedPropertyInfo { public PREDEFPROP property; public PredefinedName name; public PREDEFMETH getter; public PREDEFMETH setter; public PredefinedPropertyInfo(PREDEFPROP property, MethodRequiredEnum required, PredefinedName name, PREDEFMETH getter, PREDEFMETH setter) { this.property = property; this.name = name; this.getter = getter; this.setter = setter; } }; // Loads and caches predefined members. // Also finds constructors on delegate types. internal sealed class PredefinedMembers { private static void RETAILVERIFY(bool f) { if (!f) Debug.Assert(false, "panic!"); } private readonly SymbolLoader _loader; internal SymbolTable RuntimeBinderSymbolTable; private readonly MethodSymbol[] _methods = new MethodSymbol[(int)PREDEFMETH.PM_COUNT]; private readonly PropertySymbol[] _properties = new PropertySymbol[(int)PREDEFPROP.PP_COUNT]; private Name GetMethName(PREDEFMETH method) { return GetPredefName(GetMethPredefName(method)); } private AggregateSymbol GetMethParent(PREDEFMETH method) { return GetOptPredefAgg(GetMethPredefType(method)); } // delegate specific helpers private MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType, int[] signature) { Debug.Assert(delegateType != null && delegateType.IsDelegate()); Debug.Assert(signature != null); return LoadMethod( delegateType, signature, 0, // meth ty vars GetPredefName(PredefinedName.PN_CTOR), ACCESS.ACC_PUBLIC, false, // MethodCallingConventionEnum.Static false); // MethodCallingConventionEnum.Virtual } private MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType) { Debug.Assert(delegateType != null && delegateType.IsDelegate()); MethodSymbol ctor = FindDelegateConstructor(delegateType, s_DelegateCtorSignature1); if (ctor == null) { ctor = FindDelegateConstructor(delegateType, s_DelegateCtorSignature2); } return ctor; } public MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType, bool fReportErrors) { MethodSymbol ctor = FindDelegateConstructor(delegateType); if (ctor == null && fReportErrors) { GetErrorContext().Error(ErrorCode.ERR_BadDelegateConstructor, delegateType); } return ctor; } // property specific helpers private PropertySymbol EnsureProperty(PREDEFPROP property) { RETAILVERIFY((int)property > (int)PREDEFMETH.PM_FIRST && (int)property < (int)PREDEFMETH.PM_COUNT); if (_properties[(int)property] == null) { _properties[(int)property] = LoadProperty(property); } return _properties[(int)property]; } private PropertySymbol LoadProperty(PREDEFPROP property) { return LoadProperty( property, GetPropName(property), GetPropGetter(property), GetPropSetter(property)); } private Name GetPropName(PREDEFPROP property) { return GetPredefName(GetPropPredefName(property)); } private PropertySymbol LoadProperty( PREDEFPROP predefProp, Name propertyName, PREDEFMETH propertyGetter, PREDEFMETH propertySetter) { Debug.Assert(propertyName != null); Debug.Assert(propertyGetter > PREDEFMETH.PM_FIRST && propertyGetter < PREDEFMETH.PM_COUNT); Debug.Assert(propertySetter > PREDEFMETH.PM_FIRST && propertySetter <= PREDEFMETH.PM_COUNT); MethodSymbol getter = GetOptionalMethod(propertyGetter); MethodSymbol setter = null; if (propertySetter != PREDEFMETH.PM_COUNT) { setter = GetOptionalMethod(propertySetter); } if (getter == null && setter == null) { RuntimeBinderSymbolTable.AddPredefinedPropertyToSymbolTable(GetOptPredefAgg(GetPropPredefType(predefProp)), propertyName); getter = GetOptionalMethod(propertyGetter); if (propertySetter != PREDEFMETH.PM_COUNT) { setter = GetOptionalMethod(propertySetter); } } setter?.SetMethKind(MethodKindEnum.PropAccessor); PropertySymbol property = null; if (getter != null) { getter.SetMethKind(MethodKindEnum.PropAccessor); property = getter.getProperty(); // Didn't find it, so load it. if (property == null) { RuntimeBinderSymbolTable.AddPredefinedPropertyToSymbolTable(GetOptPredefAgg(GetPropPredefType(predefProp)), propertyName); } property = getter.getProperty(); Debug.Assert(property != null); if (property.name != propertyName || (propertySetter != PREDEFMETH.PM_COUNT && (setter == null || !setter.isPropertyAccessor() || setter.getProperty() != property)) || property.getBogus()) { property = null; } } return property; } private SymbolLoader GetSymbolLoader() { Debug.Assert(_loader != null); return _loader; } private ErrorHandling GetErrorContext() { return GetSymbolLoader().GetErrorContext(); } private TypeManager GetTypeManager() { return GetSymbolLoader().GetTypeManager(); } private BSYMMGR getBSymmgr() { return GetSymbolLoader().getBSymmgr(); } private Name GetPredefName(PredefinedName pn) { return NameManager.GetPredefinedName(pn); } private AggregateSymbol GetOptPredefAgg(PredefinedType pt) { return GetSymbolLoader().GetOptPredefAgg(pt); } private CType LoadTypeFromSignature(int[] signature, ref int indexIntoSignatures, TypeArray classTyVars) { Debug.Assert(signature != null); MethodSignatureEnum current = (MethodSignatureEnum)signature[indexIntoSignatures]; indexIntoSignatures++; switch (current) { case MethodSignatureEnum.SIG_REF: { CType refType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (refType == null) { return null; } return GetTypeManager().GetParameterModifier(refType, false); } case MethodSignatureEnum.SIG_OUT: { CType outType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (outType == null) { return null; } return GetTypeManager().GetParameterModifier(outType, true); } case MethodSignatureEnum.SIG_SZ_ARRAY: { CType elementType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (elementType == null) { return null; } return GetTypeManager().GetArray(elementType, 1, true); } case MethodSignatureEnum.SIG_METH_TYVAR: { int index = signature[indexIntoSignatures]; indexIntoSignatures++; return GetTypeManager().GetStdMethTypeVar(index); } case MethodSignatureEnum.SIG_CLASS_TYVAR: { int index = signature[indexIntoSignatures]; indexIntoSignatures++; return classTyVars[index]; } case (MethodSignatureEnum)PredefinedType.PT_VOID: return GetTypeManager().GetVoid(); default: { Debug.Assert(current >= 0 && (int)current < (int)PredefinedType.PT_COUNT); AggregateSymbol agg = GetOptPredefAgg((PredefinedType)current); if (agg != null) { CType[] typeArgs = new CType[agg.GetTypeVars().Count]; for (int iTypeArg = 0; iTypeArg < agg.GetTypeVars().Count; iTypeArg++) { typeArgs[iTypeArg] = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (typeArgs[iTypeArg] == null) { return null; } } AggregateType type = GetTypeManager().GetAggregate(agg, getBSymmgr().AllocParams(agg.GetTypeVars().Count, typeArgs)); if (type.isPredefType(PredefinedType.PT_G_OPTIONAL)) { return GetTypeManager().GetNubFromNullable(type); } return type; } } break; } return null; } private TypeArray LoadTypeArrayFromSignature(int[] signature, ref int indexIntoSignatures, TypeArray classTyVars) { Debug.Assert(signature != null); int count = signature[indexIntoSignatures]; indexIntoSignatures++; Debug.Assert(count >= 0); CType[] ptypes = new CType[count]; for (int i = 0; i < count; i++) { ptypes[i] = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (ptypes[i] == null) { return null; } } return getBSymmgr().AllocParams(count, ptypes); } public PredefinedMembers(SymbolLoader loader) { _loader = loader; Debug.Assert(_loader != null); _methods = new MethodSymbol[(int)PREDEFMETH.PM_COUNT]; _properties = new PropertySymbol[(int)PREDEFPROP.PP_COUNT]; #if DEBUG // validate the tables for (int i = (int)PREDEFMETH.PM_FIRST + 1; i < (int)PREDEFMETH.PM_COUNT; i++) { Debug.Assert((int)GetMethInfo((PREDEFMETH)i).method == i); } for (int i = (int)PREDEFPROP.PP_FIRST + 1; i < (int)PREDEFPROP.PP_COUNT; i++) { Debug.Assert((int)GetPropInfo((PREDEFPROP)i).property == i); } #endif } public PropertySymbol GetProperty(PREDEFPROP property) // Reports an error if the property is not found. { PropertySymbol result = EnsureProperty(property); if (result == null) { ReportError(property); } return result; } public MethodSymbol GetMethod(PREDEFMETH method) { MethodSymbol result = EnsureMethod(method); if (result == null) { ReportError(method); } return result; } private MethodSymbol GetOptionalMethod(PREDEFMETH method) { return EnsureMethod(method); } private MethodSymbol EnsureMethod(PREDEFMETH method) { RETAILVERIFY(method > PREDEFMETH.PM_FIRST && method < PREDEFMETH.PM_COUNT); if (_methods[(int)method] == null) { _methods[(int)method] = LoadMethod(method); } return _methods[(int)method]; } private MethodSymbol LoadMethod( AggregateSymbol type, int[] signature, int cMethodTyVars, Name methodName, ACCESS methodAccess, bool isStatic, bool isVirtual ) { Debug.Assert(signature != null); Debug.Assert(cMethodTyVars >= 0); Debug.Assert(methodName != null); if (type == null) { return null; } TypeArray classTyVars = type.GetTypeVarsAll(); int index = 0; CType returnType = LoadTypeFromSignature(signature, ref index, classTyVars); if (returnType == null) { return null; } TypeArray argumentTypes = LoadTypeArrayFromSignature(signature, ref index, classTyVars); if (argumentTypes == null) { return null; } TypeArray standardMethodTyVars = GetTypeManager().GetStdMethTyVarArray(cMethodTyVars); MethodSymbol ret = LookupMethodWhileLoading(type, cMethodTyVars, methodName, methodAccess, isStatic, isVirtual, returnType, argumentTypes); if (ret == null) { RuntimeBinderSymbolTable.AddPredefinedMethodToSymbolTable(type, methodName); ret = LookupMethodWhileLoading(type, cMethodTyVars, methodName, methodAccess, isStatic, isVirtual, returnType, argumentTypes); } return ret; } private MethodSymbol LookupMethodWhileLoading(AggregateSymbol type, int cMethodTyVars, Name methodName, ACCESS methodAccess, bool isStatic, bool isVirtual, CType returnType, TypeArray argumentTypes) { for (Symbol sym = GetSymbolLoader().LookupAggMember(methodName, type, symbmask_t.MASK_ALL); sym != null; sym = GetSymbolLoader().LookupNextSym(sym, type, symbmask_t.MASK_ALL)) { if (sym.IsMethodSymbol()) { MethodSymbol methsym = sym.AsMethodSymbol(); if ((methsym.GetAccess() == methodAccess || methodAccess == ACCESS.ACC_UNKNOWN) && methsym.isStatic == isStatic && methsym.isVirtual == isVirtual && methsym.typeVars.Count == cMethodTyVars && GetTypeManager().SubstEqualTypes(methsym.RetType, returnType, null, methsym.typeVars, SubstTypeFlags.DenormMeth) && GetTypeManager().SubstEqualTypeArrays(methsym.Params, argumentTypes, (TypeArray)null, methsym.typeVars, SubstTypeFlags.DenormMeth) && !methsym.getBogus()) { return methsym; } } } return null; } private MethodSymbol LoadMethod(PREDEFMETH method) { return LoadMethod( GetMethParent(method), GetMethSignature(method), GetMethTyVars(method), GetMethName(method), GetMethAccess(method), IsMethStatic(method), IsMethVirtual(method)); } private void ReportError(PREDEFMETH method) { ReportError(GetMethPredefType(method), GetMethPredefName(method)); } private void ReportError(PredefinedType type, PredefinedName name) { GetErrorContext().Error(ErrorCode.ERR_MissingPredefinedMember, PredefinedTypes.GetFullName(type), GetPredefName(name)); } private static readonly int[] s_DelegateCtorSignature1 = { (int)PredefinedType.PT_VOID, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_INTPTR }; private static readonly int[] s_DelegateCtorSignature2 = { (int)PredefinedType.PT_VOID, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_UINTPTR }; private static PredefinedName GetPropPredefName(PREDEFPROP property) { return GetPropInfo(property).name; } private static PREDEFMETH GetPropGetter(PREDEFPROP property) { PREDEFMETH result = GetPropInfo(property).getter; // getters are MethodRequiredEnum.Required Debug.Assert(result > PREDEFMETH.PM_FIRST && result < PREDEFMETH.PM_COUNT); return result; } private static PredefinedType GetPropPredefType(PREDEFPROP property) { return GetMethInfo(GetPropGetter(property)).type; } private static PREDEFMETH GetPropSetter(PREDEFPROP property) { PREDEFMETH result = GetPropInfo(property).setter; // setters are not MethodRequiredEnum.Required Debug.Assert(result > PREDEFMETH.PM_FIRST && result <= PREDEFMETH.PM_COUNT); return GetPropInfo(property).setter; } private void ReportError(PREDEFPROP property) { ReportError(GetPropPredefType(property), GetPropPredefName(property)); } // the list of predefined property definitions. // This list must be in the same order as the PREDEFPROP enum. private static readonly PredefinedPropertyInfo[] s_predefinedProperties = { new PredefinedPropertyInfo( PREDEFPROP.PP_FIRST, MethodRequiredEnum.Optional, PredefinedName.PN_COUNT, PREDEFMETH.PM_COUNT, PREDEFMETH.PM_COUNT ), new PredefinedPropertyInfo( PREDEFPROP.PP_G_OPTIONAL_VALUE, MethodRequiredEnum.Optional, PredefinedName.PN_CAP_VALUE, PREDEFMETH.PM_G_OPTIONAL_GETVALUE, PREDEFMETH.PM_COUNT ), }; private static PredefinedPropertyInfo GetPropInfo(PREDEFPROP property) { RETAILVERIFY(property > PREDEFPROP.PP_FIRST && property < PREDEFPROP.PP_COUNT); RETAILVERIFY(s_predefinedProperties[(int)property].property == property); return s_predefinedProperties[(int)property]; } private static PredefinedMethodInfo GetMethInfo(PREDEFMETH method) { RETAILVERIFY(method > PREDEFMETH.PM_FIRST && method < PREDEFMETH.PM_COUNT); RETAILVERIFY(s_predefinedMethods[(int)method].method == method); return s_predefinedMethods[(int)method]; } private static PredefinedName GetMethPredefName(PREDEFMETH method) { return GetMethInfo(method).name; } private static PredefinedType GetMethPredefType(PREDEFMETH method) { return GetMethInfo(method).type; } private static bool IsMethStatic(PREDEFMETH method) { return GetMethInfo(method).callingConvention == MethodCallingConventionEnum.Static; } private static bool IsMethVirtual(PREDEFMETH method) { return GetMethInfo(method).callingConvention == MethodCallingConventionEnum.Virtual; } private static ACCESS GetMethAccess(PREDEFMETH method) { return GetMethInfo(method).access; } private static int GetMethTyVars(PREDEFMETH method) { return GetMethInfo(method).cTypeVars; } private static int[] GetMethSignature(PREDEFMETH method) { return GetMethInfo(method).signature; } // the list of predefined method definitions. // This list must be in the same order as the PREDEFMETH enum. private static readonly PredefinedMethodInfo[] s_predefinedMethods = new PredefinedMethodInfo[(int)PREDEFMETH.PM_COUNT] { new PredefinedMethodInfo( PREDEFMETH.PM_FIRST, MethodRequiredEnum.Optional, PredefinedType.PT_COUNT, PredefinedName.PN_COUNT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDECREMENT, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDECREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDIVISION, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDIVISION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINCREMENT, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINCREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMINUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMODULUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMODULUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMULTIPLY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPPLUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYMINUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYPLUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_COMBINE, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_COMBINE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_REMOVE, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_REMOVE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ASSIGN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ASSIGN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONDITION, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONDITION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONDITIONALEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONSTANT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONSTANTEXPRESSION, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_FIELD, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CAP_FIELD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_FIELDINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LAMBDA, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LAMBDA, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 1, new int[] { (int)PredefinedType.PT_G_EXPRESSION, (int)MethodSignatureEnum.SIG_METH_TYVAR, 0, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_PARAMETEREXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PARAMETER, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PARAMETER, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_PARAMETEREXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PLUS , MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CALL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CALL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 2, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_MEMBERS, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 3, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)PredefinedType.PT_G_IENUMERABLE, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_MEMBERINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_TYPE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 1, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_QUOTE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_QUOTE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYLENGTH, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEWARRAYINIT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWARRAYEXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PROPERTY, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXPRESSION_PROPERTY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_PROPERTYINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_INVOKE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_INVOKE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INVOCATIONEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT, MethodRequiredEnum.Optional, PredefinedType.PT_METHODINFO, PredefinedName.PN_CREATEDELEGATE, MethodCallingConventionEnum.Virtual, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_OBJECT}), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_CTOR, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_CTOR, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 1, (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETHASVALUE, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETHASVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETVALUE, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GET_VALUE_OR_DEF, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GET_VALUE_OR_DEF, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_1, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_2, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_3, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_1, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_2, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_3, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_4, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 4, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_OBJECT, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_STRING, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETCHARS, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_GETCHARS, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CHAR, 1, (int)PredefinedType.PT_INT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_GETLENGTH, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INT, 0, }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), }; } }
/* * 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.IO; using System.Reflection; using System.Collections.Generic; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.Agent.AssetTransaction { public class AssetXferUploader { // Viewer's notion of the default texture private List<UUID> defaultIDs = new List<UUID> { new UUID("5748decc-f629-461c-9a36-a35a221fe21f"), new UUID("7ca39b4c-bd19-4699-aff7-f93fd03d3e7b"), new UUID("6522e74d-1660-4e7f-b601-6f48c1659a77"), new UUID("c228d1cf-4b5d-4ba8-84f4-899a0796aa97") }; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Upload state. /// </summary> /// <remarks> /// New -> Uploading -> Complete /// </remarks> private enum UploadState { New, Uploading, Complete } /// <summary> /// Reference to the object that holds this uploader. Used to remove ourselves from it's list if we /// are performing a delayed update. /// </summary> AgentAssetTransactions m_transactions; private UploadState m_uploadState = UploadState.New; private AssetBase m_asset; private UUID InventFolder = UUID.Zero; private sbyte invType = 0; private bool m_createItem; private uint m_createItemCallback; private bool m_updateItem; private InventoryItemBase m_updateItemData; private bool m_updateTaskItem; private TaskInventoryItem m_updateTaskItemData; private string m_description = String.Empty; private bool m_dumpAssetToFile; private string m_name = String.Empty; // private bool m_storeLocal; private uint nextPerm = 0; private IClientAPI ourClient; private UUID m_transactionID; private sbyte type = 0; private byte wearableType = 0; private byte[] m_oldData = null; public ulong XferID; private Scene m_Scene; /// <summary> /// AssetXferUploader constructor /// </summary> /// <param name='transactions'>/param> /// <param name='scene'></param> /// <param name='transactionID'></param> /// <param name='dumpAssetToFile'> /// If true then when the asset is uploaded it is dumped to a file with the format /// String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat", /// now.Year, now.Month, now.Day, now.Hour, now.Minute, /// now.Second, m_asset.Name, m_asset.Type); /// for debugging purposes. /// </param> public AssetXferUploader( AgentAssetTransactions transactions, Scene scene, UUID transactionID, bool dumpAssetToFile) { m_asset = new AssetBase(); m_transactions = transactions; m_transactionID = transactionID; m_Scene = scene; m_dumpAssetToFile = dumpAssetToFile; } /// <summary> /// Process transfer data received from the client. /// </summary> /// <param name="xferID"></param> /// <param name="packetID"></param> /// <param name="data"></param> /// <returns>True if the transfer is complete, false otherwise or if the xferID was not valid</returns> public bool HandleXferPacket(ulong xferID, uint packetID, byte[] data) { // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Received packet {0} for xfer {1} (data length {2})", // packetID, xferID, data.Length); if (XferID == xferID) { lock (this) { int assetLength = m_asset.Data.Length; int dataLength = data.Length; if (m_asset.Data.Length > 1) { byte[] destinationArray = new byte[assetLength + dataLength]; Array.Copy(m_asset.Data, 0, destinationArray, 0, assetLength); Array.Copy(data, 0, destinationArray, assetLength, dataLength); m_asset.Data = destinationArray; } else { if (dataLength > 4) { byte[] buffer2 = new byte[dataLength - 4]; Array.Copy(data, 4, buffer2, 0, dataLength - 4); m_asset.Data = buffer2; } } } ourClient.SendConfirmXfer(xferID, packetID); if ((packetID & 0x80000000) != 0) { SendCompleteMessage(); return true; } } return false; } /// <summary> /// Start asset transfer from the client /// </summary> /// <param name="remoteClient"></param> /// <param name="assetID"></param> /// <param name="transaction"></param> /// <param name="type"></param> /// <param name="data"> /// Optional data. If present then the asset is created immediately with this data /// rather than requesting an upload from the client. The data must be longer than 2 bytes. /// </param> /// <param name="storeLocal"></param> /// <param name="tempFile"></param> public void StartUpload( IClientAPI remoteClient, UUID assetID, UUID transaction, sbyte type, byte[] data, bool storeLocal, bool tempFile) { // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Initialised xfer from {0}, asset {1}, transaction {2}, type {3}, storeLocal {4}, tempFile {5}, already received data length {6}", // remoteClient.Name, assetID, transaction, type, storeLocal, tempFile, data.Length); lock (this) { if (m_uploadState != UploadState.New) { m_log.WarnFormat( "[ASSET XFER UPLOADER]: Tried to start upload of asset {0}, transaction {1} for {2} but this is already in state {3}. Aborting.", assetID, transaction, remoteClient.Name, m_uploadState); return; } m_uploadState = UploadState.Uploading; } ourClient = remoteClient; m_asset.FullID = assetID; m_asset.Type = type; m_asset.CreatorID = remoteClient.AgentId.ToString(); m_asset.Data = data; m_asset.Local = storeLocal; m_asset.Temporary = tempFile; // m_storeLocal = storeLocal; if (m_asset.Data.Length > 2) { SendCompleteMessage(); } else { RequestStartXfer(); } } protected void RequestStartXfer() { XferID = Util.GetNextXferID(); // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Requesting Xfer of asset {0}, type {1}, transfer id {2} from {3}", // m_asset.FullID, m_asset.Type, XferID, ourClient.Name); ourClient.SendXferRequest(XferID, m_asset.Type, m_asset.FullID, 0, new byte[0]); } protected void SendCompleteMessage() { // We must lock in order to avoid a race with a separate thread dealing with an inventory item or create // message from other client UDP. lock (this) { m_uploadState = UploadState.Complete; ourClient.SendAssetUploadCompleteMessage(m_asset.Type, true, m_asset.FullID); if (m_createItem) { CompleteCreateItem(m_createItemCallback); } else if (m_updateItem) { CompleteItemUpdate(m_updateItemData); } else if (m_updateTaskItem) { CompleteTaskItemUpdate(m_updateTaskItemData); } else if (m_asset.Local) { m_Scene.AssetService.Store(m_asset); } } m_log.DebugFormat( "[ASSET XFER UPLOADER]: Uploaded asset {0} for transaction {1}", m_asset.FullID, m_transactionID); if (m_dumpAssetToFile) { DateTime now = DateTime.Now; string filename = String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat", now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, m_asset.Name, m_asset.Type); SaveAssetToFile(filename, m_asset.Data); } } private void SaveAssetToFile(string filename, byte[] data) { string assetPath = "UserAssets"; if (!Directory.Exists(assetPath)) { Directory.CreateDirectory(assetPath); } FileStream fs = File.Create(Path.Combine(assetPath, filename)); BinaryWriter bw = new BinaryWriter(fs); bw.Write(data); bw.Close(); fs.Close(); } public void RequestCreateInventoryItem(IClientAPI remoteClient, UUID folderID, uint callbackID, string description, string name, sbyte invType, sbyte type, byte wearableType, uint nextOwnerMask) { InventFolder = folderID; m_name = name; m_description = description; this.type = type; this.invType = invType; this.wearableType = wearableType; nextPerm = nextOwnerMask; m_asset.Name = name; m_asset.Description = description; m_asset.Type = type; // We must lock to avoid a race with a separate thread uploading the asset. lock (this) { if (m_uploadState == UploadState.Complete) { CompleteCreateItem(callbackID); } else { m_createItem = true; //set flag so the inventory item is created when upload is complete m_createItemCallback = callbackID; } } } public void RequestUpdateInventoryItem(IClientAPI remoteClient, InventoryItemBase item) { // We must lock to avoid a race with a separate thread uploading the asset. lock (this) { m_asset.Name = item.Name; m_asset.Description = item.Description; m_asset.Type = (sbyte)item.AssetType; // remove redundante m_Scene.InventoryService.UpdateItem // if uploadState == UploadState.Complete) // if (m_asset.FullID != UUID.Zero) // { // We must always store the item at this point even if the asset hasn't finished uploading, in order // to avoid a race condition when the appearance module retrieves the item to set the asset id in // the AvatarAppearance structure. // item.AssetID = m_asset.FullID; // m_Scene.InventoryService.UpdateItem(item); // } if (m_uploadState == UploadState.Complete) { CompleteItemUpdate(item); } else { // do it here to avoid the eventual race condition if (m_asset.FullID != UUID.Zero) { // We must always store the item at this point even if the asset hasn't finished uploading, in order // to avoid a race condition when the appearance module retrieves the item to set the asset id in // the AvatarAppearance structure. item.AssetID = m_asset.FullID; m_Scene.InventoryService.UpdateItem(item); } // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Holding update inventory item request {0} for {1} pending completion of asset xfer for transaction {2}", // item.Name, remoteClient.Name, transactionID); m_updateItem = true; m_updateItemData = item; } } } public void RequestUpdateTaskInventoryItem(IClientAPI remoteClient, TaskInventoryItem taskItem) { // We must lock to avoid a race with a separate thread uploading the asset. lock (this) { m_asset.Name = taskItem.Name; m_asset.Description = taskItem.Description; m_asset.Type = (sbyte)taskItem.Type; taskItem.AssetID = m_asset.FullID; if (m_uploadState == UploadState.Complete) { CompleteTaskItemUpdate(taskItem); } else { m_updateTaskItem = true; m_updateTaskItemData = taskItem; } } } /// <summary> /// Store the asset for the given item when it has been uploaded. /// </summary> /// <param name="item"></param> private void CompleteItemUpdate(InventoryItemBase item) { // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Storing asset {0} for earlier item update for {1} for {2}", // m_asset.FullID, item.Name, ourClient.Name); ValidateAssets(); m_Scene.AssetService.Store(m_asset); if (m_asset.FullID != UUID.Zero) { item.AssetID = m_asset.FullID; m_Scene.InventoryService.UpdateItem(item); } ourClient.SendInventoryItemCreateUpdate(item, m_transactionID, 0); m_transactions.RemoveXferUploader(m_transactionID); m_Scene.EventManager.TriggerOnNewInventoryItemUploadComplete(ourClient.AgentId, (AssetType)type, m_asset.FullID, m_asset.Name, 0); } /// <summary> /// Store the asset for the given task item when it has been uploaded. /// </summary> /// <param name="taskItem"></param> private void CompleteTaskItemUpdate(TaskInventoryItem taskItem) { // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Storing asset {0} for earlier task item update for {1} for {2}", // m_asset.FullID, taskItem.Name, ourClient.Name); ValidateAssets(); m_Scene.AssetService.Store(m_asset); m_transactions.RemoveXferUploader(m_transactionID); } private void CompleteCreateItem(uint callbackID) { ValidateAssets(); m_Scene.AssetService.Store(m_asset); InventoryItemBase item = new InventoryItemBase(); item.Owner = ourClient.AgentId; item.CreatorId = ourClient.AgentId.ToString(); item.ID = UUID.Random(); item.AssetID = m_asset.FullID; item.Description = m_description; item.Name = m_name; item.AssetType = type; item.InvType = invType; item.Folder = InventFolder; item.BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export); item.CurrentPermissions = item.BasePermissions; item.GroupPermissions=0; item.EveryOnePermissions=0; item.NextPermissions = nextPerm; item.Flags = (uint) wearableType; item.CreationDate = Util.UnixTimeSinceEpoch(); m_log.DebugFormat("[XFER]: Created item {0} with asset {1}", item.ID, item.AssetID); if (m_Scene.AddInventoryItem(item)) ourClient.SendInventoryItemCreateUpdate(item, m_transactionID, callbackID); else ourClient.SendAlertMessage("Unable to create inventory item"); m_transactions.RemoveXferUploader(m_transactionID); } private void ValidateAssets() { if (m_asset.Type == (sbyte)CustomAssetType.AnimationSet) { AnimationSet animSet = new AnimationSet(m_asset.Data); bool allOk = animSet.Validate(x => { int perms = m_Scene.InventoryService.GetAssetPermissions(ourClient.AgentId, x); int required = (int)(PermissionMask.Transfer | PermissionMask.Copy); if ((perms & required) != required) return false; return true; }); if (!allOk) m_asset.Data = animSet.ToBytes(); } if (m_asset.Type == (sbyte)AssetType.Clothing || m_asset.Type == (sbyte)AssetType.Bodypart) { string content = System.Text.Encoding.ASCII.GetString(m_asset.Data); string[] lines = content.Split(new char[] {'\n'}); List<string> validated = new List<string>(); Dictionary<int, UUID> allowed = ExtractTexturesFromOldData(); int textures = 0; foreach (string line in lines) { try { if (line.StartsWith("textures ")) { textures = Convert.ToInt32(line.Substring(9)); validated.Add(line); } else if (textures > 0) { string[] parts = line.Split(new char[] {' '}); UUID tx = new UUID(parts[1]); int id = Convert.ToInt32(parts[0]); if (defaultIDs.Contains(tx) || tx == UUID.Zero || (allowed.ContainsKey(id) && allowed[id] == tx)) { validated.Add(parts[0] + " " + tx.ToString()); } else { int perms = m_Scene.InventoryService.GetAssetPermissions(ourClient.AgentId, tx); int full = (int)(PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Copy); if ((perms & full) != full) { m_log.ErrorFormat("[ASSET UPLOADER]: REJECTED update with texture {0} from {1} because they do not own the texture", tx, ourClient.AgentId); validated.Add(parts[0] + " " + UUID.Zero.ToString()); } else { validated.Add(line); } } textures--; } else { validated.Add(line); } } catch { // If it's malformed, skip it } } string final = String.Join("\n", validated.ToArray()); m_asset.Data = System.Text.Encoding.ASCII.GetBytes(final); } } /// <summary> /// Get the asset data uploaded in this transfer. /// </summary> /// <returns>null if the asset has not finished uploading</returns> public AssetBase GetAssetData() { if (m_uploadState == UploadState.Complete) { ValidateAssets(); return m_asset; } return null; } public void SetOldData(byte[] d) { m_oldData = d; } private Dictionary<int,UUID> ExtractTexturesFromOldData() { Dictionary<int,UUID> result = new Dictionary<int,UUID>(); if (m_oldData == null) return result; string content = System.Text.Encoding.ASCII.GetString(m_oldData); string[] lines = content.Split(new char[] {'\n'}); int textures = 0; foreach (string line in lines) { try { if (line.StartsWith("textures ")) { textures = Convert.ToInt32(line.Substring(9)); } else if (textures > 0) { string[] parts = line.Split(new char[] {' '}); UUID tx = new UUID(parts[1]); int id = Convert.ToInt32(parts[0]); result[id] = tx; textures--; } } catch { // If it's malformed, skip it } } return result; } } }
using System; using System.Text; using System.Collections; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Text.RegularExpressions; namespace IfacesEnumsStructsClasses { /// <summary> /// Windows API constants and functions /// </summary> public sealed class WinApis { public const uint MAX_PATH = 512; public const uint STGM_READ = 0x00000000; public const uint SHDVID_SSLSTATUS = 33; public const int GWL_WNDPROC = -4; public const uint KEYEVENTF_EXTENDEDKEY = 0x01; public const uint KEYEVENTF_KEYUP = 0x02; public const short //defined inWTypes.h // 0 == FALSE, -1 == TRUE //typedef short VARIANT_BOOL; VAR_TRUE = -1, VAR_FALSE = 0; #region Methods - GetWindowName - GetWindowClass public static int HiWord(int number) { if ((number & 0x80000000) == 0x80000000) return (number >> 16); else return (number >> 16) & 0xffff; } public static int LoWord(int number) { return number & 0xffff; } public static int MakeLong(int LoWord, int HiWord) { return (HiWord << 16) | (LoWord & 0xffff); } public static IntPtr MakeLParam(int LoWord, int HiWord) { return (IntPtr)((HiWord << 16) | (LoWord & 0xffff)); } public static string GetWindowName(IntPtr Hwnd) { if (Hwnd == IntPtr.Zero) return string.Empty; // This function gets the name of a window from its handle StringBuilder Title = new StringBuilder((int)WinApis.MAX_PATH); WinApis.GetWindowText(Hwnd, Title, (int)WinApis.MAX_PATH); return Title.ToString().Trim(); } public static string GetWindowClass(IntPtr Hwnd) { if (Hwnd == IntPtr.Zero) return string.Empty; // This function gets the name of a window class from a window handle StringBuilder Title = new StringBuilder((int)WinApis.MAX_PATH); WinApis.RealGetWindowClass(Hwnd, Title, (int)WinApis.MAX_PATH); return Title.ToString().Trim(); } public static FILETIME DateTimeToFiletime(DateTime time) { FILETIME ft; long hFT1 = time.ToFileTimeUtc(); ft.dwLowDateTime = (uint)(hFT1 & 0xFFFFFFFF); ft.dwHighDateTime = (uint)(hFT1 >> 32); return ft; } public static DateTime FiletimeToDateTime(FILETIME fileTime) { if ((fileTime.dwHighDateTime == Int32.MaxValue) || (fileTime.dwHighDateTime == 0 && fileTime.dwLowDateTime == 0)) { // Not going to fit in the DateTime. In the WinInet APIs, this is // what happens when there is no FILETIME attached to the cache entry. // We're going to use DateTime.MinValue as a marker for this case. return DateTime.MaxValue; } //long hFT2 = (((long)fileTime.dwHighDateTime) << 32) + fileTime.dwLowDateTime; //return DateTime.FromFileTimeUtc(hFT2); SYSTEMTIME syst = new SYSTEMTIME(); SYSTEMTIME systLocal = new SYSTEMTIME(); if (0 == FileTimeToSystemTime(ref fileTime, ref syst)) { throw new ApplicationException("Error calling FileTimeToSystemTime: " + Marshal.GetLastWin32Error().ToString()); } if (0 == SystemTimeToTzSpecificLocalTime(IntPtr.Zero, ref syst, out systLocal)) { throw new ApplicationException("Error calling SystemTimeToTzSpecificLocalTime: " + Marshal.GetLastWin32Error().ToString()); } return new DateTime(systLocal.Year, systLocal.Month, systLocal.Day, systLocal.Hour, systLocal.Minute, systLocal.Second); } public static string ToStringFromFileTime(FILETIME ft) { DateTime dt = FiletimeToDateTime(ft); if (dt == DateTime.MinValue) { return string.Empty; } return dt.ToString(); } /// <summary> /// UrlCache functionality is taken from: /// Scott McMaster ([email protected]) /// CodeProject article /// /// There were some issues with preparing URLs /// for RegExp to work properly. This is /// demonstrated in AllForms.SetupCookieCachePattern method /// /// urlPattern: /// . Dump the entire contents of the cache. /// Cookie: Lists all cookies on the system. /// Visited: Lists all of the history items. /// Cookie:.*\.example\.com Lists cookies from the example.com domain. /// http://www.example.com/example.html$: Lists the specific named file if present /// \.example\.com: Lists any and all entries from *.example.com. /// \.example\.com.*\.gif$: Lists the .gif files from *.example.com. /// \.js$: Lists the .js files in the cache. /// </summary> /// <param name="urlPattern"></param> /// <returns></returns> public static ArrayList FindUrlCacheEntries(string urlPattern) { ArrayList results = new ArrayList(); IntPtr buffer = IntPtr.Zero; UInt32 structSize; //This call will fail but returns the size required in structSize //to allocate necessary buffer IntPtr hEnum = FindFirstUrlCacheEntry(null, buffer, out structSize); try { if (hEnum == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); if (lastError == Hresults.ERROR_INSUFFICIENT_BUFFER) { //Allocate buffer buffer = Marshal.AllocHGlobal((int)structSize); //Call again, this time it should succeed hEnum = FindFirstUrlCacheEntry(urlPattern, buffer, out structSize); } else if (lastError == Hresults.ERROR_NO_MORE_ITEMS) { return results; } } INTERNET_CACHE_ENTRY_INFO result = (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buffer, typeof(INTERNET_CACHE_ENTRY_INFO)); try { if (Regex.IsMatch(result.lpszSourceUrlName, urlPattern, RegexOptions.IgnoreCase)) { results.Add(result); } } catch (ArgumentException ae) { throw new ApplicationException("Invalid regular expression, details=" + ae.Message); } if (buffer != IntPtr.Zero) { try { Marshal.FreeHGlobal(buffer); } catch { } buffer = IntPtr.Zero; structSize = 0; } //Loop through all entries, attempt to find matches while (true) { long nextResult = FindNextUrlCacheEntry(hEnum, buffer, out structSize); if (nextResult != 1) //TRUE { int lastError = Marshal.GetLastWin32Error(); if (lastError == Hresults.ERROR_INSUFFICIENT_BUFFER) { buffer = Marshal.AllocHGlobal((int)structSize); nextResult = FindNextUrlCacheEntry(hEnum, buffer, out structSize); } else if (lastError == Hresults.ERROR_NO_MORE_ITEMS) { break; } } result = (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buffer, typeof(INTERNET_CACHE_ENTRY_INFO)); if (Regex.IsMatch(result.lpszSourceUrlName, urlPattern, RegexOptions.IgnoreCase)) { results.Add(result); } if (buffer != IntPtr.Zero) { try { Marshal.FreeHGlobal(buffer); } catch { } buffer = IntPtr.Zero; structSize = 0; } } } finally { if (hEnum != IntPtr.Zero) { FindCloseUrlCache(hEnum); } if (buffer != IntPtr.Zero) { try { Marshal.FreeHGlobal(buffer); } catch { } } } return results; } /// <summary> /// Attempts to delete a cookie or cache entry /// </summary> /// <param name="url">INTERNET_CACHE_ENTRY_INFO.lpszSourceUrlName</param> public static void DeleteFromUrlCache(string url) { long apiResult = DeleteUrlCacheEntry(url); if (apiResult != 0) { return; } int lastError = Marshal.GetLastWin32Error(); if (lastError == Hresults.ERROR_ACCESS_DENIED) { throw new ApplicationException("Access denied: " + url); } else { throw new ApplicationException("Insufficient buffer: " + url); } } #endregion [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern IntPtr ExtractIcon(IntPtr hInst, string lpszExeFileName, int nIconIndex); [DllImport("user32.dll")] public static extern bool DestroyIcon(IntPtr hIcon); [DllImport("user32", SetLastError = true, CharSet = CharSet.Auto)] public static extern int CallWindowProc( IntPtr lpPrevWndFunc, IntPtr hWnd, int Msg, int wParam, int lParam); [DllImport("user32", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SetWindowLong( IntPtr hWnd, int nIndex, IntPtr newProc); [DllImport("ole32.dll", SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] public static extern int RevokeObjectParam( [In, MarshalAs(UnmanagedType.LPWStr)] string pszKey); //[DllImport("urlmon.dll", SetLastError = true)] //public static extern int RegisterBindStatusCallback( // [MarshalAs(UnmanagedType.Interface)] IBindCtx pBc, // [MarshalAs(UnmanagedType.Interface)] DownloadManagerImpl.IBindStatusCallback pBSCb, // [Out, MarshalAs(UnmanagedType.Interface)] out IBindStatusCallback ppBSCBPrev, // [In, MarshalAs(UnmanagedType.U4)] UInt32 dwReserved); //[DllImport("user32.dll", SetLastError = true)] //public static extern int GetClipboardFormatName(uint format, [Out] StringBuilder // lpszFormatName, int cchMaxCount); [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr GetWindowDC(IntPtr hWnd); //MSDN //This function should no longer be used. Use the CoTaskMemFree and CoTaskMemAlloc functions in its place. [DllImport("shell32.dll", SetLastError = true)] public static extern int SHGetMalloc(out IMalloc ppMalloc); [DllImport("gdi32.dll", SetLastError = true)] public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)] public static extern bool DeleteDC(IntPtr hdc); [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll", SetLastError = true)] public static extern bool SetStretchBltMode(IntPtr hdc, StretchMode iStretchMode); [DllImport("gdi32.dll", SetLastError = true)] public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjSource, int nXSrc, int nYSrc, TernaryRasterOperations dwRop); [DllImport("gdi32.dll", SetLastError = true)] public static extern bool StretchBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidthDest, int nHeightDest, IntPtr hdcSrc, int nXSrc, int nYSrc, int nWidthSrc, int nHeightSrc, TernaryRasterOperations dwRop); [DllImport("ole32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] public static extern int CreateBindCtx( [MarshalAs(UnmanagedType.U4)] uint dwReserved, [Out, MarshalAs(UnmanagedType.Interface)] out IBindCtx ppbc); [DllImport("ole32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] public static extern int CreateAsyncBindCtx( [MarshalAs(UnmanagedType.U4)] uint dwReserved, [MarshalAs(UnmanagedType.Interface)] IBindStatusCallback pbsc, [MarshalAs(UnmanagedType.Interface)] IEnumFORMATETC penumfmtetc, [Out, MarshalAs(UnmanagedType.Interface)] out IBindCtx ppbc); [DllImport("urlmon.dll", ExactSpelling = true, CharSet = CharSet.Auto)] public static extern int CreateURLMoniker( [MarshalAs(UnmanagedType.Interface)] IMoniker pmkContext, [MarshalAs(UnmanagedType.LPWStr)] string szURL, [Out, MarshalAs(UnmanagedType.Interface)] out IMoniker ppmk); public const uint URL_MK_LEGACY = 0; public const uint URL_MK_UNIFORM = 1; public const uint URL_MK_NO_CANONICALIZE = 2; [DllImport("urlmon.dll", ExactSpelling = true, CharSet = CharSet.Auto)] public static extern int CreateURLMonikerEx( [MarshalAs(UnmanagedType.Interface)] IMoniker pmkContext, [MarshalAs(UnmanagedType.LPWStr)] string szURL, [Out, MarshalAs(UnmanagedType.Interface)] out IMoniker ppmk, uint URL_MK_XXX); //Flags, one of [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, ref StringBuilder lParam); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern void SendMessage(HandleRef hWnd, uint msg, IntPtr wParam, ref tagRECT lParam); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(HandleRef hWnd, uint msg, IntPtr wParam, ref tagPOINT lParam); [DllImport("ole32.dll", CharSet = CharSet.Auto)] public static extern int CreateStreamOnHGlobal(IntPtr hGlobal, bool fDeleteOnRelease, [MarshalAs(UnmanagedType.Interface)] out IStream ppstm); [DllImport("user32.dll")] public static extern short GetKeyState(int nVirtKey); [DllImport("ole32.dll", ExactSpelling = true, PreserveSig = false)] [return: MarshalAs(UnmanagedType.Interface)] public static extern object CoCreateInstance( [In, MarshalAs(UnmanagedType.LPStruct)] Guid rclsid, [MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, CLSCTX dwClsContext, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid); //MessageBox(new IntPtr(0), "Text", "Caption", 0 ); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern uint MessageBox( IntPtr hWnd, String text, String caption, uint type); [DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr hWnd, out tagRECT lpRect); [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd); [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, IntPtr windowTitle); [DllImport("user32.dll")] public static extern int GetWindowText(IntPtr hWnd, StringBuilder title, int size); [DllImport("user32.dll")] public static extern uint RealGetWindowClass(IntPtr hWnd, StringBuilder pszType, uint cchType); [DllImport("user32.dll")] public static extern IntPtr SetFocus(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool CopyRect( [In, Out, MarshalAs(UnmanagedType.Struct)] ref tagRECT lprcDst, [In, MarshalAs(UnmanagedType.Struct)] ref tagRECT lprcSrc); //[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] //public static extern uint RegisterClipboardFormat(string lpszFormat); [DllImport("ole32.dll")] public static extern void ReleaseStgMedium( [In, MarshalAs(UnmanagedType.Struct)] ref System.Runtime.InteropServices.ComTypes.STGMEDIUM pmedium); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern uint DragQueryFile(IntPtr hDrop, uint iFile, [Out] StringBuilder lpszFile, uint cch); [DllImport("kernel32.dll")] public static extern IntPtr GlobalLock(IntPtr hMem); [DllImport("kernel32.dll")] public static extern bool GlobalUnlock(IntPtr hMem); [DllImport("kernel32.dll")] public static extern UIntPtr GlobalSize(IntPtr hMem); [DllImport("Kernel32.dll", SetLastError = true)] public static extern long FileTimeToSystemTime(ref FILETIME FileTime, ref SYSTEMTIME SystemTime); [DllImport("kernel32.dll", SetLastError = true)] public static extern long SystemTimeToTzSpecificLocalTime( IntPtr lpTimeZoneInformation, ref SYSTEMTIME lpUniversalTime, out SYSTEMTIME lpLocalTime); [DllImport("wininet.dll", SetLastError = true)] public static extern long FindCloseUrlCache(IntPtr hEnumHandle); [DllImport("wininet.dll", SetLastError = true)] public static extern IntPtr FindFirstUrlCacheEntry(string lpszUrlSearchPattern, IntPtr lpFirstCacheEntryInfo, out UInt32 lpdwFirstCacheEntryInfoBufferSize); [DllImport("wininet.dll", SetLastError = true)] public static extern long FindNextUrlCacheEntry(IntPtr hEnumHandle, IntPtr lpNextCacheEntryInfo, out UInt32 lpdwNextCacheEntryInfoBufferSize); [DllImport("wininet.dll", SetLastError = true)] public static extern bool GetUrlCacheEntryInfo(string lpszUrlName, IntPtr lpCacheEntryInfo, out UInt32 lpdwCacheEntryInfoBufferSize); [DllImport("wininet.dll", SetLastError = true)] public static extern long DeleteUrlCacheEntry(string lpszUrlName); [DllImport("wininet.dll", SetLastError = true)] public static extern IntPtr RetrieveUrlCacheEntryStream(string lpszUrlName, IntPtr lpCacheEntryInfo, out UInt32 lpdwCacheEntryInfoBufferSize, long fRandomRead, UInt32 dwReserved); [DllImport("wininet.dll", SetLastError = true)] public static extern IntPtr ReadUrlCacheEntryStream(IntPtr hUrlCacheStream, UInt32 dwLocation, IntPtr lpBuffer, out UInt32 lpdwLen, UInt32 dwReserved); [DllImport("wininet.dll", SetLastError = true)] public static extern long UnlockUrlCacheEntryStream(IntPtr hUrlCacheStream, UInt32 dwReserved); [DllImport("user32.dll", SetLastError = true)] public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni); private const uint SPIF_UPDATEINIFILE = 0x0001; private const uint SPIF_SENDWININICHANGE = 0x0002; //SPIF_SENDCHANGE SPIF_SENDWININICHANGE private const uint SPI_SETBEEP = 0x0002; //For older windows public static bool SetSystemBeep(bool bEnable) { if (bEnable) return SystemParametersInfo(SPI_SETBEEP, 1, IntPtr.Zero, (SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE)); else return SystemParametersInfo(SPI_SETBEEP, 0, IntPtr.Zero, (SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE)); } //Pass IntPtr.Zero for hInternet to indicate global //dwOption, one of INTERNET_OPTION_XXXX flags //To retrieve all cookies for a particular domain, call //InternetGetCookie[Ex]. To delete them, call InternetSetCookie[Ex]: pass //IntPtr.Zero for cookie data to delete a cookie. [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, //Len of lpBuffer in bytes //If lpBuffer contains a string, the size is in TCHARs. If lpBuffer contains anything other than a string, the size is in bytes. int lpdwBufferLength); //call DoOrganizeFavDlg( this.Handle.ToInt64(), null ); [DllImport("shdocvw.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern long DoOrganizeFavDlg(long hWnd, string lpszRootFolder); [DllImport("shdocvw.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern long AddUrlToFavorites(long hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszUrlW, [MarshalAs(UnmanagedType.LPWStr)] string pszTitleW, //If null, url value is used [MarshalAs(UnmanagedType.Bool)] bool fDisplayUI); [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool InternetGetCookie(string lpszUrlName, string lpszCookieName, [Out] string lpszCookieData, [MarshalAs(UnmanagedType.U4)] out int lpdwSize); [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool InternetSetCookie(string lpszUrlName, string lpszCookieName, IntPtr lpszCookieData); } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Daniel Grunwald" email="[email protected]"/> // <version>$Revision: 3630 $</version> // </file> using System; using System.Collections.Generic; using System.Text; namespace ICSharpCode.SharpDevelop.Dom { /// <summary> /// ConstructedReturnType is a reference to generic class that specifies the type parameters. /// When getting the Members, this return type modifies the lists in such a way that the /// <see cref="GenericReturnType"/>s are replaced with the return types in the type parameters /// collection. /// Example: List&lt;string&gt; /// </summary> public sealed class ConstructedReturnType : DecoratingReturnType { // Return types that should be substituted for the generic types // If a substitution is unknown (type could not be resolved), the list // contains a null entry. IList<IReturnType> typeArguments; IReturnType baseType; public IList<IReturnType> TypeArguments { get { return typeArguments; } } public ConstructedReturnType(IReturnType baseType, IList<IReturnType> typeArguments) { if (baseType == null) throw new ArgumentNullException("baseType"); if (typeArguments == null) throw new ArgumentNullException("typeArguments"); this.typeArguments = typeArguments; this.baseType = baseType; } public override T CastToDecoratingReturnType<T>() { if (typeof(T) == typeof(ConstructedReturnType)) { return (T)(object)this; } else { return null; } } public override bool Equals(IReturnType rt) { return rt != null && rt.IsConstructedReturnType && this.DotNetName == rt.DotNetName; } public override int GetHashCode() { return this.DotNetName.GetHashCode(); } public override IReturnType GetDirectReturnType() { IReturnType newBaseType = baseType.GetDirectReturnType(); IReturnType[] newTypeArguments = new IReturnType[typeArguments.Count]; bool typeArgumentsChanged = false; for (int i = 0; i < typeArguments.Count; i++) { if (typeArguments[i] != null) newTypeArguments[i] = typeArguments[i].GetDirectReturnType(); if (typeArguments[i] != newTypeArguments[i]) typeArgumentsChanged = true; } if (baseType == newBaseType && !typeArgumentsChanged) return this; else return new ConstructedReturnType(newBaseType, newTypeArguments); } public override IReturnType BaseType { get { return baseType; } } public IReturnType UnboundType { get { return baseType; } } /// <summary> /// Gets if <paramref name="t"/> is/contains a generic return type referring to a class type parameter. /// </summary> bool CheckReturnType(IReturnType t) { if (t == null) { return false; } if (t.IsGenericReturnType) { return t.CastToGenericReturnType().TypeParameter.Method == null; } else if (t.IsArrayReturnType) { return CheckReturnType(t.CastToArrayReturnType().ArrayElementType); } else if (t.IsConstructedReturnType) { foreach (IReturnType para in t.CastToConstructedReturnType().TypeArguments) { if (CheckReturnType(para)) return true; } return false; } else { return false; } } bool CheckParameters(IList<IParameter> l) { foreach (IParameter p in l) { if (CheckReturnType(p.ReturnType)) return true; } return false; } public override string DotNetName { get { string baseName = baseType.DotNetName; int pos = baseName.LastIndexOf('`'); StringBuilder b; if (pos < 0) b = new StringBuilder(baseName); else b = new StringBuilder(baseName, 0, pos, pos + 20); b.Append('{'); for (int i = 0; i < typeArguments.Count; ++i) { if (i > 0) b.Append(','); if (typeArguments[i] != null) { b.Append(typeArguments[i].DotNetName); } } b.Append('}'); return b.ToString(); } } public static IReturnType TranslateType(IReturnType input, IList<IReturnType> typeParameters, bool convertForMethod) { if (input == null || typeParameters == null || typeParameters.Count == 0) { return input; // nothing to do when there are no type parameters specified } if (input.IsGenericReturnType) { GenericReturnType rt = input.CastToGenericReturnType(); if (convertForMethod ? (rt.TypeParameter.Method != null) : (rt.TypeParameter.Method == null)) { if (rt.TypeParameter.Index < typeParameters.Count) { IReturnType newType = typeParameters[rt.TypeParameter.Index]; if (newType != null) { return newType; } } } } else if (input.IsArrayReturnType) { ArrayReturnType arInput = input.CastToArrayReturnType(); IReturnType e = arInput.ArrayElementType; IReturnType t = TranslateType(e, typeParameters, convertForMethod); if (e != t && t != null) return new ArrayReturnType(arInput.ProjectContent, t, arInput.ArrayDimensions); } else if (input.IsConstructedReturnType) { ConstructedReturnType cinput = input.CastToConstructedReturnType(); List<IReturnType> para = new List<IReturnType>(cinput.TypeArguments.Count); foreach (IReturnType argument in cinput.TypeArguments) { para.Add(TranslateType(argument, typeParameters, convertForMethod)); } return new ConstructedReturnType(cinput.UnboundType, para); } return input; } IReturnType TranslateType(IReturnType input) { return TranslateType(input, typeArguments, false); } public override List<IMethod> GetMethods() { List<IMethod> l = baseType.GetMethods(); for (int i = 0; i < l.Count; ++i) { if (CheckReturnType(l[i].ReturnType) || CheckParameters(l[i].Parameters)) { l[i] = (IMethod)l[i].CreateSpecializedMember(); if (l[i].DeclaringType == baseType.GetUnderlyingClass()) { l[i].DeclaringTypeReference = this; } l[i].ReturnType = TranslateType(l[i].ReturnType); for (int j = 0; j < l[i].Parameters.Count; ++j) { l[i].Parameters[j].ReturnType = TranslateType(l[i].Parameters[j].ReturnType); } } } return l; } public override List<IProperty> GetProperties() { List<IProperty> l = baseType.GetProperties(); for (int i = 0; i < l.Count; ++i) { if (CheckReturnType(l[i].ReturnType) || CheckParameters(l[i].Parameters)) { l[i] = (IProperty)l[i].CreateSpecializedMember(); if (l[i].DeclaringType == baseType.GetUnderlyingClass()) { l[i].DeclaringTypeReference = this; } l[i].ReturnType = TranslateType(l[i].ReturnType); for (int j = 0; j < l[i].Parameters.Count; ++j) { l[i].Parameters[j].ReturnType = TranslateType(l[i].Parameters[j].ReturnType); } } } return l; } public override List<IField> GetFields() { List<IField> l = baseType.GetFields(); for (int i = 0; i < l.Count; ++i) { if (CheckReturnType(l[i].ReturnType)) { l[i] = (IField)l[i].CreateSpecializedMember(); if (l[i].DeclaringType == baseType.GetUnderlyingClass()) { l[i].DeclaringTypeReference = this; } l[i].ReturnType = TranslateType(l[i].ReturnType); } } return l; } public override List<IEvent> GetEvents() { List<IEvent> l = baseType.GetEvents(); for (int i = 0; i < l.Count; ++i) { if (CheckReturnType(l[i].ReturnType)) { l[i] = (IEvent)l[i].CreateSpecializedMember(); if (l[i].DeclaringType == baseType.GetUnderlyingClass()) { l[i].DeclaringTypeReference = this; } l[i].ReturnType = TranslateType(l[i].ReturnType); } } return l; } public override string ToString() { string r = "[ConstructedReturnType: "; r += baseType; r += "<"; for (int i = 0; i < typeArguments.Count; i++) { if (i > 0) r += ","; if (typeArguments[i] != null) { r += typeArguments[i]; } } return r + ">]"; } } }
//--------------------------------------------------------------------------- // // <copyright file="AssemblyHelper.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: services for code that potentially loads uncommon assemblies. // //--------------------------------------------------------------------------- /* Most of the WPF codebase uses types from WPF's own assemblies or from certain standard .Net assemblies (System, mscorlib, etc.). However, some code uses types from other assemblies (System.Xml, System.Data, etc.) - we'll refer to these as "uncommon" assemblies. We don't want WPF to load an uncommon assembly unless the app itself needs to. The AssemblyHelper class helps to solve this problem by keeping track of which uncommon assemblies have been loaded. Any code that uses an uncommon assembly should be isolated in a separate "extension" assembly, and calls to that method should be routed through the corresponding extension helper. The helper classes check whether the uncommon assembly is loaded before loading the extension assembly. */ using System; using System.IO; // FileNotFoundException using System.Reflection; // Assembly using System.Runtime.Remoting; // ObjectHandle using System.Security; // [SecurityCritical] using System.Security.Permissions; // [ReflectionPermission] using MS.Internal.WindowsBase; // [FriendAccessAllowed] // BuildInfo namespace MS.Internal { [FriendAccessAllowed] internal enum UncommonAssembly { // Each enum name must match the assembly name, with dots replaced by underscores System_Drawing, System_Xml, System_Xml_Linq, System_Data, System_Core, } [FriendAccessAllowed] internal static class AssemblyHelper { #region Constructors /// <SecurityNote> /// Critical: accesses AppDomain.AssemblyLoad event /// TreatAsSafe: the event is not exposed - merely updates internal state. /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] static AssemblyHelper() { // create the records for each uncommon assembly string[] names = Enum.GetNames(typeof(UncommonAssembly)); int n = names.Length; _records = new AssemblyRecord[n]; for (int i=0; i<n; ++i) { _records[i].Name = names[i].Replace('_','.') + ","; // comma delimits simple name within Assembly.FullName } // register for AssemblyLoad event AppDomain domain = AppDomain.CurrentDomain; domain.AssemblyLoad += OnAssemblyLoad; // handle the assemblies that are already loaded Assembly[] assemblies = domain.GetAssemblies(); for (int i=assemblies.Length-1; i>=0; --i) { OnLoaded(assemblies[i]); } } #endregion Constructors #region Internal Methods /// <SecurityNote> /// Critical: accesses critical field _records /// TreatAsSafe: it's OK to read the IsLoaded bit /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] [FriendAccessAllowed] internal static bool IsLoaded(UncommonAssembly assemblyEnum) { // this method is typically called by WPF code on a UI thread. // Although assemblies can load on any thread, there's no need to lock. // If the object of interest came from the given assembly, the // AssemblyLoad event has already been raised and the bit has already // been set before the caller calls IsLoaded. return _records[(int)assemblyEnum].IsLoaded; } #endregion Internal Methods #region System.Drawing static SystemDrawingExtensionMethods _systemDrawingExtensionMethods; // load the extension class for System.Drawing internal static SystemDrawingExtensionMethods ExtensionsForSystemDrawing(bool force=false) { if (_systemDrawingExtensionMethods == null && (force || IsLoaded(UncommonAssembly.System_Drawing))) { _systemDrawingExtensionMethods = (SystemDrawingExtensionMethods)LoadExtensionFor("SystemDrawing"); } return _systemDrawingExtensionMethods; } #endregion System.Drawing #region System.Xml static SystemXmlExtensionMethods _systemXmlExtensionMethods; // load the extension class for System.Xml internal static SystemXmlExtensionMethods ExtensionsForSystemXml(bool force=false) { if (_systemXmlExtensionMethods == null && (force || IsLoaded(UncommonAssembly.System_Xml))) { _systemXmlExtensionMethods = (SystemXmlExtensionMethods)LoadExtensionFor("SystemXml"); } return _systemXmlExtensionMethods; } #endregion System.Xml #region System.Xml.Linq static SystemXmlLinqExtensionMethods _systemXmlLinqExtensionMethods; // load the extension class for System.XmlLinq internal static SystemXmlLinqExtensionMethods ExtensionsForSystemXmlLinq(bool force=false) { if (_systemXmlLinqExtensionMethods == null && (force || IsLoaded(UncommonAssembly.System_Xml_Linq))) { _systemXmlLinqExtensionMethods = (SystemXmlLinqExtensionMethods)LoadExtensionFor("SystemXmlLinq"); } return _systemXmlLinqExtensionMethods; } #endregion System.Xml.Linq #region System.Data static SystemDataExtensionMethods _systemDataExtensionMethods; // load the extension class for System.Data internal static SystemDataExtensionMethods ExtensionsForSystemData(bool force=false) { if (_systemDataExtensionMethods == null && (force || IsLoaded(UncommonAssembly.System_Data))) { _systemDataExtensionMethods = (SystemDataExtensionMethods)LoadExtensionFor("SystemData"); } return _systemDataExtensionMethods; } #endregion System.Data #region System.Core static SystemCoreExtensionMethods _systemCoreExtensionMethods; // load the extension class for System.Core internal static SystemCoreExtensionMethods ExtensionsForSystemCore(bool force=false) { if (_systemCoreExtensionMethods == null && (force || IsLoaded(UncommonAssembly.System_Core))) { _systemCoreExtensionMethods = (SystemCoreExtensionMethods)LoadExtensionFor("SystemCore"); } return _systemCoreExtensionMethods; } #endregion System.Core #region Private Methods // Get the extension class for the given assembly /// <SecurityNote> /// Critical: Asserts RestrictedMemberAccess permission /// TreatAsSafe: Only used internally to load our own types /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] [ReflectionPermission(SecurityAction.Assert, RestrictedMemberAccess=true)] private static object LoadExtensionFor(string name) { // The docs claim that Activator.CreateInstance will create an instance // of an internal type provided that (a) the caller has ReflectionPermission // with the RestrictedMemberAccess flag, and (b) the grant set of the // calling assembly (WindowsBase) is a superset of the grant set of the // target assembly (one of our extension assemblies). Both those conditions // are satisfied, yet the call still results in a security exception when run // under partial trust (specifically, in the PT environment created by // the WPF test infrastructure). The only workaround I've found is to // assert full trust. PermissionSet ps = new PermissionSet(PermissionState.Unrestricted); ps.Assert(); // build the full display name of the extension assembly string assemblyName = Assembly.GetExecutingAssembly().FullName; string extensionAssemblyName = assemblyName.Replace("WindowsBase", "PresentationFramework-" + name) .Replace(BuildInfo.WCP_PUBLIC_KEY_TOKEN, BuildInfo.DEVDIV_PUBLIC_KEY_TOKEN); string extensionTypeName = "MS.Internal." + name + "Extension"; ObjectHandle handle; // create the instance of the extension class try { handle = Activator.CreateInstance(extensionAssemblyName, extensionTypeName); } catch (FileNotFoundException) { // if the extension assembly is missing, just return null handle = null; } return (handle != null) ? handle.Unwrap() : null; } /// <SecurityNote> /// Critical: This code potentially sets the IsLoaded bit for the given assembly. /// </SecurityNote> [SecurityCritical] private static void OnAssemblyLoad(object sender, AssemblyLoadEventArgs args) { OnLoaded(args.LoadedAssembly); } /// <SecurityNote> /// Critical: This code potentially sets the IsLoaded bit for the given assembly. /// </SecurityNote> [SecurityCritical] private static void OnLoaded(Assembly assembly) { // although this method can be called on an arbitrary thread, there's no // need to lock. The only change it makes is a monotonic one - changing // a bit in an AssemblyRecord from false to true. Even if two threads try // to do this simultaneously, the same outcome results. // ignore reflection-only assemblies - we care about running code from the assembly if (assembly.ReflectionOnly) return; // see if the assembly matches one of the uncommon assemblies for (int i=_records.Length-1; i>=0; --i) { if (!_records[i].IsLoaded && assembly.GlobalAssemblyCache && assembly.FullName.StartsWith(_records[i].Name, StringComparison.OrdinalIgnoreCase)) { _records[i].IsLoaded = true; } } } #endregion Private Methods #region Private Data private struct AssemblyRecord { public string Name { get; set; } public bool IsLoaded { get; set; } } /// <SecurityNote> /// Critical: The IsLoaded status could be used in security-critical /// situations. Make sure the IsLoaded bit is only set by authorized /// code, namely OnLoaded. /// </SecurityNote> [SecurityCritical] private static AssemblyRecord[] _records; #endregion Private Data } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Serialization; namespace SerializationTestTypes { [DataContract(IsReference = true)] public class BaseWithIsRefTrue { [DataMember] public SimpleDC Data; public BaseWithIsRefTrue() { } public BaseWithIsRefTrue(bool init) { Data = new SimpleDC(true); } } [DataContract] public class DerivedNoIsRef : BaseWithIsRefTrue { [DataMember] public SimpleDC RefData; public DerivedNoIsRef() { } public DerivedNoIsRef(bool init) : base(init) { RefData = Data; } } [DataContract] public class DerivedNoIsRef2 : DerivedNoIsRef { [DataMember] public SimpleDC RefData2; public DerivedNoIsRef2() { } public DerivedNoIsRef2(bool init) : base(init) { RefData2 = RefData; } } [DataContract] public class DerivedNoIsRef3 : DerivedNoIsRef2 { [DataMember] public SimpleDC RefData3; public DerivedNoIsRef3() { } public DerivedNoIsRef3(bool init) : base(init) { RefData3 = RefData2; } } [DataContract] public class DerivedNoIsRef4 : DerivedNoIsRef3 { [DataMember] public SimpleDC RefData4; public DerivedNoIsRef4() { } public DerivedNoIsRef4(bool init) : base(init) { RefData4 = RefData3; } } [DataContract] public class DerivedNoIsRef5 : DerivedNoIsRef4 { [DataMember] public SimpleDC RefData5; public DerivedNoIsRef5() { } public DerivedNoIsRef5(bool init) : base(init) { RefData5 = RefData4; } } [DataContract(IsReference = true)] public class DerivedNoIsRefWithIsRefTrue6 : DerivedNoIsRef5 { [DataMember] public SimpleDC RefData6; public DerivedNoIsRefWithIsRefTrue6() { } public DerivedNoIsRefWithIsRefTrue6(bool init) : base(init) { RefData6 = RefData5; } } [DataContract] public class DerivedWithIsRefFalse : BaseWithIsRefTrue { [DataMember] public SimpleDC RefData; public DerivedWithIsRefFalse() { } public DerivedWithIsRefFalse(bool init) : base(init) { RefData = Data; } } [DataContract] public class DerivedWithIsRefFalse2 : DerivedWithIsRefFalse { [DataMember] public SimpleDC RefData2; public DerivedWithIsRefFalse2() { } public DerivedWithIsRefFalse2(bool init) : base(init) { RefData2 = RefData; } } [DataContract] public class DerivedWithIsRefFalse3 : DerivedWithIsRefFalse2 { [DataMember] public SimpleDC RefData3; public DerivedWithIsRefFalse3() { } public DerivedWithIsRefFalse3(bool init) : base(init) { RefData3 = RefData2; } } [DataContract] public class DerivedWithIsRefFalse4 : DerivedWithIsRefFalse3 { [DataMember] public SimpleDC RefData4; public DerivedWithIsRefFalse4() { } public DerivedWithIsRefFalse4(bool init) : base(init) { RefData4 = RefData3; } } [DataContract] public class DerivedWithIsRefFalse5 : DerivedWithIsRefFalse4 { [DataMember] public SimpleDC RefData5; public DerivedWithIsRefFalse5() { } public DerivedWithIsRefFalse5(bool init) : base(init) { RefData5 = RefData4; } } [DataContract(IsReference = true)] public class DerivedWithIsRefTrue6 : DerivedWithIsRefFalse5 { [DataMember] public SimpleDC RefData6; public DerivedWithIsRefTrue6() { } public DerivedWithIsRefTrue6(bool init) : base(init) { RefData6 = RefData5; } } [DataContract(IsReference = true)] public class DerivedWithIsRefTrueExplicit : BaseWithIsRefTrue { [DataMember] public SimpleDC RefData; public DerivedWithIsRefTrueExplicit() { } public DerivedWithIsRefTrueExplicit(bool init) : base(init) { RefData = Data; } } [DataContract(IsReference = true)] public class DerivedWithIsRefTrueExplicit2 : DerivedWithIsRefTrueExplicit { [DataMember] public SimpleDC RefData2; public DerivedWithIsRefTrueExplicit2() { } public DerivedWithIsRefTrueExplicit2(bool init) : base(init) { RefData2 = Data; } } [DataContract()] public class BaseNoIsRef { [DataMember] public SimpleDC Data; public BaseNoIsRef() { } public BaseNoIsRef(bool init) { Data = new SimpleDC(true); } } [DataContract(IsReference = true)] public class DerivedWithIsRefTrue : BaseNoIsRef { [DataMember] public SimpleDC RefData; public DerivedWithIsRefTrue() { } public DerivedWithIsRefTrue(bool init) : base(true) { RefData = Data; } } [DataContract] public class DerivedWithIsRefFalseExplicit : BaseNoIsRef { [DataMember] public SimpleDC RefData; public DerivedWithIsRefFalseExplicit() { } public DerivedWithIsRefFalseExplicit(bool init) : base(true) { RefData = Data; } } [DataContract(IsReference = true)] [KnownType(typeof(DerivedDC))] public class TestInheritence { private BaseDC _b; private DerivedDC _d; [DataMember] public BaseDC baseDC { get { return _b; } set { _b = value; } } [DataMember] public DerivedDC derivedDC { get { return _d; } set { _d = value; } } public TestInheritence() { } public TestInheritence(bool init) { derivedDC = new DerivedDC(true); baseDC = derivedDC; } } [DataContract] [KnownType(typeof(DerivedSerializable))] [KnownType(typeof(Derived2Serializable))] public class TestInheritence9 { [DataMember] public BaseSerializable baseDC; [DataMember] public DerivedSerializable derivedDC; [DataMember] public BaseDC base1; [DataMember] public Derived2Serializable derived2; public TestInheritence9() { } public TestInheritence9(bool init) { derivedDC = new DerivedSerializable(true); baseDC = derivedDC; base1 = new Derived2Serializable(true); derived2 = (Derived2Serializable)base1; } } [DataContract] [KnownType(typeof(DerivedSerializable))] [KnownType(typeof(Derived2Serializable))] [KnownType(typeof(Derived3Derived2Serializable))] public class TestInheritence91 { [DataMember] public BaseSerializable baseDC; [DataMember] public DerivedSerializable derivedDC; [DataMember] public BaseDC base1; [DataMember] public Derived2Serializable derived2; [DataMember] public Derived3Derived2Serializable derived3; public TestInheritence91() { } public TestInheritence91(bool init) { derivedDC = new DerivedSerializable(true); baseDC = derivedDC; base1 = new Derived2Serializable(true); derived3 = new Derived3Derived2Serializable(true); derived2 = derived3; } } [DataContract(IsReference = true)] [KnownType(typeof(DerivedDC))] public class TestInheritence5 { [DataMember] public BaseDC baseDC = null; [DataMember] public DerivedDC derivedDC = null; public TestInheritence5() { } public TestInheritence5(bool init) { baseDC = derivedDC; } } [DataContract] public class TestInheritence10 { public BaseSerializable baseDC = null; public DerivedSerializable derivedDC = null; public TestInheritence10() { } public TestInheritence10(bool init) { baseDC = derivedDC; } } [DataContract(IsReference = true)] [KnownType(typeof(DerivedDC))] public class TestInheritence2 { [DataMember] public BaseDC baseDC; [DataMember] public DerivedDC derivedDC; public TestInheritence2() { } public TestInheritence2(bool init) { derivedDC = new DerivedDC(true); baseDC = new BaseDC(true); baseDC.data = derivedDC.data; derivedDC.Data = "String1"; baseDC.Data = derivedDC.Data; baseDC.data = derivedDC.data1; derivedDC.Data1 = "String2"; baseDC.Data = derivedDC.Data1; baseDC.data = baseDC.data2; baseDC.Data2 = "String3"; baseDC.Data = baseDC.Data2; } } [DataContract] public class TestInheritence11 { [DataMember] public BaseSerializable baseDC; [DataMember] public DerivedSerializable derivedDC; public TestInheritence11() { } public TestInheritence11(bool init) { derivedDC = new DerivedSerializable(true); baseDC = new BaseSerializable(true); baseDC.data = derivedDC.data; derivedDC.Data = "String1"; baseDC.Data = derivedDC.Data; baseDC.data = derivedDC.data1; derivedDC.Data1 = "String2"; baseDC.Data = derivedDC.Data1; baseDC.data = baseDC.data2; baseDC.Data2 = "String3"; baseDC.Data = baseDC.Data2; } } [DataContract(IsReference = true)] [KnownType(typeof(DerivedDC))] public class TestInheritence3 { [DataMember] public BaseDC baseDC; [DataMember] public DerivedDC derivedDC; public TestInheritence3() { } public TestInheritence3(bool init) { derivedDC = new DerivedDC(true); baseDC = new BaseDC(true); derivedDC.data = baseDC.data; baseDC.Data = "String1"; derivedDC.Data = baseDC.Data; derivedDC.data = baseDC.data2; baseDC.Data2 = "String2"; baseDC.Data2 = baseDC.Data2; derivedDC.data = derivedDC.data1; derivedDC.Data1 = "String3"; derivedDC.Data = derivedDC.Data1; } } [DataContract] public class TestInheritence16 { [DataMember] public BaseSerializable baseDC; [DataMember] public DerivedSerializable derivedDC; public TestInheritence16() { } public TestInheritence16(bool init) { derivedDC = new DerivedSerializable(true); baseDC = new BaseSerializable(true); derivedDC.data = baseDC.data; baseDC.Data = "String1"; derivedDC.Data = baseDC.Data; derivedDC.data = baseDC.data2; baseDC.Data2 = "String2"; baseDC.Data2 = baseDC.Data2; derivedDC.data = derivedDC.data1; derivedDC.Data1 = "String3"; derivedDC.Data = derivedDC.Data1; } } [DataContract(IsReference = true)] [KnownType(typeof(DerivedDC))] public class TestInheritence4 { [DataMember] public BaseDC baseDC; [DataMember] public DerivedDC derivedDC; public TestInheritence4() { } public TestInheritence4(bool init) { derivedDC = new DerivedDC(true); baseDC = new BaseDC(true); derivedDC.Data = "String1"; ((BaseDC)derivedDC).Data = derivedDC.Data; ((BaseDC)derivedDC).data = derivedDC.data1; derivedDC.Data1 = "String2"; ((BaseDC)derivedDC).Data = derivedDC.Data1; ((BaseDC)derivedDC).data = ((BaseDC)derivedDC).data2; ((BaseDC)derivedDC).Data2 = "String3"; ((BaseDC)derivedDC).Data = ((BaseDC)derivedDC).Data2; } } [DataContract] public class TestInheritence12 { [DataMember] public BaseSerializable baseDC; [DataMember] public DerivedSerializable derivedDC; public TestInheritence12() { } public TestInheritence12(bool init) { derivedDC = new DerivedSerializable(true); baseDC = new BaseSerializable(true); derivedDC.Data = "String1"; ((BaseSerializable)derivedDC).Data = derivedDC.Data; ((BaseSerializable)derivedDC).data = derivedDC.data1; derivedDC.Data1 = "String2"; ((BaseSerializable)derivedDC).Data = derivedDC.Data1; ((BaseSerializable)derivedDC).data = ((BaseSerializable)derivedDC).data2; ((BaseSerializable)derivedDC).Data2 = "String3"; ((BaseSerializable)derivedDC).Data = ((BaseSerializable)derivedDC).Data2; } } [DataContract(IsReference = true)] [KnownType(typeof(DerivedDC))] [KnownType(typeof(Derived2DC))] public class TestInheritence6 { [DataMember] public BaseDC baseDC; [DataMember] public DerivedDC derivedDC; [DataMember] public Derived2DC derived2DC; public TestInheritence6() { } public TestInheritence6(bool init) { baseDC = new BaseDC(true); derivedDC = new DerivedDC(true); derived2DC = new Derived2DC(true); derived2DC.data = derivedDC.data; derivedDC.Data = "String1"; derived2DC.Data = derivedDC.Data; derived2DC.data = derivedDC.data3; derivedDC.Data3 = "String2"; derived2DC.Data = derivedDC.Data3; derived2DC.data4 = derivedDC.data1; derivedDC.Data1 = "String3"; derived2DC.Data4 = derivedDC.Data1; derived2DC.data1 = derived2DC.data2; derived2DC.Data2 = "String4"; derived2DC.Data1 = derived2DC.Data2; } } [DataContract(IsReference = true)] [KnownType(typeof(Derived2DC))] public class TestInheritence7 { [DataMember] public BaseDC baseDC; [DataMember] public Derived2DC derived2DC; public TestInheritence7() { } public TestInheritence7(bool init) { baseDC = new BaseDC(true); derived2DC = new Derived2DC(true); derived2DC.data = baseDC.data; baseDC.Data = "String1"; derived2DC.Data = baseDC.Data; derived2DC.data = baseDC.data2; baseDC.Data2 = "String2"; derived2DC.Data = baseDC.Data2; } } [DataContract] public class TestInheritence14 { [DataMember] public BaseSerializable baseDC; [DataMember] public Derived2Serializable derived2DC; public TestInheritence14() { } public TestInheritence14(bool init) { baseDC = new BaseSerializable(true); derived2DC = new Derived2Serializable(true); derived2DC.data = baseDC.data; baseDC.Data = "String1"; derived2DC.Data = baseDC.Data; derived2DC.data = baseDC.data2; baseDC.Data2 = "String2"; derived2DC.Data = baseDC.Data2; } } [DataContract(IsReference = true)] [KnownType(typeof(Derived2DC))] public class TestInheritence8 { [DataMember] public BaseDC baseDC; [DataMember] public Derived2DC derived2DC; public TestInheritence8() { } public TestInheritence8(bool init) { derived2DC = new Derived2DC(true); baseDC = new BaseDC(true); baseDC.data = derived2DC.data; derived2DC.Data = "String1"; baseDC.Data = derived2DC.Data; baseDC.data = derived2DC.data1; derived2DC.Data1 = "String2"; baseDC.Data = derived2DC.Data1; } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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 SharpDX.Win32; namespace SharpDX.WIC { /// <summary> /// BitmapEncoderOptions used for encoding. /// </summary> public class BitmapEncoderOptions : PropertyBag { /// <summary> /// Initializes a new instance of the <see cref="BitmapEncoderOptions"/> class. /// </summary> /// <param name="propertyBagPointer">The property bag pointer.</param> public BitmapEncoderOptions(IntPtr propertyBagPointer) : base(propertyBagPointer) { } /// <summary> /// Gets or sets the image quality. /// </summary> /// <value> /// The image quality. /// </value> /// <remarks> /// Range value: 0-1.0f /// Applicable Codecs: JPEG, HDPhoto /// </remarks> public float ImageQuality { get { return Get(ImageQualityKey); } set { Set(ImageQualityKey, value);} } private static readonly PropertyBagKey<float, float> ImageQualityKey = new PropertyBagKey<float, float>("ImageQuality"); /// <summary> /// Gets or sets the compression quality. /// </summary> /// <value> /// The compression quality. /// </value> /// <remarks> /// Range value: 0-1.0f /// Applicable Codecs: TIFF /// </remarks> public float CompressionQuality { get { return Get(CompressionQualityKey); } set { Set(CompressionQualityKey, value); } } private static readonly PropertyBagKey<float, float> CompressionQualityKey = new PropertyBagKey<float, float>("CompressionQuality"); /// <summary> /// Gets or sets a value indicating whether loss less compression is enabled. /// </summary> /// <value> /// <c>true</c> if [loss less]; otherwise, <c>false</c>. /// </value> /// <remarks> /// Range value: true-false /// Applicable Codecs: HDPhoto /// </remarks> public bool LossLess { get { return Get(LosslessKey); } set { Set(LosslessKey, value); } } private static readonly PropertyBagKey<bool, bool> LosslessKey = new PropertyBagKey<bool, bool>("Lossless"); /// <summary> /// Gets or sets the bitmap transform. /// </summary> /// <value> /// The bitmap transform. /// </value> /// <remarks> /// Range value: <see cref="BitmapTransformOptions"/> /// Applicable Codecs: JPEG /// </remarks> public BitmapTransformOptions BitmapTransform { get { return Get(BitmapTransformKey); } set { Set(BitmapTransformKey, value); } } private static readonly PropertyBagKey<BitmapTransformOptions, byte> BitmapTransformKey = new PropertyBagKey<BitmapTransformOptions, byte>("BitmapTransform"); /// <summary> /// Gets or sets a value indicating whether [interlace option]. /// </summary> /// <value> /// <c>true</c> if [interlace option]; otherwise, <c>false</c>. /// </value> /// <remarks> /// Range value: true-false /// Applicable Codecs: PNG /// </remarks> public bool InterlaceOption { get { return Get(InterlaceOptionKey); } set { Set(InterlaceOptionKey, value); } } private static readonly PropertyBagKey<bool, bool> InterlaceOptionKey = new PropertyBagKey<bool, bool>("InterlaceOption"); /// <summary> /// Gets or sets the filter option. /// </summary> /// <value> /// The filter option. /// </value> /// <remarks> /// Range value: <see cref="PngFilterOption"/> /// Applicable Codecs: PNG /// </remarks> public PngFilterOption FilterOption { get { return Get(FilterOptionKey); } set { Set(FilterOptionKey, value); } } private static readonly PropertyBagKey<PngFilterOption, byte> FilterOptionKey = new PropertyBagKey<PngFilterOption, byte>("FilterOption"); /// <summary> /// Gets or sets the TIFF compression method. /// </summary> /// <value> /// The TIFF compression method. /// </value> /// <remarks> /// Range value: <see cref="TiffCompressionOption"/> /// Applicable Codecs: TIFF /// </remarks> public TiffCompressionOption TiffCompressionMethod { get { return Get(TiffCompressionMethodKey); } set { Set(TiffCompressionMethodKey, value); } } private static readonly PropertyBagKey<TiffCompressionOption, bool> TiffCompressionMethodKey = new PropertyBagKey<TiffCompressionOption, bool>("TiffCompressionMethod"); /// <summary> /// Gets or sets the luminance. /// </summary> /// <value> /// The luminance. /// </value> /// <remarks> /// Range value: 64 Entries (DCT) /// Applicable Codecs: JPEG /// </remarks> public uint[] Luminance { get { return Get(LuminanceKey); } set { Set(LuminanceKey, value); } } private static readonly PropertyBagKey<uint[], uint[]> LuminanceKey = new PropertyBagKey<uint[], uint[]>("Luminance"); /// <summary> /// Gets or sets the chrominance. /// </summary> /// <value> /// The chrominance. /// </value> /// <remarks> /// Range value: 64 Entries (DCT) /// Applicable Codecs: JPEG /// </remarks> public uint[] Chrominance { get { return Get(ChrominanceKey); } set { Set(ChrominanceKey, value); } } private static readonly PropertyBagKey<uint[], uint[]> ChrominanceKey = new PropertyBagKey<uint[], uint[]>("Chrominance"); /// <summary> /// Gets or sets the JPEG Y Cr Cb subsampling. /// </summary> /// <value> /// The JPEG Y Cr Cb subsampling. /// </value> /// <remarks> /// Range value: <see cref="JpegYCrCbSubsamplingOption"/> /// Applicable Codecs: JPEG /// </remarks> public JpegYCrCbSubsamplingOption JpegYCrCbSubsampling { get { return Get(JpegYCrCbSubsamplingKey); } set { Set(JpegYCrCbSubsamplingKey, value); } } private static readonly PropertyBagKey<JpegYCrCbSubsamplingOption, byte> JpegYCrCbSubsamplingKey = new PropertyBagKey<JpegYCrCbSubsamplingOption, byte>("JpegYCrCbSubsampling"); /// <summary> /// Gets or sets a value indicating whether [suppress app0]. /// </summary> /// <value> /// <c>true</c> if [suppress app0]; otherwise, <c>false</c>. /// </value> /// <remarks> /// Range value: true-false /// Applicable Codecs: JPEG /// </remarks> public bool SuppressApp0 { get { return Get(SuppressApp0Key); } set { Set(SuppressApp0Key, value); } } private static readonly PropertyBagKey<bool, bool> SuppressApp0Key = new PropertyBagKey<bool, bool>("SuppressApp0"); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Text; using BLToolkit.Mapping; using Sybase.Data.AseClient; namespace BLToolkit.Data.DataProvider { using Sql.SqlProvider; public class SybaseDataProvider : DataProviderBase { public override IDbConnection CreateConnectionObject() { return new AseConnection(); } public override DbDataAdapter CreateDataAdapterObject() { return new AseDataAdapter(); } public override bool DeriveParameters(IDbCommand command) { AseCommandBuilder.DeriveParameters((AseCommand)command); return true; } public override object Convert(object value, ConvertType convertType) { switch (convertType) { case ConvertType.ExceptionToErrorNumber: if (value is AseException) { var ex = (AseException)value; foreach (AseError error in ex.Errors) if (error.IsError) return error.MessageNumber; foreach (AseError error in ex.Errors) if (error.MessageNumber != 0) return error.MessageNumber; return 0; } break; case ConvertType.ExceptionToErrorMessage: if (value is AseException) { try { var ex = (AseException)value; var sb = new StringBuilder(); foreach (AseError error in ex.Errors) if (error.IsError) sb.AppendFormat("{0} Ln: {1}{2}", error.Message.TrimEnd('\n', '\r'), error.LineNum, Environment.NewLine); foreach (AseError error in ex.Errors) if (!error.IsError) sb.AppendFormat("* {0}{1}", error.Message, Environment.NewLine); return sb.Length == 0 ? ex.Message : sb.ToString(); } catch { } } break; } return SqlProvider.Convert(value, convertType); } public override void AttachParameter(IDbCommand command, IDbDataParameter parameter) { if (parameter.Value is string && parameter.DbType == DbType.Guid) parameter.DbType = DbType.AnsiString; base.AttachParameter(command, parameter); var p = (AseParameter)parameter; if (p.AseDbType == AseDbType.Unsupported && p.Value is DBNull) parameter.DbType = DbType.AnsiString; } public override Type ConnectionType { get { return typeof(AseConnection); } } public override string Name { get { return DataProvider.ProviderName.Sybase; } } public override ISqlProvider CreateSqlProvider() { return new SybaseSqlProvider(); } public override bool InitParameter(IDbDataParameter parameter) { if (parameter.Value is Guid) { parameter.Value = parameter.Value.ToString(); parameter.DbType = DbType.StringFixedLength; parameter.Size = 36; return true; } return false; } public override void PrepareCommand(ref CommandType commandType, ref string commandText, ref IDbDataParameter[] commandParameters) { base.PrepareCommand(ref commandType, ref commandText, ref commandParameters); List<IDbDataParameter> list = null; if (commandParameters != null) for (var i = 0; i < commandParameters.Length; i++) { var p = commandParameters[i]; if (p.Value is Guid) { p.Value = p.Value.ToString(); p.DbType = DbType.StringFixedLength; p.Size = 36; } if (commandType == CommandType.Text) { if (commandText.IndexOf(p.ParameterName) < 0) { if (list == null) { list = new List<IDbDataParameter>(commandParameters.Length); for (var j = 0; j < i; j++) list.Add(commandParameters[j]); } } else { if (list != null) list.Add(p); } } } if (list != null) commandParameters = list.ToArray(); } public override DbType GetDbType(Type systemType) { if (systemType == typeof(byte[])) return DbType.Object; return base.GetDbType(systemType); } #region DataReaderEx public override IDataReader GetDataReader(MappingSchema schema, IDataReader dataReader) { return dataReader is AseDataReader? new DataReaderEx((AseDataReader)dataReader): base.GetDataReader(schema, dataReader); } class DataReaderEx : DataReaderBase<AseDataReader>, IDataReader { public DataReaderEx(AseDataReader rd): base(rd) { } public new object GetValue(int i) { var value = DataReader.GetValue(i); if (value is DateTime) { var dt = (DateTime)value; if (dt.Year == 1900 && dt.Month == 1 && dt.Day == 1) return new DateTime(1, 1, 1, dt.Hour, dt.Minute, dt.Second, dt.Millisecond); } return value; } public new DateTime GetDateTime(int i) { var dt = DataReader.GetDateTime(i); if (dt.Year == 1900 && dt.Month == 1 && dt.Day == 1) return new DateTime(1, 1, 1, dt.Hour, dt.Minute, dt.Second, dt.Millisecond); return dt; } } #endregion } }
namespace Gu.Wpf.PropertyGrid { using System; using System.Collections.Generic; using System.Threading; /// <summary>Optimized this a lot to avoid caching of results.</summary> internal static class FormatString { private static readonly ThreadLocal<SortedSet<int>> Indices = new ThreadLocal<SortedSet<int>>(() => new SortedSet<int>()); /// <summary>Checks if <paramref name="format"/> has argument placeholders like 'Value: {0}'</summary> /// <param name="format">A format string.</param> /// <returns>True if the string contains format placeholders.</returns> public static bool IsFormatString(string format) { if (IsValidFormat(format, out int count, out bool? _)) { return count != 0; } return false; } /// <summary>Check if <paramref name="format"/> is a valid format string for <paramref name="numberOfArguments"/></summary> /// <param name="format">The format string.</param> /// <param name="numberOfArguments">The number of format arguments.</param> /// <returns>True if <paramref name="format"/> is well formed and matches <paramref name="numberOfArguments"/></returns> public static bool IsValidFormatString(string format, int numberOfArguments) { if (string.IsNullOrEmpty(format)) { return numberOfArguments == 0; } if (numberOfArguments < 0) { throw new ArgumentException(nameof(numberOfArguments)); } if (IsValidFormat(format, out int indexCount, out bool? _)) { return indexCount == numberOfArguments; } return false; } /// <summary> /// Check a format string for errors and other properties. /// Does not throw nor allocate no need to cache the result as it is about as fast as a dictionary lookup for common strings. /// </summary> /// <param name="format">The format string to check</param> /// <param name="indexCount">The number of format indices or -1 if error</param> /// <param name="anyItemHasFormat">If any index has formatting i.e: {0:N}</param> /// <returns>True if <paramref name="format"/> is a valid format string</returns> internal static bool IsValidFormat(string format, out int indexCount, out bool? anyItemHasFormat) { if (string.IsNullOrEmpty(format)) { indexCount = 0; anyItemHasFormat = false; return true; } int pos = 0; anyItemHasFormat = false; var indices = Indices.Value; indices.Clear(); while (TrySkipTo(format, '{', '}', ref pos)) { if (format[pos] == '}') { if (TrySkipEscaped(format, '}', ref pos)) { continue; } indexCount = -1; return false; } if (TrySkipEscaped(format, '{', ref pos)) { continue; } if (!TryParseItemFormat(format, ref pos, out int index, out bool? itemHasFormat)) { indexCount = -1; anyItemHasFormat = null; return false; } anyItemHasFormat |= itemHasFormat; indices.Add(index); } if (indices.Count == 0) { indexCount = 0; return true; } if (indices.Min == 0 && indices.Max == indices.Count - 1) { indexCount = indices.Count; return true; } indexCount = -1; return false; } private static bool TrySkipEscaped(string text, char c, ref int pos) { if (pos < text.Length - 1 && text[pos] == c && text[pos + 1] == c) { pos += 2; return true; } return false; } private static bool TrySkipTo(string text, char c1, char c2, ref int pos) { while (pos < text.Length && text[pos] != c1 && text[pos] != c2) { pos++; } return pos < text.Length; } private static bool TrySkipTo(string text, char c, ref int pos) { while (pos < text.Length && text[pos] != c) { pos++; } return pos < text.Length; } private static bool TryParseItemFormat(string text, ref int pos, out int index, out bool? itemHasFormat) { if (text[pos] != '{') { index = -1; itemHasFormat = null; return false; } pos++; if (!TryParseUnsignedInt(text, ref pos, out index)) { itemHasFormat = null; return false; } if (!TryParseFormatSuffix(text, ref pos, out itemHasFormat) || !TrySkipTo(text, '}', ref pos)) { index = -1; itemHasFormat = null; return false; } pos++; return true; } // ReSharper disable once UnusedMember.Local private static bool TryParseItemFormat(string text, ref int pos, out int index, out string format) { if (text[pos] != '{') { index = -1; format = null; return false; } pos++; if (!TryParseUnsignedInt(text, ref pos, out index)) { format = null; return false; } TryParseFormatSuffix(text, ref pos, out format); if (!TrySkipTo(text, '}', ref pos)) { index = -1; format = null; return false; } pos++; return true; } private static bool TryParseFormatSuffix(string text, ref int pos, out bool? itemHasFormat) { if (pos >= text.Length) { itemHasFormat = null; return false; } if (text[pos] == '}') { itemHasFormat = false; return true; } if (text[pos] != ':') { itemHasFormat = null; return false; } if (pos < text.Length - 1 && text[pos + 1] == '}') { itemHasFormat = null; return false; } pos++; if (!TrySkipTo(text, '}', ref pos)) { itemHasFormat = null; return false; } itemHasFormat = true; return true; } private static bool TryParseFormatSuffix(string text, ref int pos, out string result) { if (text[pos] != ':') { result = null; return false; } if (pos < text.Length - 1 && text[pos + 1] == '}') { result = null; return false; } pos++; var start = pos; if (!TrySkipTo(text, '}', ref pos)) { result = null; return false; } result = text.Slice(start, pos - 1); return true; } private static bool TryParseUnsignedInt(string text, ref int pos, out int result) { result = -1; while (pos < text.Length) { var i = text[pos] - '0'; if (i < 0 || i > 9) { return result != -1; } if (result == -1) { result = i; } else { result *= 10; result += i; } pos++; } return result != -1; } private static string Slice(this string text, int start, int end) { return text.Substring(start, end - start + 1); } } }
#region Foreign-License /* Copyright (c) 1997 Cornell University. Copyright (c) 1997 Sun Microsystems, Inc. Copyright (c) 1998-1999 by Scriptics Corporation. Copyright (c) 2000 Christian Krone. Copyright (c) 2012 Sky Morey See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #endregion using System; namespace Tcl.Lang { /* * This class implements the built-in "lsearch" command in Tcl. */ class LsearchCmd : ICommand { private static readonly string[] options = new string[] { "-ascii", "-decreasing", "-dictionary", "-exact", "-increasing", "-integer", "-glob", "-real", "-regexp", "-sorted" }; internal const int LSEARCH_ASCII = 0; internal const int LSEARCH_DECREASING = 1; internal const int LSEARCH_DICTIONARY = 2; internal const int LSEARCH_EXACT = 3; internal const int LSEARCH_INCREASING = 4; internal const int LSEARCH_INTEGER = 5; internal const int LSEARCH_GLOB = 6; internal const int LSEARCH_REAL = 7; internal const int LSEARCH_REGEXP = 8; internal const int LSEARCH_SORTED = 9; internal const int ASCII = 0; internal const int DICTIONARY = 1; internal const int INTEGER = 2; internal const int REAL = 3; internal const int EXACT = 0; internal const int GLOB = 1; internal const int REGEXP = 2; internal const int SORTED = 3; /* *----------------------------------------------------------------------------- * * cmdProc -- * * This procedure is invoked to process the "lsearch" Tcl command. * See the user documentation for details on what it does. * * Results: * None. * * Side effects: * See the user documentation. * *----------------------------------------------------------------------------- */ public TCL.CompletionCode CmdProc(Interp interp, TclObject[] objv) { int mode = GLOB; int dataType = ASCII; bool isIncreasing = true; TclObject pattern; TclObject list; if (objv.Length < 3) { throw new TclNumArgsException(interp, 1, objv, "?options? list pattern"); } for (int i = 1; i < objv.Length - 2; i++) { switch (TclIndex.Get(interp, objv[i], options, "option", 0)) { case LSEARCH_ASCII: dataType = ASCII; break; case LSEARCH_DECREASING: isIncreasing = false; break; case LSEARCH_DICTIONARY: dataType = DICTIONARY; break; case LSEARCH_EXACT: mode = EXACT; break; case LSEARCH_INCREASING: isIncreasing = true; break; case LSEARCH_INTEGER: dataType = INTEGER; break; case LSEARCH_GLOB: mode = GLOB; break; case LSEARCH_REAL: dataType = REAL; break; case LSEARCH_REGEXP: mode = REGEXP; break; case LSEARCH_SORTED: mode = SORTED; break; } } // Make sure the list argument is a list object and get its length and // a pointer to its array of element pointers. TclObject[] listv = TclList.getElements(interp, objv[objv.Length - 2]); TclObject patObj = objv[objv.Length - 1]; string patternBytes = null; int patInt = 0; double patDouble = 0.0; int length = 0; if (mode == EXACT || mode == SORTED) { switch (dataType) { case ASCII: case DICTIONARY: patternBytes = patObj.ToString(); length = patternBytes.Length; break; case INTEGER: patInt = TclInteger.Get(interp, patObj); break; case REAL: patDouble = TclDouble.Get(interp, patObj); break; } } else { patternBytes = patObj.ToString(); length = patternBytes.Length; } // Set default index value to -1, indicating failure; if we find the // item in the course of our search, index will be set to the correct // value. int index = -1; if (mode == SORTED) { // If the data is sorted, we can do a more intelligent search. int match = 0; int lower = -1; int upper = listv.Length; while (lower + 1 != upper) { int i = (lower + upper) / 2; switch (dataType) { case ASCII: { string bytes = listv[i].ToString(); match = patternBytes.CompareTo(bytes); break; } case DICTIONARY: { string bytes = listv[i].ToString(); match = DictionaryCompare(patternBytes, bytes); break; } case INTEGER: { int objInt = TclInteger.Get(interp, listv[i]); if (patInt == objInt) { match = 0; } else if (patInt < objInt) { match = -1; } else { match = 1; } break; } case REAL: { double objDouble = TclDouble.Get(interp, listv[i]); if (patDouble == objDouble) { match = 0; } else if (patDouble < objDouble) { match = -1; } else { match = 1; } break; } } if (match == 0) { // Normally, binary search is written to stop when it // finds a match. If there are duplicates of an element in // the list, our first match might not be the first occurance. // Consider: 0 0 0 1 1 1 2 2 2 // To maintain consistancy with standard lsearch semantics, // we must find the leftmost occurance of the pattern in the // list. Thus we don't just stop searching here. This // variation means that a search always makes log n // comparisons (normal binary search might "get lucky" with // an early comparison). index = i; upper = i; } else if (match > 0) { if (isIncreasing) { lower = i; } else { upper = i; } } else { if (isIncreasing) { upper = i; } else { lower = i; } } } } else { for (int i = 0; i < listv.Length; i++) { bool match = false; switch (mode) { case SORTED: case EXACT: { switch (dataType) { case ASCII: { string bytes = listv[i].ToString(); int elemLen = bytes.Length; if (length == elemLen) { match = bytes.Equals(patternBytes); } break; } case DICTIONARY: { string bytes = listv[i].ToString(); match = (DictionaryCompare(bytes, patternBytes) == 0); break; } case INTEGER: { int objInt = TclInteger.Get(interp, listv[i]); match = (objInt == patInt); break; } case REAL: { double objDouble = TclDouble.Get(interp, listv[i]); match = (objDouble == patDouble); break; } } break; } case GLOB: { match = Util.StringMatch(listv[i].ToString(), patternBytes); break; } case REGEXP: { match = Util.regExpMatch(interp, listv[i].ToString(), patObj); break; } } if (match) { index = i; break; } } } interp.SetResult(index); return TCL.CompletionCode.RETURN; } /* *---------------------------------------------------------------------- * * DictionaryCompare -> dictionaryCompare * * This function compares two strings as if they were being used in * an index or card catalog. The case of alphabetic characters is * ignored, except to break ties. Thus "B" comes before "b" but * after "a". Also, integers embedded in the strings compare in * numerical order. In other words, "x10y" comes after "x9y", not * before it as it would when using strcmp(). * * Results: * A negative result means that the first element comes before the * second, and a positive result means that the second element * should come first. A result of zero means the two elements * are equal and it doesn't matter which comes first. * * Side effects: * None. * *---------------------------------------------------------------------- */ private static int DictionaryCompare(string left, string right) // The strings to compare { char[] leftArr = left.ToCharArray(); char[] rightArr = right.ToCharArray(); char leftChar, rightChar, leftLower, rightLower; int lInd = 0; int rInd = 0; int diff; int secondaryDiff = 0; while (true) { if ((rInd < rightArr.Length) && (System.Char.IsDigit(rightArr[rInd])) && (lInd < leftArr.Length) && (System.Char.IsDigit(leftArr[lInd]))) { // There are decimal numbers embedded in the two // strings. Compare them as numbers, rather than // strings. If one number has more leading zeros than // the other, the number with more leading zeros sorts // later, but only as a secondary choice. int zeros = 0; while ((rightArr[rInd] == '0') && (rInd + 1 < rightArr.Length) && (System.Char.IsDigit(rightArr[rInd + 1]))) { rInd++; zeros--; } while ((leftArr[lInd] == '0') && (lInd + 1 < leftArr.Length) && (System.Char.IsDigit(leftArr[lInd + 1]))) { lInd++; zeros++; } if (secondaryDiff == 0) { secondaryDiff = zeros; } // The code below compares the numbers in the two // strings without ever converting them to integers. It // does this by first comparing the lengths of the // numbers and then comparing the digit values. diff = 0; while (true) { if ((diff == 0) && (lInd < leftArr.Length) && (rInd < rightArr.Length)) { diff = leftArr[lInd] - rightArr[rInd]; } rInd++; lInd++; if (rInd >= rightArr.Length || !System.Char.IsDigit(rightArr[rInd])) { if (lInd < leftArr.Length && System.Char.IsDigit(leftArr[lInd])) { return 1; } else { // The two numbers have the same length. See // if their values are different. if (diff != 0) { return diff; } break; } } else if (lInd >= leftArr.Length || !System.Char.IsDigit(leftArr[lInd])) { return -1; } } continue; } // Convert character to Unicode for comparison purposes. If either // string is at the terminating null, do a byte-wise comparison and // bail out immediately. if ((lInd < leftArr.Length) && (rInd < rightArr.Length)) { // Convert both chars to lower for the comparison, because // dictionary sorts are case insensitve. Covert to lower, not // upper, so chars between Z and a will sort before A (where most // other interesting punctuations occur) leftChar = leftArr[lInd++]; rightChar = rightArr[rInd++]; leftLower = System.Char.ToLower(leftChar); rightLower = System.Char.ToLower(rightChar); } else if (lInd < leftArr.Length) { diff = -rightArr[rInd]; break; } else if (rInd < rightArr.Length) { diff = leftArr[lInd]; break; } else { diff = 0; break; } diff = leftLower - rightLower; if (diff != 0) { return diff; } else if (secondaryDiff == 0) { if (System.Char.IsUpper(leftChar) && System.Char.IsLower(rightChar)) { secondaryDiff = -1; } else if (System.Char.IsUpper(rightChar) && System.Char.IsLower(leftChar)) { secondaryDiff = 1; } } } if (diff == 0) { diff = secondaryDiff; } return diff; } } // end LsearchCmd }
// 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.SafeHandles; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net.Sockets; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.IO.Pipes { public abstract partial class PipeStream : Stream { // The Windows implementation of PipeStream sets the stream's handle during // creation, and as such should always have a handle, but the Unix implementation // sometimes sets the handle not during creation but later during connection. // As such, validation during member access needs to verify a valid handle on // Windows, but can't assume a valid handle on Unix. internal const bool CheckOperationsRequiresSetHandle = false; internal static string GetPipePath(string serverName, string pipeName) { if (serverName != "." && serverName != Interop.Sys.GetHostName()) { // Cross-machine pipes are not supported. throw new PlatformNotSupportedException(SR.PlatformNotSupported_RemotePipes); } if (string.Equals(pipeName, AnonymousPipeName, StringComparison.OrdinalIgnoreCase)) { // Match Windows constraint throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved); } if (pipeName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { // Since pipes are stored as files in the file system, we don't support // pipe names that are actually paths or that otherwise have invalid // filename characters in them. throw new PlatformNotSupportedException(SR.PlatformNotSupproted_InvalidNameChars); } // Return the pipe path return Path.Combine(EnsurePipeDirectoryPath(), pipeName); } /// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary> /// <param name="safePipeHandle">The handle to validate.</param> internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { if (safePipeHandle.NamedPipeSocket == null) { Interop.Sys.FileStatus status; int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status)); if (result == 0) { if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO && (status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFSOCK) { throw new IOException(SR.IO_InvalidPipeHandle); } } } } /// <summary>Initializes the handle to be used asynchronously.</summary> /// <param name="handle">The handle.</param> [SecurityCritical] private void InitializeAsyncHandle(SafePipeHandle handle) { // nop } private void UninitializeAsyncHandle() { // nop } private unsafe int ReadCore(byte[] buffer, int offset, int count) { DebugAssertReadWriteArgs(buffer, offset, count, _handle); // For named pipes, receive on the socket. Socket socket = _handle.NamedPipeSocket; if (socket != null) { // For a blocking socket, we could simply use the same Read syscall as is done // for reading an anonymous pipe. However, for a non-blocking socket, Read could // end up returning EWOULDBLOCK rather than blocking waiting for data. Such a case // is already handled by Socket.Receive, so we use it here. try { return socket.Receive(buffer, offset, count, SocketFlags.None); } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } // For anonymous pipes, read from the file descriptor. fixed (byte* bufPtr = buffer) { int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr + offset, count)); Debug.Assert(result <= count); return result; } } private unsafe void WriteCore(byte[] buffer, int offset, int count) { DebugAssertReadWriteArgs(buffer, offset, count, _handle); // For named pipes, send to the socket. Socket socket = _handle.NamedPipeSocket; if (socket != null) { // For a blocking socket, we could simply use the same Write syscall as is done // for writing to anonymous pipe. However, for a non-blocking socket, Write could // end up returning EWOULDBLOCK rather than blocking waiting for space available. // Such a case is already handled by Socket.Send, so we use it here. try { while (count > 0) { int bytesWritten = socket.Send(buffer, offset, count, SocketFlags.None); Debug.Assert(bytesWritten <= count); count -= bytesWritten; offset += bytesWritten; } } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } // For anonymous pipes, write the file descriptor. fixed (byte* bufPtr = buffer) { while (count > 0) { int bytesWritten = CheckPipeCall(Interop.Sys.Write(_handle, bufPtr + offset, count)); Debug.Assert(bytesWritten <= count); count -= bytesWritten; offset += bytesWritten; } } } private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}"); Socket socket = InternalHandle.NamedPipeSocket; // If a cancelable token is used, we have a choice: we can either ignore it and use a true async operation // with Socket.ReceiveAsync, or we can use a polling loop on a worker thread to block for short intervals // and check for cancellation in between. We do the latter. if (cancellationToken.CanBeCanceled) { await Task.CompletedTask.ForceAsync(); // queue the remainder of the work to avoid blocking the caller int timeout = 10000; const int MaxTimeoutMicroseconds = 500000; while (true) { cancellationToken.ThrowIfCancellationRequested(); if (socket.Poll(timeout, SelectMode.SelectRead)) { return ReadCore(buffer, offset, count); } timeout = Math.Min(timeout * 2, MaxTimeoutMicroseconds); } } // The token wasn't cancelable, so we can simply use an async receive on the socket. try { return await socket.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false); } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}"); try { while (count > 0) { // cancellationToken is (mostly) ignored. We could institute a polling loop like we do for reads if // cancellationToken.CanBeCanceled, but that adds costs regardless of whether the operation will be canceled, and // most writes will complete immediately as they simply store data into the socket's buffer. The only time we end // up using it in a meaningful way is if a write completes partially, we'll check it on each individual write operation. cancellationToken.ThrowIfCancellationRequested(); int bytesWritten = await _handle.NamedPipeSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false); Debug.Assert(bytesWritten <= count); count -= bytesWritten; offset += bytesWritten; } } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } private IOException GetIOExceptionForSocketException(SocketException e) { if (e.SocketErrorCode == SocketError.Shutdown) // EPIPE { State = PipeState.Broken; } return new IOException(e.Message, e); } // Blocks until the other end of the pipe has read in all written buffer. [SecurityCritical] public void WaitForPipeDrain() { CheckWriteOperations(); if (!CanWrite) { throw Error.GetWriteNotSupported(); } // For named pipes on sockets, we could potentially partially implement this // via ioctl and TIOCOUTQ, which provides the number of unsent bytes. However, // that would require polling, and it wouldn't actually mean that the other // end has read all of the data, just that the data has left this end's buffer. throw new PlatformNotSupportedException(); } // Gets the transmission mode for the pipe. This is virtual so that subclassing types can // override this in cases where only one mode is legal (such as anonymous pipes) public virtual PipeTransmissionMode TransmissionMode { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } } // Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read // access. If that passes, call to GetNamedPipeInfo will succeed. public virtual int InBufferSize { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] get { CheckPipePropertyOperations(); if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } return GetPipeBufferSize(); } } // Gets the buffer size in the outbound direction for the pipe. This uses cached version // if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe. // However, returning cached is good fallback, especially if user specified a value in // the ctor. public virtual int OutBufferSize { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); if (!CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } return GetPipeBufferSize(); } } public virtual PipeTransmissionMode ReadMode { [SecurityCritical] get { CheckPipePropertyOperations(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] set { CheckPipePropertyOperations(); if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg); } if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based { throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode); } // nop, since it's already the only valid value } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private static string s_pipeDirectoryPath; /// <summary> /// We want to ensure that only one asynchronous operation is actually in flight /// at a time. The base Stream class ensures this by serializing execution via a /// semaphore. Since we don't delegate to the base stream for Read/WriteAsync due /// to having specialized support for cancellation, we do the same serialization here. /// </summary> private SemaphoreSlim _asyncActiveSemaphore; private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } private static string EnsurePipeDirectoryPath() { const string PipesFeatureName = "pipe"; // Ideally this would simply use PersistedFiles.GetTempFeatureDirectory(PipesFeatureName) and then // Directory.CreateDirectory to ensure it exists. But this assembly doesn't reference System.IO.FileSystem. // As such, we'd be calling GetTempFeatureDirectory, only to then need to parse it in order // to create each of the individual directories as part of the path. We instead access the named portions // of the path directly and do the building of the path and directory structure manually. // First ensure we know what the full path should be, e.g. /tmp/.dotnet/corefx/pipe/ string fullPath = s_pipeDirectoryPath; string tempPath = null; if (fullPath == null) { tempPath = Path.GetTempPath(); fullPath = Path.Combine(tempPath, PersistedFiles.TopLevelHiddenDirectory, PersistedFiles.SecondLevelDirectory, PipesFeatureName); s_pipeDirectoryPath = fullPath; } // Then create the directory if it doesn't already exist. If we get any error back from stat, // just proceed to build up the directory, failing in the CreateDirectory calls if there's some // problem. Similarly, it's possible stat succeeds but the path is a file rather than directory; we'll // call that success for now and let this fail later when the code tries to create a file in this "directory" // (we don't want to overwrite/delete whatever that unknown file may be, and this is similar to other cases // we can't control where the file system is manipulated concurrently with and separately from this code). Interop.Sys.FileStatus ignored; bool pathExists = Interop.Sys.Stat(fullPath, out ignored) == 0; if (!pathExists) { // We need to build up the directory manually. Ensure we have the temp directory in which // we'll create the structure, e.g. /tmp/ if (tempPath == null) { tempPath = Path.GetTempPath(); } Debug.Assert(Interop.Sys.Stat(tempPath, out ignored) == 0, "Path.GetTempPath() directory could not be accessed"); // Create /tmp/.dotnet/ if it doesn't exist. string partialPath = Path.Combine(tempPath, PersistedFiles.TopLevelHiddenDirectory); CreateDirectory(partialPath); // Create /tmp/.dotnet/corefx/ if it doesn't exist partialPath = Path.Combine(partialPath, PersistedFiles.SecondLevelDirectory); CreateDirectory(partialPath); // Create /tmp/.dotnet/corefx/pipe/ if it doesn't exist CreateDirectory(fullPath); } return fullPath; } private static void CreateDirectory(string directoryPath) { int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.Mask); // If successful created, we're done. if (result >= 0) return; // If the directory already exists, consider it a success. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EEXIST) return; // Otherwise, fail. throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true); } /// <summary>Creates an anonymous pipe.</summary> /// <param name="inheritability">The inheritability to try to use. This may not always be honored, depending on platform.</param> /// <param name="reader">The resulting reader end of the pipe.</param> /// <param name="writer">The resulting writer end of the pipe.</param> internal static unsafe void CreateAnonymousPipe( HandleInheritability inheritability, out SafePipeHandle reader, out SafePipeHandle writer) { // Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations reader = new SafePipeHandle(); writer = new SafePipeHandle(); // Create the OS pipe int* fds = stackalloc int[2]; CreateAnonymousPipe(inheritability, fds); // Store the file descriptors into our safe handles reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]); writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]); } internal int CheckPipeCall(int result) { if (result == -1) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EPIPE) State = PipeState.Broken; throw Interop.GetExceptionForIoErrno(errorInfo); } return result; } private int GetPipeBufferSize() { if (!Interop.Sys.Fcntl.CanGetSetPipeSz) { throw new PlatformNotSupportedException(); } // If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction). // If we don't, just return the buffer size that was passed to the constructor. return _handle != null ? CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) : _outBufferSize; } internal static unsafe void CreateAnonymousPipe(HandleInheritability inheritability, int* fdsptr) { var flags = (inheritability & HandleInheritability.Inheritable) == 0 ? Interop.Sys.PipeFlags.O_CLOEXEC : 0; Interop.CheckIo(Interop.Sys.Pipe(fdsptr, flags)); } internal static void ConfigureSocket( Socket s, SafePipeHandle pipeHandle, PipeDirection direction, int inBufferSize, int outBufferSize, HandleInheritability inheritability) { if (inBufferSize > 0) { s.ReceiveBufferSize = inBufferSize; } if (outBufferSize > 0) { s.SendBufferSize = outBufferSize; } if (inheritability != HandleInheritability.Inheritable) { Interop.Sys.Fcntl.SetCloseOnExec(pipeHandle); // ignore failures, best-effort attempt } switch (direction) { case PipeDirection.In: s.Shutdown(SocketShutdown.Send); break; case PipeDirection.Out: s.Shutdown(SocketShutdown.Receive); break; } } } }
using System.Collections.Generic; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; public static class CecilExtensions { public static void Replace(this Collection<Instruction> collection, Instruction instruction, ICollection<Instruction> instructions) { var newInstruction = instructions.First(); instruction.Operand = newInstruction.Operand; instruction.OpCode = newInstruction.OpCode; var indexOf = collection.IndexOf(instruction); foreach (var instruction1 in instructions.Skip(1)) { collection.Insert(indexOf+1, instruction1); indexOf++; } } public static void Append(this List<Instruction> collection, params Instruction[] instructions) { collection.AddRange(instructions); } public static string DisplayName(this MethodDefinition method) { method = GetActualMethod(method); var paramNames = string.Join(", ", method.Parameters.Select(x => x.ParameterType.DisplayName())); return string.Format("{0} {1}({2})", method.ReturnType.DisplayName(), method.Name, paramNames); } public static string DisplayName(this TypeReference typeReference) { var genericInstanceType = typeReference as GenericInstanceType; if (genericInstanceType != null && genericInstanceType.HasGenericArguments) { return typeReference.Name.Split('`').First() + "<" + string.Join(", ", genericInstanceType.GenericArguments.Select(c => c.DisplayName())) + ">"; } return typeReference.Name; } static MethodDefinition GetActualMethod(MethodDefinition method) { var isTypeCompilerGenerated = method.DeclaringType.IsCompilerGenerated(); if (isTypeCompilerGenerated) { var rootType = method.DeclaringType.GetNonCompilerGeneratedType(); if (rootType != null) { foreach (var parentClassMethod in rootType.Methods) { if (method.DeclaringType.Name.Contains("<" + parentClassMethod.Name + ">")) { return parentClassMethod; } if (method.Name.StartsWith("<" + parentClassMethod.Name + ">")) { return parentClassMethod; } } } } var isMethodCompilerGenerated = method.IsCompilerGenerated(); if (isMethodCompilerGenerated) { foreach (var parentClassMethod in method.DeclaringType.Methods) { if (method.Name.StartsWith("<" + parentClassMethod.Name + ">")) { return parentClassMethod; } } } return method; } public static TypeDefinition GetNonCompilerGeneratedType(this TypeDefinition typeDefinition) { while (typeDefinition.IsCompilerGenerated() && typeDefinition.DeclaringType != null) { typeDefinition = typeDefinition.DeclaringType; } return typeDefinition; } public static bool IsCompilerGenerated(this ICustomAttributeProvider value) { return value.CustomAttributes.Any(a => a.AttributeType.Name == "CompilerGeneratedAttribute"); } public static bool IsCompilerGenerated(this TypeDefinition typeDefinition) { return typeDefinition.CustomAttributes.Any(a => a.AttributeType.Name == "CompilerGeneratedAttribute") || (typeDefinition.IsNested && typeDefinition.DeclaringType.IsCompilerGenerated()); } public static void CheckForInvalidLogToUsages(this MethodDefinition methodDefinition) { foreach (var instruction in methodDefinition.Body.Instructions) { var methodReference = instruction.Operand as MethodReference; if (methodReference != null) { var declaringType = methodReference.DeclaringType; if (declaringType.Name != "LogTo") { continue; } if (declaringType.Namespace == null || !declaringType.Namespace.StartsWith("Anotar")) { continue; } //TODO: sequence point if (instruction.OpCode == OpCodes.Ldftn) { var message = string.Format("Inline delegate usages of 'LogTo' are not supported. '{0}'.", methodDefinition.FullName); throw new WeavingException(message); } } var typeReference = instruction.Operand as TypeReference; if (typeReference != null) { if (typeReference.Name != "LogTo") { continue; } if (typeReference.Namespace == null || !typeReference.Namespace.StartsWith("Anotar")) { continue; } //TODO: sequence point if (instruction.OpCode == OpCodes.Ldtoken) { var message = string.Format("'typeof' usages or passing `dynamic' params to 'LogTo' are not supported. '{0}'.", methodDefinition.FullName); throw new WeavingException(message); } } } } public static MethodDefinition GetStaticConstructor(this TypeDefinition type) { var staticConstructor = type.Methods.FirstOrDefault(x => x.IsConstructor && x.IsStatic); if (staticConstructor == null) { const MethodAttributes attributes = MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Private; staticConstructor = new MethodDefinition(".cctor", attributes, type.Module.TypeSystem.Void); staticConstructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); type.Methods.Add(staticConstructor); } staticConstructor.Body.InitLocals = true; return staticConstructor; } public static void InsertBefore(this ILProcessor processor, Instruction target, IEnumerable<Instruction> instructions) { foreach (var instruction in instructions) { processor.InsertBefore(target, instruction); } } public static bool IsBasicLogCall(this Instruction instruction) { var previous = instruction.Previous; if (previous.OpCode != OpCodes.Newarr || ((TypeReference) previous.Operand).FullName != "System.Object") { return false; } previous = previous.Previous; if (previous.OpCode != OpCodes.Ldc_I4) { return false; } previous = previous.Previous; if (previous.OpCode != OpCodes.Ldstr) { return false; } return true; } public static Instruction FindStringInstruction(this Instruction call) { if (IsBasicLogCall(call)) { return call.Previous.Previous.Previous; } var previous = call.Previous; if (previous.OpCode != OpCodes.Ldloc) { return null; } var variable = (VariableDefinition) previous.Operand; while (previous != null && (previous.OpCode != OpCodes.Stloc || previous.Operand != variable)) { previous = previous.Previous; } if (previous == null) { return null; } if (IsBasicLogCall(previous)) { return previous.Previous.Previous.Previous; } return null; } public static bool TryGetPreviousLineNumber(this Instruction instruction, out int lineNumber) { while (true) { var sequencePoint = instruction.SequencePoint; if (sequencePoint != null) { // not a hiddent line http://blogs.msdn.com/b/jmstall/archive/2005/06/19/feefee-sequencepoints.aspx if (sequencePoint.StartLine != 0xFeeFee) { lineNumber = sequencePoint.StartLine; return true; } } instruction = instruction.Previous; if (instruction == null) { lineNumber = 0; return false; } } } public static bool ContainsAttribute(this Collection<CustomAttribute> attributes, string attributeName) { var containsAttribute = attributes.FirstOrDefault(x => x.AttributeType.FullName == attributeName); if (containsAttribute != null) { attributes.Remove(containsAttribute); } return containsAttribute != null; } public static MethodDefinition FindMethod(this TypeDefinition typeDefinition, string method, params string[] paramTypes) { var firstOrDefault = typeDefinition.Methods .FirstOrDefault(x => !x.HasGenericParameters && x.Name == method && x.IsMatch(paramTypes)); if (firstOrDefault == null) { var parameterNames = string.Join(", ", paramTypes); throw new WeavingException(string.Format("Expected to find method '{0}({1})' on type '{2}'.", method, parameterNames, typeDefinition.FullName)); } return firstOrDefault; } public static MethodDefinition FindGenericMethod(this TypeDefinition typeDefinition, string method, params string[] paramTypes) { var firstOrDefault = typeDefinition.Methods .FirstOrDefault(x => x.HasGenericParameters && x.Name == method && x.IsMatch(paramTypes)); if (firstOrDefault == null) { var parameterNames = string.Join(", ", paramTypes); throw new WeavingException(string.Format("Expected to find method '{0}({1})' on type '{2}'.", method, parameterNames, typeDefinition.FullName)); } return firstOrDefault; } public static bool IsMatch(this MethodReference methodReference, params string[] paramTypes) { if (methodReference.Parameters.Count != paramTypes.Length) { return false; } for (var index = 0; index < methodReference.Parameters.Count; index++) { var parameterDefinition = methodReference.Parameters[index]; var paramType = paramTypes[index]; if (parameterDefinition.ParameterType.Name != paramType) { return false; } } return true; } public static FieldReference GetGeneric(this FieldDefinition definition) { if (definition.DeclaringType.HasGenericParameters) { var declaringType = new GenericInstanceType(definition.DeclaringType); foreach (var parameter in definition.DeclaringType.GenericParameters) { declaringType.GenericArguments.Add(parameter); } return new FieldReference(definition.Name, definition.FieldType, declaringType); } return definition; } public static TypeReference GetGeneric(this TypeDefinition definition) { if (definition.HasGenericParameters) { var genericInstanceType = new GenericInstanceType(definition); foreach (var parameter in definition.GenericParameters) { genericInstanceType.GenericArguments.Add(parameter); } return genericInstanceType; } return definition; } }
// Copyright 2020 The Tilt Brush Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using UnityEngine; using TMPro; namespace TiltBrush { [System.Serializable] public struct PopupMapKey { public GameObject m_PopUpPrefab; public SketchControlsScript.GlobalCommands m_Command; } public class BasePanel : MonoBehaviour { static private float GAZE_DISTANCE = 10 * App.METERS_TO_UNITS; static private float LARGE_DISTANCE = 9999.0f * App.METERS_TO_UNITS; // Types etc protected class TextSpring { public float m_CurrentAngle; public float m_DesiredAngle; public float m_Velocity; public void Update(float fK, float fDampen) { float fToDesired = m_DesiredAngle - m_CurrentAngle; fToDesired *= fK; float fDampenedVel = m_Velocity * fDampen; float fSpringForce = fToDesired - fDampenedVel; m_Velocity += fSpringForce; m_CurrentAngle += (m_Velocity * Time.deltaTime); } } protected enum DescriptionState { Open, Closing, Closed } protected enum PanelState { Unused, Unavailable, Available, } // These names are used in our player prefs, so they must be protected from obfuscation // Do not change the names of any of them, unless they've never been released. [Serializable] public enum PanelType { SketchSurface, Color, Brush, AudioReactor, AdminPanelMobile, ToolsBasicMobile, ToolsBasic, Experimental, ToolsAdvancedMobile, MemoryWarning, Labs, Sketchbook, SketchbookMobile, BrushMobile, AppSettings, Tutorials, Reference, Lights, GuideTools, Environment, Camera, Testing, Poly, BrushExperimental, ToolsAdvanced, AppSettingsMobile, AdminPanel, ExtraPanel, ExtraMobile, PolyMobile, LabsMobile, ReferenceMobile, CameraPath, BrushLab } private enum FixedTransitionState { Floating, FixedToFloating, FloatingToFixed, Fixed } // Inspector data, tunables [SerializeField] protected PanelType m_PanelType; [SerializeField] protected Collider m_Collider; [SerializeField] public GameObject m_Mesh; [SerializeField] protected Renderer m_Border; [SerializeField] protected Collider m_MeshCollider; [SerializeField] protected Vector3 m_ParticleBounds; [SerializeField] protected PopupMapKey [] m_PanelPopUpMap; [SerializeField] protected string m_PanelDescription; [SerializeField] protected GameObject m_PanelDescriptionPrefab; [SerializeField] protected Vector3 m_PanelDescriptionOffset; [SerializeField] protected Color m_PanelDescriptionColor; [SerializeField] protected GameObject m_PanelFlairPrefab; [SerializeField] protected Vector3 m_PanelFlairOffset; [SerializeField] protected float m_DescriptionSpringK = 4.0f; [SerializeField] protected float m_DescriptionSpringDampen = 0.2f; [SerializeField] protected float m_DescriptionClosedAngle = -90.0f; [SerializeField] protected float m_DescriptionOpenAngle = 0.0f; [SerializeField] protected float m_DescriptionAlphaDistance = 90.0f; [SerializeField] protected GameObject[] m_Decor; [SerializeField] protected float m_GazeHighlightScaleMultiplier = 1.2f; [SerializeField] private float m_BorderMeshWidth = 0.02f; [SerializeField] private float m_BorderMeshAdvWidth = 0.01f; [SerializeField] public float m_PanelSensitivity = 0.1f; [SerializeField] protected bool m_ClampToBounds = false; [SerializeField] protected Vector3 m_ReticleBounds; [SerializeField] public float m_BorderSphereHighlightRadius; [SerializeField] protected Vector2 m_PositioningSpheresBounds; [SerializeField] protected float m_PositioningSphereRadius = 0.4f; [SerializeField] public bool m_UseGazeRotation = false; [SerializeField] public float m_MaxGazeRotation = 20.0f; [SerializeField] protected float m_GazeActivateSpeed = 8.0f; [SerializeField] public Vector3 m_InitialSpawnPos; [SerializeField] public Vector3 m_InitialSpawnRotEulers; [SerializeField] public float m_WandAttachAngle; [SerializeField] public float m_WandAttachYOffset; [SerializeField] public float m_WandAttachHalfHeight; [SerializeField] private bool m_BeginFixed; [SerializeField] private bool m_CanBeFixedToWand = true; [SerializeField] private bool m_CanBeDetachedFromWand = true; [SerializeField] private float m_PopUpGazeDuration = .2f; [SerializeField] protected MeshRenderer[] m_PromoBorders; protected const float m_SwipeThreshold = 0.4f; protected Material m_BorderMaterial; // Public, mutable data [NonSerialized] public float m_SweetSpotDistance = 1.0f; [NonSerialized] public bool m_Fixed; [NonSerialized] public bool m_WandPrimedForAttach; [NonSerialized] public float m_WandAttachRadiusAdjust; [NonSerialized] public float m_WandAttachYOffset_Target; // This is used to store the Y offset of a fixed panel at the point where the user begins // interacting with a panelWidget. Storing this value allows modifications to the panes to be // undone. When the user ends interaction, _Stable is updated to be the _Target. [NonSerialized] public float m_WandAttachYOffset_Stable; // Internal data protected PopUpWindow m_ActivePopUp; protected SketchControlsScript.GlobalCommands m_DelayedCommand; protected int m_DelayedCommandParam; protected int m_DelayedCommandParam2; protected GameObject m_PanelDescriptionObject; protected Renderer m_PanelDescriptionRenderer; protected TextMeshPro m_PanelDescriptionTextMeshPro; protected Vector3 m_BaseScale; protected float m_AdjustedScale; protected TextSpring m_PanelDescriptionTextSpring; protected TextSpring m_PanelFlairSpring; protected PanelFlair m_PanelFlair; protected Vector3 m_ReticleOffset; protected Vector3 m_Bounds; protected Vector3 m_WorkingReticleBounds; protected DescriptionState m_PanelDescriptionState; protected DescriptionState m_PanelFlairState; protected float m_CloseAngleThreshold; protected PanelState m_CurrentState; protected PanelState m_DesiredState; protected bool m_GazeActive; protected bool m_GazeWasActive; protected bool m_GazeDescriptionsActive; protected bool m_InputValid; protected bool m_EatInput; protected Ray m_ReticleSelectionRay; protected float m_PositioningPercent; protected float m_MaxGazeOffsetDistance; protected Vector3 m_GazeRotationAxis; protected float m_GazeRotationAngle; protected Quaternion m_GazeRotationAmount; protected float m_GazeActivePercent; protected UIComponentManager m_UIComponentManager; protected NonScaleChild m_NonScaleChild; // potentially null // Private private List<Renderer> m_DecorRenderers; private List<TextMeshPro> m_DecorTextMeshes; private float m_ScaledPositioningSphereRadius; private float m_PositioningExtent; private Vector3[] m_PositioningSpheres; private Vector3[] m_PositioningSpheresTransformed; private Vector3 m_PositioningHome; private float m_PositioningK = 0.5f; private float m_PositioningDampen = 0.1f; private float m_DepenetrationScalar = 200.0f; private Vector3 m_PositioningVelocity; private Vector3 m_GazeHitPositionCurrent; private Vector3 m_GazeHitPositionDesired; private float m_GazeHitPositionSpeed = 10.0f; protected Vector2 m_SwipeRecentMotion = Vector2.zero; private FixedTransitionState m_TransitionState; private TrTransform m_WandTransitionTarget; private static float m_WandTransitionDuration = .25f; private float m_WandTransitionPercent; // 0 = on wand, 1 = at target private float m_WandAttachAdjustSpeed = 16.0f; private float m_WandAttachYOffset_Initial; private float m_WandAttachAngle_Initial; private PanelWidget m_WidgetSibling; private GameObject m_TempPopUpCollider; private float m_PopUpGazeTimer; private bool m_AdvancedModePanel; private bool m_CurrentlyVisibleInAdvancedMode; // TODO: The following are just to track down an elusive NRE. Delete when we've figured // it out. private bool m_PanelInitializationStarted; private bool m_PanelInitializationFinished; private float m_PanelDescriptionCounter; // Accessors/properties public Vector3 GetBounds() { return m_Bounds; } public float GetPositioningExtent() { return m_PositioningExtent; } public bool IsAvailable() { return m_CurrentState != PanelState.Unavailable; } public bool IsActive() { return m_GazeActive; } public bool BeginFixed { get { return m_BeginFixed; } } public void ClearBeginFixed() { m_BeginFixed = false; } public bool CanBeDetached { get { return m_CanBeDetachedFromWand; } } public bool IsInInitialPosition() { return m_WandAttachYOffset == m_WandAttachYOffset_Initial && m_WandAttachAngle == m_WandAttachAngle_Initial; } public PanelWidget WidgetSibling { get { return m_WidgetSibling; } } public bool AdvancedModePanel { get { return m_AdvancedModePanel; } } public bool CurrentlyVisibleInAdvancedMode { get { return m_CurrentlyVisibleInAdvancedMode; } } public Vector3 ParticleBounds { get { return m_ParticleBounds; } } public PopUpWindow PanelPopUp { get { return m_ActivePopUp; } } public Color GetGazeColorFromActiveGazePercent() { PanelManager pm = PanelManager.m_Instance; return Color.Lerp(pm.PanelHighlightInactiveColor, pm.PanelHighlightActiveColor, m_GazeActivePercent); } public PanelType Type { get { return m_PanelType; } } public virtual bool ShouldRegister { get { return true; } } public void InitAdvancedFlag(bool advanced) { m_AdvancedModePanel = advanced; m_CurrentlyVisibleInAdvancedMode = m_BeginFixed; } public float PopUpOffset { get { return m_ActivePopUp ? m_ActivePopUp.GetPopUpForwardOffset() : 0; } } virtual protected void CalculateBounds() { Vector3 vCurrentScale = transform.localScale; m_Bounds = m_ReticleBounds; m_Bounds.x *= vCurrentScale.x * 0.5f; m_Bounds.y *= vCurrentScale.y * 0.5f; m_Bounds.z = 0.0f; if (m_ActivePopUp == null) { m_WorkingReticleBounds = m_Bounds; } else { Vector3 vPopUpCurrentScale = m_ActivePopUp.transform.localScale; m_WorkingReticleBounds = m_ActivePopUp.GetReticleBounds(); m_WorkingReticleBounds.x *= vPopUpCurrentScale.x * 0.5f; m_WorkingReticleBounds.y *= vPopUpCurrentScale.y * 0.5f; } } public void ActivatePromoBorder(bool activate) { if (m_WidgetSibling) { if (activate) { m_WidgetSibling.RemovePromoMeshesFromTintable(m_PromoBorders); } else { m_WidgetSibling.AddPromoMeshesToTintable(m_PromoBorders); } } foreach (var m in m_PromoBorders) { m.material = activate ? PromoManager.m_Instance.SharePromoMaterial : m_BorderMaterial; } } virtual public void SetInIntroMode(bool inIntro) { } public void SetPositioningPercent(float fPercent) { m_PositioningPercent = fPercent; } public void SetScale(float fScale) { m_AdjustedScale = fScale; transform.localScale = m_BaseScale * m_AdjustedScale; } public bool PanelIsUsed() { return m_CurrentState != PanelState.Unused; } public Collider GetCollider() { return m_Collider; } public bool HasMeshCollider() { return m_MeshCollider != null; } virtual public bool RaycastAgainstMeshCollider(Ray rRay, out RaycastHit rHitInfo, float fDist) { rHitInfo = new RaycastHit(); bool bReturnValue = false; // Creating a popup when a popup exists will generate a temp collider. This is to prevent // forced, accidental out of bounds user input. if (m_TempPopUpCollider != null) { BoxCollider tempCollider = m_TempPopUpCollider.GetComponent<BoxCollider>(); bReturnValue = tempCollider.Raycast(rRay, out rHitInfo, fDist); if (!bReturnValue) { // If we're ever not pointing at the temp collider, destroy it. Destroy(m_TempPopUpCollider); m_TempPopUpCollider = null; } } // If we've got a pop-up, check collision against that guy first. if (m_ActivePopUp != null) { var collider = m_ActivePopUp.GetCollider(); if (collider == null) { throw new InvalidOperationException("No popup collider"); } bReturnValue = bReturnValue || m_ActivePopUp.GetCollider().Raycast(rRay, out rHitInfo, fDist); } // Check custom colliders on components. bReturnValue = bReturnValue || m_UIComponentManager.RaycastAgainstCustomColliders(rRay, out rHitInfo, fDist); // If we didn't have a pop-up, or collision failed, default to base mesh. if (m_MeshCollider == null) { throw new InvalidOperationException("No mesh collider"); } bReturnValue = bReturnValue || m_MeshCollider.Raycast(rRay, out rHitInfo, fDist); return bReturnValue; } virtual public void AssignControllerMaterials(InputManager.ControllerName controller) { m_UIComponentManager.AssignControllerMaterials(controller); } /// This function is used to determine the value to be passed in to the controller pad mesh's /// shader for visualizing swipes and other actions. /// It is called by SketchControls when the panel is in focus. public float GetControllerPadShaderRatio(InputManager.ControllerName controller) { return m_UIComponentManager.GetControllerPadShaderRatio(controller); } public bool BrushPadAnimatesOnHover() { return m_UIComponentManager.BrushPadAnimatesOnAnyHover(); } public bool UndoRedoBlocked() { // This function could be generalized to allow specific UIComponents to block undo/redo, // but we only need it in a single case right now, so it's a bit more specific. return m_ActivePopUp == null ? false : m_ActivePopUp.BlockUndoRedo(); } virtual public void OnPanelMoved() { } virtual protected void Awake() { m_WandAttachYOffset_Initial = m_WandAttachYOffset; m_WandAttachAngle_Initial = m_WandAttachAngle; m_WandAttachYOffset_Target = m_WandAttachYOffset; } // Happens at App Start() time. virtual public void InitPanel() { m_PanelInitializationStarted = true; m_BorderMaterial = m_Border.material; m_BaseScale = transform.localScale; m_AdjustedScale = 1.0f; CalculateBounds(); m_NonScaleChild = GetComponent<NonScaleChild>(); if (m_PanelDescriptionPrefab != null) { m_PanelDescriptionObject = (GameObject)Instantiate(m_PanelDescriptionPrefab); m_PanelDescriptionObject.transform.position = m_Mesh.transform.position; m_PanelDescriptionObject.transform.rotation = m_Mesh.transform.rotation; m_PanelDescriptionObject.transform.SetParent(transform); Vector3 vScale = m_PanelDescriptionObject.transform.localScale; vScale *= transform.localScale.x; m_PanelDescriptionObject.transform.localScale = vScale; m_PanelDescriptionRenderer = m_PanelDescriptionObject.GetComponent<Renderer>(); if (m_PanelDescriptionRenderer) { m_PanelDescriptionRenderer.enabled = false; } m_PanelDescriptionTextMeshPro = m_PanelDescriptionObject.GetComponent<TextMeshPro>(); if (m_PanelDescriptionTextMeshPro) { m_PanelDescriptionTextMeshPro.text = m_PanelDescription; m_PanelDescriptionTextMeshPro.color = m_PanelDescriptionColor; } } if (m_PanelFlairPrefab != null) { GameObject go = (GameObject)Instantiate(m_PanelFlairPrefab); m_PanelFlair = go.GetComponent<PanelFlair>(); m_PanelFlair.ParentToPanel(transform, m_PanelFlairOffset); } m_PanelDescriptionState = DescriptionState.Closing; m_PanelFlairState = DescriptionState.Closing; m_CloseAngleThreshold = Mathf.Abs(m_DescriptionOpenAngle - m_DescriptionClosedAngle) * 0.01f; m_PanelDescriptionTextSpring = new TextSpring(); m_PanelDescriptionTextSpring.m_CurrentAngle = m_DescriptionClosedAngle; m_PanelDescriptionTextSpring.m_DesiredAngle = m_DescriptionClosedAngle; m_PanelFlairSpring = new TextSpring(); m_PanelFlairSpring.m_CurrentAngle = m_DescriptionClosedAngle; m_PanelFlairSpring.m_DesiredAngle = m_DescriptionClosedAngle; PanelManager pm = PanelManager.m_Instance; m_Border.material.SetColor("_Color", pm.PanelHighlightInactiveColor); m_DecorRenderers = new List<Renderer>(); m_DecorTextMeshes = new List<TextMeshPro>(); if (m_Decor.Length > 0) { // Cache all decor renderers. for (int i = 0; i < m_Decor.Length; ++i) { Renderer [] aChildRenderers = m_Decor[i].GetComponentsInChildren<Renderer>(); for (int j = 0; j < aChildRenderers.Length; ++j) { // Prefer to cache a text mesh pro object if we find one. TextMeshPro tmp = aChildRenderers[j].GetComponent<TextMeshPro>(); if (tmp) { m_DecorTextMeshes.Add(tmp); } else { // Otherwise, the standard renderer will do. m_DecorRenderers.Add(aChildRenderers[j]); m_DecorRenderers[m_DecorRenderers.Count - 1].material.SetColor("_Color", pm.PanelHighlightInactiveColor); } } } } m_CurrentState = PanelState.Available; m_DesiredState = PanelState.Available; m_GazeActive = false; m_PositioningPercent = 0.0f; if (m_PositioningSpheresBounds.x > 0.0f && m_PositioningSpheresBounds.y > 0.0f && m_PositioningSphereRadius > 0.0f) { Vector2 vSphereBounds = m_PositioningSpheresBounds; vSphereBounds.x -= m_PositioningSphereRadius * 0.5f; vSphereBounds.y -= m_PositioningSphereRadius * 0.5f; m_ScaledPositioningSphereRadius = m_PositioningSphereRadius * transform.localScale.x; int iNumSpheresWidth = Mathf.CeilToInt((vSphereBounds.x * 2.0f) / m_PositioningSphereRadius); int iNumSpheresHeight = Mathf.CeilToInt((vSphereBounds.y * 2.0f) / m_PositioningSphereRadius); int iTotalNumSpheres = (iNumSpheresWidth * 2) + ((iNumSpheresHeight - 2) * 2); m_PositioningSpheres = new Vector3[iTotalNumSpheres]; float fXInterval = (vSphereBounds.x / (float)(iNumSpheresWidth - 1)) * 2.0f; float fYInterval = (vSphereBounds.y / (float)(iNumSpheresHeight - 1)) * 2.0f; for (int i = 0; i < iNumSpheresWidth; ++i) { float fX = -vSphereBounds.x + (fXInterval * (float)i); m_PositioningSpheres[i].Set(fX, -vSphereBounds.y, 0.0f); } for (int i = 0; i < iNumSpheresHeight - 2; ++i) { float fY = -vSphereBounds.y + (fYInterval * (float)(i + 1)); m_PositioningSpheres[iNumSpheresWidth + (i * 2)].Set(-vSphereBounds.x, fY, 0.0f); m_PositioningSpheres[iNumSpheresWidth + (i * 2) + 1].Set(vSphereBounds.x, fY, 0.0f); } for (int i = iTotalNumSpheres - iNumSpheresWidth; i < iTotalNumSpheres; ++i) { int iIndex = i - (iTotalNumSpheres - iNumSpheresWidth); float fX = -vSphereBounds.x + (fXInterval * (float)iIndex); m_PositioningSpheres[i].Set(fX, vSphereBounds.y, 0.0f); } m_PositioningSpheresTransformed = new Vector3[m_PositioningSpheres.Length]; for (int i = 0; i < m_PositioningSpheresTransformed.Length; ++i) { m_PositioningSpheresTransformed[i] = new Vector3(); m_PositioningExtent = Mathf.Max(m_PositioningExtent, Mathf.Max(m_PositioningSpheres[i].x, m_PositioningSpheres[i].y)); } m_PositioningExtent += (m_PositioningSphereRadius * 2.0f); } m_MaxGazeOffsetDistance = m_Bounds.magnitude; m_GazeRotationAmount = Quaternion.identity; m_UIComponentManager = GetComponent<UIComponentManager>(); m_UIComponentManager.SetColor(pm.PanelHighlightInactiveColor); m_WidgetSibling = GetComponent<PanelWidget>(); if (m_Fixed) { m_TransitionState = FixedTransitionState.Fixed; } // Bake border meshs. float width = !m_AdvancedModePanel ? m_BorderMeshAdvWidth : m_BorderMeshWidth; Color baseCol = !m_AdvancedModePanel ? pm.PanelBorderMeshOutlineColor : pm.PanelBorderMeshBaseColor; Color outlineCol = !m_AdvancedModePanel ? pm.PanelBorderMeshBaseColor : pm.PanelBorderMeshOutlineColor; BakedMeshOutline[] bakeries = GetComponentsInChildren<BakedMeshOutline>(true); BakedMeshOutline borderBakery = m_Border.GetComponent<BakedMeshOutline>(); for (int i = 0; i < bakeries.Length; ++i) { if (bakeries[i] == borderBakery) { // The border is the only bakery that gets custom treatment. bakeries[i].Bake(baseCol, outlineCol, width); } else { bakeries[i].Bake(pm.PanelBorderMeshBaseColor, pm.PanelBorderMeshOutlineColor, m_BorderMeshWidth); } } m_PanelInitializationFinished = true; } public void CloseActivePopUp(bool force) { if (m_ActivePopUp != null) { if (m_ActivePopUp.RequestClose(force)) { InvalidateIfActivePopup(m_ActivePopUp); } } } public void VerifyStateForFloating() { m_TransitionState = FixedTransitionState.Floating; m_WandTransitionPercent = 1; } public void SetPanelStableToTarget() { m_WandAttachYOffset_Stable = m_WandAttachYOffset_Target; } public void ResetPanelToInitialPosition() { m_WandAttachYOffset = m_WandAttachYOffset_Initial; m_WandAttachYOffset_Target = m_WandAttachYOffset_Initial; m_WandAttachYOffset_Stable = m_WandAttachYOffset_Initial; m_WandAttachAngle = m_WandAttachAngle_Initial; if (m_TransitionState != FixedTransitionState.Fixed) { m_Fixed = true; m_TransitionState = FixedTransitionState.Fixed; m_WandTransitionPercent = 0; } } public void ResetPanel() { // Get rid of the popup as fast as possible. if (m_ActivePopUp != null) { Destroy(m_ActivePopUp.gameObject); InvalidateIfActivePopup(m_ActivePopUp); } Destroy(m_TempPopUpCollider); m_TempPopUpCollider = null; //reset gaze animations m_PanelDescriptionState = DescriptionState.Closed; if (m_PanelDescriptionRenderer) { m_PanelDescriptionRenderer.enabled = false; } m_PanelFlairState = DescriptionState.Closed; if (m_PanelFlair != null) { m_PanelFlair.Hide(); } UpdatePanelColor(PanelManager.m_Instance.PanelHighlightInactiveColor); m_GazeActive = false; m_GazeActivePercent = 0.0001f; m_GazeRotationAxis = Vector3.zero; } public void InvalidateIfActivePopup(PopUpWindow activePopup) { // If this popup isn't the active one, don't bother. if (activePopup == m_ActivePopUp) { m_ActivePopUp = null; // Eat input when we close a popup so the close action doesn't carry over. m_EatInput = true; } } void OnEnable() { OnEnablePanel(); } void OnDisable() { OnDisablePanel(); } virtual protected void OnEnablePanel() { if (PanelManager.m_Instance != null) { if (PanelManager.m_Instance.AdvancedModeActive()) { m_CurrentlyVisibleInAdvancedMode = true; } } } virtual protected void OnDisablePanel() { if (PanelManager.m_Instance != null) { if (PanelManager.m_Instance.AdvancedModeActive()) { m_CurrentlyVisibleInAdvancedMode = false; } } } public void ResetReticleOffset() { m_ReticleOffset = Vector3.zero; } public void UpdateReticleOffset(float fXDelta, float fYDelta) { m_ReticleOffset.x += fXDelta * m_PanelSensitivity; m_ReticleOffset.y += fYDelta * m_PanelSensitivity; if (m_ClampToBounds) { m_ReticleOffset.x = Mathf.Clamp(m_ReticleOffset.x, -m_WorkingReticleBounds.x, m_WorkingReticleBounds.x); m_ReticleOffset.y = Mathf.Clamp(m_ReticleOffset.y, -m_WorkingReticleBounds.y, m_WorkingReticleBounds.y); m_ReticleOffset.z = m_WorkingReticleBounds.z; } } // Given a position that has been proven to be a hit point on the panel's collider and the cast // direction that resulted in that point, determine where the reticle should be located. // Used by wand panel method of interacting with panels. virtual public void GetReticleTransformFromPosDir(Vector3 vInPos, Vector3 vInDir, out Vector3 vOutPos, out Vector3 vForward) { //by default, the collision point is ok, and the reticle's forward should be the same as the mesh vOutPos = vInPos; vForward = -m_Mesh.transform.forward; Vector3 dir = Vector3.forward; Ray rCastRay = new Ray(vInPos - vInDir * 0.5f, vInDir); // If we have a ghost popup, collide with that to find our position. if (m_TempPopUpCollider != null) { RaycastHit rHitInfo; if (DoesRayHitCollider(rCastRay, m_TempPopUpCollider.GetComponent<BoxCollider>(), out rHitInfo)) { vOutPos = rHitInfo.point; } } // Override default and ghost with standard popup collision. if (m_ActivePopUp != null) { m_ActivePopUp.CalculateReticleCollision(rCastRay, ref vOutPos, ref vForward); } else { // PopUps trump UIComponents, so if there isn't a PopUp, check against all UIComponents. m_UIComponentManager.CalculateReticleCollision(rCastRay, ref vOutPos, ref vForward); } } // TODO : This is currently broken. Needs to be updated to use new // m_UIComponentManager.CalculateReticleCollision style. // Using m_ReticleOffset, determine where the reticle should be located. // Used by gaze method of interacting with panels. virtual public void GetReticleTransform(out Vector3 vPos, out Vector3 vForward, bool bGazeAndTap) { // For ViewingOnly controls, position the reticle at the gaze panel position if (bGazeAndTap) { // Calculate plane intersection Transform head = ViewpointScript.Head; Ray ray = new Ray(head.position, head.forward); RaycastHit rHitInfo; if (RaycastAgainstMeshCollider(ray, out rHitInfo, GAZE_DISTANCE)) { vPos = rHitInfo.point; } else { vPos = new Vector3(LARGE_DISTANCE, LARGE_DISTANCE, LARGE_DISTANCE); } } else { Vector3 vTransformedOffset = m_Mesh.transform.rotation * m_ReticleOffset; vPos = transform.position + vTransformedOffset; } vForward = -m_Mesh.transform.forward; } // This function should only be used when the app state changes in a way that requires // an out-of-focus panel's visuals to become reflect a stale state. virtual public void ForceUpdatePanelVisuals() { m_UIComponentManager.UpdateVisuals(); } void Update() { BaseUpdate(); } protected void BaseUpdate() { UpdateState(); CalculateBounds(); UpdateDescriptions(); UpdateGazeBehavior(); UpdateFixedTransition(); } protected void UpdateState() { //check if we're switching activity if (m_GazeWasActive != m_GazeActive) { if (m_GazeActive) { AudioManager.m_Instance.ActivatePanel(true, transform.position); } else { m_UIComponentManager.ResetInput(); AudioManager.m_Instance.ActivatePanel(false, transform.position); } m_GazeWasActive = m_GazeActive; OnUpdateActive(); } bool bGazeDescriptionsWereActive = m_GazeDescriptionsActive; m_GazeDescriptionsActive = m_GazeActive; // Update components if gaze is active. if (m_GazeDescriptionsActive) { m_UIComponentManager.UpdateVisuals(); } //check if we're switching descriptions showing if (bGazeDescriptionsWereActive != m_GazeDescriptionsActive) { if (m_GazeDescriptionsActive) { if (m_PanelDescriptionObject) { m_PanelDescriptionState = DescriptionState.Open; m_PanelDescriptionTextSpring.m_DesiredAngle = m_DescriptionOpenAngle; m_PanelDescriptionRenderer.enabled = true; } } else { if (m_PanelDescriptionObject) { m_PanelDescriptionState = DescriptionState.Closing; m_PanelDescriptionTextSpring.m_DesiredAngle = m_DescriptionClosedAngle; ResetPanelFlair(); } m_UIComponentManager.ManagerLostFocus(); m_UIComponentManager.Deactivate(); if (m_ActivePopUp != null) { if (m_ActivePopUp.RequestClose()) { InvalidateIfActivePopup(m_ActivePopUp); } } } } //update state m_CurrentState = m_DesiredState; } virtual protected void OnUpdateActive() { } void UpdateMeshRotation() { m_Mesh.transform.rotation = m_GazeRotationAmount * transform.rotation; } protected void UpdateDescriptions() { try { m_PanelDescriptionCounter = 0; if (m_PanelDescriptionState != DescriptionState.Closed && m_PanelDescriptionObject != null) { m_PanelDescriptionCounter = 1; m_PanelDescriptionTextSpring.Update(m_DescriptionSpringK, m_DescriptionSpringDampen); m_PanelDescriptionCounter = 2; Quaternion qOrient = Quaternion.Euler(0.0f, m_PanelDescriptionTextSpring.m_CurrentAngle, 0.0f); m_PanelDescriptionObject.transform.rotation = m_Mesh.transform.rotation * qOrient; m_PanelDescriptionCounter = 3; Vector3 vPanelDescriptionOffset = m_Bounds; vPanelDescriptionOffset.x *= m_PanelDescriptionOffset.x; vPanelDescriptionOffset.y *= m_PanelDescriptionOffset.y; Vector3 vTransformedOffset = m_Mesh.transform.rotation * vPanelDescriptionOffset; m_PanelDescriptionObject.transform.position = m_Mesh.transform.position + vTransformedOffset; m_PanelDescriptionCounter = 4; float fDistToClosed = Mathf.Abs(m_PanelDescriptionTextSpring.m_CurrentAngle - m_DescriptionClosedAngle); Color descColor = m_PanelDescriptionColor; if (m_ActivePopUp != null) { descColor = Color.Lerp(m_PanelDescriptionColor, PanelManager.m_Instance.PanelHighlightInactiveColor, m_ActivePopUp.GetTransitionRatioForVisuals()); } float fRatio = fDistToClosed / m_DescriptionAlphaDistance; descColor.a = Mathf.Min(fRatio * fRatio, 1.0f); if (m_PanelDescriptionTextMeshPro) { m_PanelDescriptionTextMeshPro.color = descColor; } m_PanelDescriptionCounter = 5; if (m_PanelDescriptionState == DescriptionState.Closing) { float fToDesired = m_PanelDescriptionTextSpring.m_DesiredAngle - m_PanelDescriptionTextSpring.m_CurrentAngle; if (Mathf.Abs(fToDesired) <= m_CloseAngleThreshold) { m_PanelDescriptionRenderer.enabled = false; m_PanelDescriptionState = DescriptionState.Closed; } } } m_PanelDescriptionCounter = 6; if (m_PanelFlairState != DescriptionState.Closed) { m_PanelDescriptionCounter = 7; m_PanelFlairSpring.Update(m_DescriptionSpringK, m_DescriptionSpringDampen); float fDistToClosed = Mathf.Abs(m_PanelFlairSpring.m_CurrentAngle - m_DescriptionClosedAngle); float fRatio = fDistToClosed / m_DescriptionAlphaDistance; float fAlpha = Mathf.Min(fRatio * fRatio, 1.0f); m_PanelDescriptionCounter = 8; Quaternion qOrient = m_Mesh.transform.rotation * Quaternion.Euler(0.0f, m_PanelFlairSpring.m_CurrentAngle, 0.0f); m_PanelDescriptionCounter = 9; if (m_PanelFlair != null) { m_PanelFlair.UpdateAnimationOnPanel(m_Bounds, qOrient, fAlpha); } m_PanelDescriptionCounter = 10; if (m_PanelFlairState == DescriptionState.Closing) { float fToDesired = m_PanelFlairSpring.m_DesiredAngle - m_PanelFlairSpring.m_CurrentAngle; if (Mathf.Abs(fToDesired) <= m_CloseAngleThreshold) { if (m_PanelFlair != null) { m_PanelFlair.Hide(); } m_PanelFlairState = DescriptionState.Closed; } } } } catch (Exception ex) { string message = string.Format("{0}: Init State({1}, {2}), Counter({3})", ex.Message, m_PanelInitializationStarted, m_PanelInitializationFinished, m_PanelDescriptionCounter); throw new Exception(message); } } protected virtual void UpdateGazeBehavior() { if (m_UseGazeRotation && m_Mesh) { float fPrevPercent = m_GazeActivePercent; float fPercentStep = m_GazeActivateSpeed * Time.deltaTime; if (IsActive()) { m_GazeActivePercent = Mathf.Min(m_GazeActivePercent + fPercentStep, 1.0f); } else { m_GazeActivePercent = Mathf.Max(m_GazeActivePercent - fPercentStep, 0.0f); } //don't bother updating static panels if (fPrevPercent > 0.0f) { float fRotationAngle = m_GazeRotationAngle * m_GazeActivePercent * (1.0f - m_PositioningPercent); m_GazeRotationAmount = Quaternion.AngleAxis(fRotationAngle, m_GazeRotationAxis); UpdateMeshRotation(); Color rPanelColor = GetGazeColor(); if (m_Border.material == m_BorderMaterial) { m_Border.material.SetColor("_Color", rPanelColor); } if (fPrevPercent < 1.0f) { float fScaleMult = m_GazeActivePercent * (m_GazeHighlightScaleMultiplier - 1.0f); Vector3 newScale = m_BaseScale * m_AdjustedScale * (1.0f + fScaleMult); if (m_NonScaleChild != null) { m_NonScaleChild.globalScale = newScale; } else { transform.localScale = newScale; } } UpdatePanelColor(rPanelColor); m_UIComponentManager.GazeRatioChanged(m_GazeActivePercent); } } } public Color GetGazeColor() { PanelManager pm = PanelManager.m_Instance; Color targetColor = pm.PanelHighlightActiveColor; if (m_ActivePopUp != null) { targetColor = Color.Lerp(pm.PanelHighlightActiveColor, pm.PanelHighlightInactiveColor, m_ActivePopUp.GetTransitionRatioForVisuals()); } float t = m_GazeActivePercent; if (SketchControlsScript.m_Instance.AtlasIconTextures) { // If we're atlasing panel textures, only send 0 and 1 through. t = Mathf.Floor(m_GazeActivePercent + 0.5f); } return Color.Lerp(pm.PanelHighlightInactiveColor, targetColor, t); } protected void UpdateFixedTransition() { // State machine for panel exploding off of wand controller. if (m_TransitionState == FixedTransitionState.FixedToFloating) { m_WandTransitionPercent += Time.deltaTime / m_WandTransitionDuration; if (m_WandTransitionPercent >= 1.0f) { m_WandTransitionPercent = 1.0f; m_TransitionState = FixedTransitionState.Floating; } PanelManager.m_Instance.UpdateWandTransitionXf( this, m_WandTransitionTarget, m_WandTransitionPercent); } else if (m_TransitionState == FixedTransitionState.FloatingToFixed) { m_WandTransitionPercent -= Time.deltaTime / m_WandTransitionDuration; if (m_WandTransitionPercent <= 0.0f) { m_WandTransitionPercent = 0.0f; m_TransitionState = FixedTransitionState.Fixed; } PanelManager.m_Instance.UpdateWandTransitionXf( this, m_WandTransitionTarget, m_WandTransitionPercent); } else if (WidgetSibling && WidgetSibling.IsUserInteracting(InputManager.ControllerName.Brush)) { // If the user is interacting with this panel, lock to a pane if this panel allows it. if (m_CanBeFixedToWand) { PanelManager.m_Instance.AttachHeldPanelToWand(this); } } else if (m_TransitionState == FixedTransitionState.Fixed) { // Update attach height. float fStep = m_WandAttachAdjustSpeed * Time.deltaTime; float fToTarget = m_WandAttachYOffset_Target - m_WandAttachYOffset; if (Mathf.Abs(fToTarget) < fStep) { m_WandAttachYOffset = m_WandAttachYOffset_Target; } else { m_WandAttachYOffset += fStep * Mathf.Sign(fToTarget); } m_WandAttachRadiusAdjust = 0.0f; } } public void WidgetSiblingBeginInteraction() { PanelManager.m_Instance.InitPanesForPanelAttach(m_Fixed); // Initialize primed flag to off-- it'll get enabled if the attachment checks are valid. m_WandPrimedForAttach = false; if (m_Fixed) { m_Fixed = false; m_TransitionState = FixedTransitionState.Floating; m_WandTransitionPercent = 1; } } public void WidgetSiblingEndInteraction() { if (!m_Fixed) { PanelManager.m_Instance.ResetPaneVisuals(); if (m_WandPrimedForAttach || !CanBeDetached) { m_Fixed = true; m_TransitionState = FixedTransitionState.Fixed; m_WandTransitionPercent = 0; } if (!m_WandPrimedForAttach) { // If we're releasing this panel and it's not snapping to a pane, make sure the pane // panels are reset back to their stable positions. PanelManager.m_Instance.SetFixedPanelsToStableOffsets(); } else { // If this panel is snapping to a pane, update it's stable position so it's sorted // correctly when we close the gaps. SetPanelStableToTarget(); } m_WandTransitionTarget = TrTransform.FromTransform(transform); WidgetSibling.SetActiveTintToShowError(false); PanelManager.m_Instance.ClosePanePanelGaps(); } } // Target is ignored if the panel is reattaching to the wand public void TransitionToWand(bool bFixed, TrTransform target) { if (bFixed && m_TransitionState != FixedTransitionState.Fixed) { m_TransitionState = FixedTransitionState.FloatingToFixed; } else if (!bFixed && m_TransitionState != FixedTransitionState.Floating) { m_WandTransitionTarget = target; m_TransitionState = FixedTransitionState.FixedToFloating; } } void UpdatePanelColor(Color rPanelColor) { // Set the appropriate dim value for all our UI components. m_UIComponentManager.SetColor(rPanelColor); OnUpdateGazeBehavior(rPanelColor); for (int i = 0; i < m_DecorRenderers.Count; ++i) { m_DecorRenderers[i].material.SetColor("_Color", rPanelColor); } for (int i = 0; i < m_DecorTextMeshes.Count; ++i) { m_DecorTextMeshes[i].color = rPanelColor; } } virtual protected void OnUpdateGazeBehavior(Color rPanelColor) { } virtual public void PanelGazeActive(bool bActive) { m_GazeActive = bActive; m_GazeHitPositionCurrent = transform.position; m_UIComponentManager.ResetInput(); } void SetPanelFlairText(string sText) { if (m_PanelFlair != null) { // Interpret any message as a good message. if (m_PanelFlair.AlwaysShow) { m_PanelFlair.SetText(sText); m_PanelFlair.Show(); m_PanelFlairState = DescriptionState.Open; m_PanelFlairSpring.m_DesiredAngle = m_DescriptionOpenAngle; } else { if (sText != null && !sText.Equals("")) { m_PanelFlair.SetText(sText); m_PanelFlair.Show(); m_PanelFlairState = DescriptionState.Open; m_PanelFlairSpring.m_DesiredAngle = m_DescriptionOpenAngle; } else if (m_PanelFlairState != DescriptionState.Closed) { m_PanelFlairState = DescriptionState.Closing; m_PanelFlairSpring.m_DesiredAngle = m_DescriptionClosedAngle; } } } } public void ResetPanelFlair() { if (m_PanelFlairState != DescriptionState.Closed) { m_PanelFlairState = DescriptionState.Closing; m_PanelFlairSpring.m_DesiredAngle = m_DescriptionClosedAngle; } } virtual public void OnWidgetShowAnimStart() { } virtual public void OnWidgetShowAnimComplete() { } virtual public void OnWidgetHide() { } /// Accumulates dpad input, and returns nonzero for a discrete swipe action. /// Return value is 1 for "backward" swipe moving a page forward /// and -1 for "forward" swipe moving a page backward. protected int AccumulateSwipe() { int direction = 0; if (InputManager.m_Instance.IsBrushScrollActive()) { // If our delta is beyond our trigger threshold, report it. float fDelta = InputManager.m_Instance.GetAdjustedBrushScrollAmount(); if (IncrementMotionAndCheckForSwipe(fDelta)) { direction = (int)Mathf.Sign(m_SwipeRecentMotion.x) * -1; m_SwipeRecentMotion.x = 0.0f; } } else { m_SwipeRecentMotion.x = 0.0f; } return direction; } /// Virtual so panels can interpret m_SwipeRecentMotion however they'd like. virtual public bool IncrementMotionAndCheckForSwipe(float fMotion) { m_SwipeRecentMotion.x += fMotion; return Mathf.Abs(m_SwipeRecentMotion.x) > m_SwipeThreshold; } /// Panels are updated by SketchControls when they have focus. public void UpdatePanel(Vector3 vToPanel, Vector3 vHitPoint) { // Validate input and cache it for this update. m_InputValid = InputManager.m_Instance.GetCommand(InputManager.SketchCommands.Activate); if (m_EatInput) { m_EatInput = m_InputValid; m_InputValid = false; } // Cache input ray for this update. Vector3 vReticlePos = SketchControlsScript.m_Instance.GetUIReticlePos(); m_ReticleSelectionRay = new Ray(vReticlePos - transform.forward, transform.forward); if (m_ActivePopUp != null) { var collider = m_ActivePopUp.GetCollider(); if (collider == null) { throw new InvalidOperationException("No popup collider"); } RaycastHit hitInfo; // If we're pointing at a popup, increment our gaze timer. if (BasePanel.DoesRayHitCollider(m_ReticleSelectionRay, m_ActivePopUp.GetCollider(), out hitInfo)) { if (m_ActivePopUp.IsOpen()) { m_PopUpGazeTimer += Time.deltaTime; } } else if (!m_ActivePopUp.InputObjectHasFocus() && (InputManager.m_Instance.GetCommandDown(InputManager.SketchCommands.Activate) || m_PopUpGazeTimer > m_PopUpGazeDuration)) { // If we're not pointing at the popup and the user doesn't have focus on an element // of the popup, dismiss the popup if we've pointed at it before, or there's input. m_ActivePopUp.RequestClose(); } } if (m_UseGazeRotation) { m_GazeHitPositionDesired = vHitPoint; Vector3 vCurrToDesired = m_GazeHitPositionDesired - m_GazeHitPositionCurrent; float fStep = m_GazeHitPositionSpeed * Time.deltaTime; if (vCurrToDesired.sqrMagnitude < fStep * fStep) { m_GazeHitPositionCurrent = m_GazeHitPositionDesired; } else { vCurrToDesired.Normalize(); vCurrToDesired *= fStep; m_GazeHitPositionCurrent += vCurrToDesired; } Vector3 vToCenter = m_GazeHitPositionCurrent - GetCollider().transform.position; float fOffsetDist = vToCenter.magnitude; vToCenter.Normalize(); m_GazeRotationAxis = Vector3.Cross(-vToPanel, vToCenter); m_GazeRotationAxis.Normalize(); m_GazeRotationAngle = (fOffsetDist / m_MaxGazeOffsetDistance) * m_MaxGazeRotation; } // Update custom logic for panel. OnUpdatePanel(vToPanel, vHitPoint); // Update UIComponents, with PopUps taking priority. if (m_ActivePopUp) { if (!m_EatInput && m_PopUpGazeTimer > 0) { m_ActivePopUp.UpdateUIComponents(m_ReticleSelectionRay, m_InputValid, m_ActivePopUp.GetCollider()); } } else { // TODO : I'm not convinced the 3rd parameter here should be the main collider. // I think it might need to be the mesh collider. If so, the collider is only used in // monoscopic mode and should be renamed appropriately. m_UIComponentManager.UpdateUIComponents(m_ReticleSelectionRay, m_InputValid, GetCollider()); // If a popup was just spawned, clear our active UI component, as input will now be // directed to the popup. if (m_ActivePopUp) { m_UIComponentManager.ResetInput(); } if (m_UIComponentManager.ActiveInputUIComponent == null) { SetPanelFlairText(null); } else { SetPanelFlairText(m_UIComponentManager.ActiveInputUIComponent.Description); } } } /// Base level logic for updating panel. This should be called from any derived class. virtual public void OnUpdatePanel(Vector3 vToPanel, Vector3 vHitPoint) { } public void InitForPanelMovement() { m_PositioningHome = transform.position; m_PositioningVelocity.Set(0.0f, 0.0f, 0.0f); m_WandAttachYOffset_Stable = m_WandAttachYOffset_Target; } virtual public void PanelHasStoppedMoving() { m_GazeHitPositionCurrent = transform.position; } public void CreatePopUp(SketchControlsScript.GlobalCommands rCommand, int iCommandParam, int iCommandParam2, string sDelayedText = "", Action delayedClose = null) { CreatePopUp(rCommand, iCommandParam, iCommandParam2, Vector3.zero, sDelayedText, delayedClose); } public void CreatePopUp(SketchControlsScript.GlobalCommands rCommand, int iCommandParam, int iCommandParam2, Vector3 vPopupOffset, string sDelayedText = "", Action delayedClose = null) { bool bPopUpExisted = false; Vector3 vPrevPopUpPos = Vector3.zero; // If we've got an active popup, send it packing. if (m_ActivePopUp != null) { // Create a copy of the collider so we don't pull the rug out from under the user. m_TempPopUpCollider = m_ActivePopUp.DuplicateCollider(); vPrevPopUpPos = m_ActivePopUp.transform.position; CloseActivePopUp(false); bPopUpExisted = true; } if (m_ActivePopUp == null) { // Look for the appropriate popup for this command. int iPopUpIndex = -1; for (int i = 0; i < m_PanelPopUpMap.Length; ++i) { if (m_PanelPopUpMap[i].m_Command == rCommand) { iPopUpIndex = i; break; } } if (iPopUpIndex >= 0) { // Create a new popup. GameObject popUp = (GameObject)Instantiate(m_PanelPopUpMap[iPopUpIndex].m_PopUpPrefab, m_Mesh.transform.position, m_Mesh.transform.rotation); m_ActivePopUp = popUp.GetComponent<PopUpWindow>(); // If we're replacing a popup, put the new one in the same position. if (bPopUpExisted) { popUp.transform.position = vPrevPopUpPos; } else { Vector3 vPos = m_Mesh.transform.position + (m_Mesh.transform.forward * m_ActivePopUp.GetPopUpForwardOffset()) + m_Mesh.transform.TransformVector(vPopupOffset); popUp.transform.position = vPos; } popUp.transform.parent = m_Mesh.transform; m_ActivePopUp.Init(gameObject, sDelayedText); m_ActivePopUp.SetPopupCommandParameters(iCommandParam, iCommandParam2); m_ActivePopUp.m_OnClose += delayedClose; m_PopUpGazeTimer = 0; m_EatInput = !m_ActivePopUp.IsLongPressPopUp(); // If we closed a popup to create this one, we wan't don't want the standard visual // fade that happens when a popup comes in. We're spoofing the transition value // for visuals to avoid a pop. if (bPopUpExisted) { m_ActivePopUp.SpoofTransitionValue(); } // Cache the intended command. m_DelayedCommand = rCommand; m_DelayedCommandParam = iCommandParam; m_DelayedCommandParam2 = iCommandParam2; } } } public void PositionPopUp(Vector3 basePos) { m_ActivePopUp.transform.position = basePos; } public void ResolveDelayedButtonCommand(bool bConfirm, bool bKeepOpen = false) { PopUpWindow currentPopup = m_ActivePopUp; if (bConfirm) { SketchControlsScript.m_Instance.IssueGlobalCommand( m_DelayedCommand, m_DelayedCommandParam, m_DelayedCommandParam2); } // if the popup has changed since the start of the function (and it wasn't null at the start), // that means that the global command called kicked off a new popup. In which case we shouldn't // close the popup, or overwrite the delayed command. bool panelChanged = (currentPopup != null) && (m_ActivePopUp != currentPopup); if (!panelChanged) { m_DelayedCommand = SketchControlsScript.GlobalCommands.Null; m_DelayedCommandParam = -1; m_DelayedCommandParam2 = -1; if (m_ActivePopUp != null && !bKeepOpen) { m_ActivePopUp.RequestClose(); } } } virtual public void GotoPage(int iIndex) { } virtual public void AdvancePage(int iAmount) { } public void InitForCollisionDetection() { for (int i = 0; i < m_PositioningSpheresTransformed.Length; ++i) { m_PositioningSpheresTransformed[i] = transform.TransformPoint(m_PositioningSpheres[i]); } } public void CalculateDepenetration(BasePanel rOther) { Vector3 vThemToUs = transform.position - rOther.transform.position; Vector3 vThemToUsNorm = vThemToUs.normalized; float fMaxExtent = m_PositioningExtent + rOther.GetPositioningExtent(); if (vThemToUs.sqrMagnitude < fMaxExtent * fMaxExtent) { float fCombinedSphereRad = m_ScaledPositioningSphereRadius + rOther.m_ScaledPositioningSphereRadius; float fCombinedSphereRadSq = fCombinedSphereRad * fCombinedSphereRad; for (int i = 0; i < m_PositioningSpheresTransformed.Length; ++i) { for (int j = 0; j < rOther.m_PositioningSpheresTransformed.Length; ++j) { Vector3 vSphereToSphere = rOther.m_PositioningSpheresTransformed[j] - m_PositioningSpheresTransformed[i]; if (vSphereToSphere.sqrMagnitude < fCombinedSphereRadSq) { float fSphereToSphereDist = vSphereToSphere.magnitude; float fDepenetrationAmount = fCombinedSphereRad - fSphereToSphereDist; m_PositioningVelocity += (vThemToUsNorm * fDepenetrationAmount * m_DepenetrationScalar * Time.deltaTime); } } } } } public void CalculateDepenetration(Vector3 vOtherPos, float fCombinedRadius) { Vector3 vThemToUs = transform.position - vOtherPos; if (vThemToUs.sqrMagnitude < fCombinedRadius * fCombinedRadius) { float fDepenetrationAmount = fCombinedRadius - vThemToUs.magnitude; m_PositioningVelocity += (vThemToUs.normalized * fDepenetrationAmount * m_DepenetrationScalar * Time.fixedDeltaTime); } } public void UpdatePositioningForces() { //use spring to bring us home Vector3 vToHome = m_PositioningHome - transform.position; vToHome *= m_PositioningK; Vector3 vDampenedVel = m_PositioningVelocity * m_PositioningDampen; Vector3 vSpringForce = vToHome - vDampenedVel; m_PositioningVelocity += vSpringForce; //update position Vector3 vPos = transform.position; vPos += (m_PositioningVelocity * Time.deltaTime); transform.position = vPos; if (m_NonScaleChild) { m_NonScaleChild.OnPosRotChanged(); } } /// Update the delayed command parameter that is used when a popup confirmation button is pressed. /// This can be used when something provides more context to the initial command. public void UpdateDelayedCommandParameter(int newParam) { m_DelayedCommandParam = newParam; } static public bool DoesRayHitCollider(Ray rRay, Collider rCollider, bool skipAngleCheck = false) { if (!skipAngleCheck && Vector3.Angle(rRay.direction, rCollider.transform.forward) > 90.0f) { return false; } RaycastHit rHitInfo; return rCollider.Raycast(rRay, out rHitInfo, 100.0f); } static public bool DoesRayHitCollider(Ray rRay, Collider rCollider, out RaycastHit rHitInfo) { return rCollider.Raycast(rRay, out rHitInfo, 100.0f); } /* * For Debugging. * void OnDrawGizmos() { if (m_PositioningSpheres != null) { Gizmos.color = Color.yellow; for (int i = 0; i < m_PositioningSpheres.Length; ++i) { Gizmos.DrawWireSphere(transform.TransformPoint(m_PositioningSpheres[i]), m_ScaledPositioningSphereRadius); } } if (WidgetSibling != null) { Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, WidgetSibling.m_CollisionRadius); } } /**/ } } // namespace TiltBrush
/// This Class implements the Difference Algorithm published in /// "An O(ND) Difference Algorithm and its Variations" by Eugene Myers /// Algorithmica Vol. 1 No. 2, 1986, p 251. /// /// There are many C, Java, Lisp implementations public available but they all seem to come /// from the same source (diffutils) that is under the (unfree) GNU public License /// and cannot be reused as a sourcecode for a commercial application. /// There are very old C implementations that use other (worse) algorithms. /// Microsoft also published sourcecode of a diff-tool (windiff) that uses some tree data. /// Also, a direct transfer from a C source to C# is not easy because there is a lot of pointer /// arithmetic in the typical C solutions and i need a managed solution. /// These are the reasons why I implemented the original published algorithm from the scratch and /// make it avaliable without the GNU license limitations. /// I do not need a high performance diff tool because it is used only sometimes. /// I will do some performace tweaking when needed. /// /// The algorithm itself is comparing 2 arrays of numbers so when comparing 2 text documents /// each line is converted into a (hash) number. See DiffText(). /// /// Some chages to the original algorithm: /// The original algorithm was described using a recursive approach and comparing zero indexed arrays. /// Extracting sub-arrays and rejoining them is very performance and memory intensive so the same /// (readonly) data arrays are passed arround together with their lower and upper bounds. /// This circumstance makes the LCS and SMS functions more complicate. /// I added some code to the LCS function to get a fast response on sub-arrays that are identical, /// completely deleted or inserted. /// /// The result from a comparisation is stored in 2 arrays that flag for modified (deleted or inserted) /// lines in the 2 data arrays. These bits are then analysed to produce a array of Item objects. /// /// Further possible optimizations: /// (first rule: don't do it; second: don't do it yet) /// The arrays DataA and DataB are passed as parameters, but are never changed after the creation /// so they can be members of the class to avoid the paramter overhead. /// In SMS is a lot of boundary arithmetic in the for-D and for-k loops that can be done by increment /// and decrement of local variables. /// The DownVector and UpVector arrays are alywas created and destroyed each time the SMS gets called. /// It is possible to reuse tehm when transfering them to members of the class. /// See TODO: hints. /// /// diff.cs: A port of the algorythm to C# /// Created by Matthias Hertel, see http://www.mathertel.de /// This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx /// /// Changes: /// 2002.09.20 There was a "hang" in some situations. /// Now I undestand a little bit more of the SMS algorithm. /// There have been overlapping boxes; that where analyzed partial differently. /// One return-point is enough. /// A assertion was added in CreateDiffs when in debug-mode, that counts the number of equal (no modified) lines in both arrays. /// They must be identical. /// /// 2003.02.07 Out of bounds error in the Up/Down vector arrays in some situations. /// The two vetors are now accessed using different offsets that are adjusted using the start k-Line. /// A test case is added. /// /// 2006.03.05 Some documentation and a direct Diff entry point. /// /// 2006.03.08 Refactored the API to static methods on the Diff class to make usage simpler. /// 2006.03.10 using the standard Debug class for self-test now. /// compile with: csc /target:exe /out:diffTest.exe /d:DEBUG /d:TRACE /d:SELFTEST Diff.cs /// 2007.01.05 The license changed to a <a rel="license" href="http://www.mathertel.de/License.aspx">BSD style license</a>.</p> using System; using System.Collections; using System.Text; using System.Text.RegularExpressions; namespace Microsoft.TeamFoundation.VersionControl.Client { /// <summary>details of one difference.</summary> internal struct DiffItem { /// <summary>Start Line number in Data A.</summary> public int StartA; /// <summary>Start Line number in Data B.</summary> public int StartB; /// <summary>Number of changes in Data A.</summary> public int deletedA; /// <summary>Number of changes in Data A.</summary> public int insertedB; } internal class DiffUtil { /// <summary> /// Shortest Middle Snake Return Data /// </summary> private struct SMSRD { internal int x, y; // internal int u, v; // 2002.09.20: no need for 2 points } /// <summary> /// Find the difference in 2 text documents, comparing by textlines. /// The algorithm itself is comparing 2 arrays of numbers so when comparing 2 text documents /// each line is converted into a (hash) number. This hash-value is computed by storing all /// textlines into a common hashtable so i can find dublicates in there, and generating a /// new number each time a new textline is inserted. /// </summary> /// <param name="TextA">A-version of the text (usualy the old one)</param> /// <param name="TextB">B-version of the text (usualy the new one)</param> /// <param name="trimSpace">When set to true, all leading and trailing whitespace characters are stripped out before the comparation is done.</param> /// <param name="ignoreSpace">When set to true, all whitespace characters are converted to a single space character before the comparation is done.</param> /// <param name="ignoreCase">When set to true, all characters are converted to their lowercase equivivalence before the comparation is done.</param> /// <returns>Returns a array of DiffItems that describe the differences.</returns> public static DiffItem [] DiffText(Hashtable h, string[] LinesA, string[] LinesB, bool trimSpace, bool ignoreSpace, bool ignoreCase) { // The A-Version of the data (original data) to be compared. // strip off all cr, only use lf as textline separator. DiffData DataA = new DiffData(DiffCodes(LinesA, h, trimSpace, ignoreSpace, ignoreCase)); // The B-Version of the data (modified data) to be compared. DiffData DataB = new DiffData(DiffCodes(LinesB, h, trimSpace, ignoreSpace, ignoreCase)); LCS(DataA, 0, DataA.Length, DataB, 0, DataB.Length); return CreateDiffs(DataA, DataB); } /// <summary> /// Find the difference in 2 arrays of integers. /// </summary> /// <param name="ArrayA">A-version of the numbers (usualy the old one)</param> /// <param name="ArrayB">B-version of the numbers (usualy the new one)</param> /// <returns>Returns a array of DiffItems that describe the differences.</returns> public static DiffItem [] DiffInt(int[] ArrayA, int[] ArrayB) { // The A-Version of the data (original data) to be compared. DiffData DataA = new DiffData(ArrayA); // The B-Version of the data (modified data) to be compared. DiffData DataB = new DiffData(ArrayB); LCS(DataA, 0, DataA.Length, DataB, 0, DataB.Length); return CreateDiffs(DataA, DataB); } // Diff /// <summary> /// This function converts all textlines of the text into unique numbers for every unique textline /// so further work can work only with simple numbers. /// </summary> /// <param name="aText">the input text</param> /// <param name="h">This extern initialized hashtable is used for storing all ever used textlines.</param> /// <param name="trimSpace">ignore leading and trailing space characters</param> /// <returns>a array of integers.</returns> private static int[] DiffCodes(string[] Lines, Hashtable h, bool trimSpace, bool ignoreSpace, bool ignoreCase) { // get all codes of the text int []Codes; int lastUsedCode = h.Count; object aCode; string s; Codes = new int[Lines.Length]; for (int i = 0; i < Lines.Length; ++i) { s = Lines[i]; if (trimSpace) s = s.Trim(); if (ignoreSpace) { s = Regex.Replace(s, "\\s+", " "); // TODO: optimization: faster blank removal. } if (ignoreCase) s = s.ToLower(); aCode = h[s]; if (aCode == null) { lastUsedCode++; h[s] = lastUsedCode; Codes[i] = lastUsedCode; } else { Codes[i] = (int)aCode; } // if } // for return(Codes); } // DiffCodes /// <summary> /// This is the algorithm to find the Shortest Middle Snake (SMS). /// </summary> /// <param name="DataA">sequence A</param> /// <param name="LowerA">lower bound of the actual range in DataA</param> /// <param name="UpperA">upper bound of the actual range in DataA (exclusive)</param> /// <param name="DataB">sequence B</param> /// <param name="LowerB">lower bound of the actual range in DataB</param> /// <param name="UpperB">upper bound of the actual range in DataB (exclusive)</param> /// <returns>a MiddleSnakeData record containing x,y and u,v</returns> private static SMSRD SMS(DiffData DataA, int LowerA, int UpperA, DiffData DataB, int LowerB, int UpperB) { SMSRD ret; int MAX = DataA.Length + DataB.Length + 1; int DownK = LowerA - LowerB; // the k-line to start the forward search int UpK = UpperA - UpperB; // the k-line to start the reverse search int Delta = (UpperA - LowerA) - (UpperB - LowerB); bool oddDelta = (Delta & 1) != 0; /// vector for the (0,0) to (x,y) search int[] DownVector = new int[2* MAX + 2]; /// vector for the (u,v) to (N,M) search int[] UpVector = new int[2 * MAX + 2]; // The vectors in the publication accepts negative indexes. the vectors implemented here are 0-based // and are access using a specific offset: UpOffset UpVector and DownOffset for DownVektor int DownOffset = MAX - DownK; int UpOffset = MAX - UpK; int MaxD = ((UpperA - LowerA + UpperB - LowerB) / 2) + 1; // Debug.Write(2, "SMS", String.Format("Search the box: A[{0}-{1}] to B[{2}-{3}]", LowerA, UpperA, LowerB, UpperB)); // init vectors DownVector[DownOffset + DownK + 1] = LowerA; UpVector[UpOffset + UpK - 1] = UpperA; for (int D = 0; D <= MaxD; D++) { // Extend the forward path. for (int k = DownK - D; k <= DownK + D; k += 2) { // Debug.Write(0, "SMS", "extend forward path " + k.ToString()); // find the only or better starting point int x, y; if (k == DownK - D) { x = DownVector[DownOffset + k+1]; // down } else { x = DownVector[DownOffset + k-1] + 1; // a step to the right if ((k < DownK + D) && (DownVector[DownOffset + k+1] >= x)) x = DownVector[DownOffset + k+1]; // down } y = x - k; // find the end of the furthest reaching forward D-path in diagonal k. while ((x < UpperA) && (y < UpperB) && (DataA.data[x] == DataB.data[y])) { x++; y++; } DownVector[DownOffset + k] = x; // overlap ? if (oddDelta && (UpK-D < k) && (k < UpK+D)) { if (UpVector[UpOffset + k] <= DownVector[DownOffset + k]) { ret.x = DownVector[DownOffset + k]; ret.y = DownVector[DownOffset + k] - k; // ret.u = UpVector[UpOffset + k]; // 2002.09.20: no need for 2 points // ret.v = UpVector[UpOffset + k] - k; return (ret); } // if } // if } // for k // Extend the reverse path. for (int k = UpK - D; k <= UpK + D; k += 2) { // Debug.Write(0, "SMS", "extend reverse path " + k.ToString()); // find the only or better starting point int x, y; if (k == UpK + D) { x = UpVector[UpOffset + k-1]; // up } else { x = UpVector[UpOffset + k+1] - 1; // left if ((k > UpK - D) && (UpVector[UpOffset + k-1] < x)) x = UpVector[UpOffset + k-1]; // up } // if y = x - k; while ((x > LowerA) && (y > LowerB) && (DataA.data[x-1] == DataB.data[y-1])) { x--; y--; // diagonal } UpVector[UpOffset + k] = x; // overlap ? if (! oddDelta && (DownK-D <= k) && (k <= DownK+D)) { if (UpVector[UpOffset + k] <= DownVector[DownOffset + k]) { ret.x = DownVector[DownOffset + k]; ret.y = DownVector[DownOffset + k] - k; // ret.u = UpVector[UpOffset + k]; // 2002.09.20: no need for 2 points // ret.v = UpVector[UpOffset + k] - k; return (ret); } // if } // if } // for k } // for D throw new ApplicationException("the algorithm should never come here."); } // SMS /// <summary> /// This is the divide-and-conquer implementation of the longes common-subsequence (LCS) /// algorithm. /// The published algorithm passes recursively parts of the A and B sequences. /// To avoid copying these arrays the lower and upper bounds are passed while the sequences stay constant. /// </summary> /// <param name="DataA">sequence A</param> /// <param name="LowerA">lower bound of the actual range in DataA</param> /// <param name="UpperA">upper bound of the actual range in DataA (exclusive)</param> /// <param name="DataB">sequence B</param> /// <param name="LowerB">lower bound of the actual range in DataB</param> /// <param name="UpperB">upper bound of the actual range in DataB (exclusive)</param> private static void LCS(DiffData DataA, int LowerA, int UpperA, DiffData DataB, int LowerB, int UpperB) { // Debug.Write(2, "LCS", String.Format("Analyse the box: A[{0}-{1}] to B[{2}-{3}]", LowerA, UpperA, LowerB, UpperB)); // Fast walkthrough equal lines at the start while (LowerA < UpperA && LowerB < UpperB && DataA.data[LowerA] == DataB.data[LowerB]) { LowerA++; LowerB++; } // Fast walkthrough equal lines at the end while (LowerA < UpperA && LowerB < UpperB && DataA.data[UpperA-1] == DataB.data[UpperB-1]) { --UpperA; --UpperB; } if (LowerA == UpperA) { // mark as inserted lines. while (LowerB < UpperB) DataB.modified[LowerB++] = true; } else if (LowerB == UpperB) { // mark as deleted lines. while (LowerA < UpperA) DataA.modified[LowerA++] = true; } else { // Find the middle snakea and length of an optimal path for A and B SMSRD smsrd = SMS(DataA, LowerA, UpperA, DataB, LowerB, UpperB); // Debug.Write(2, "MiddleSnakeData", String.Format("{0},{1}", smsrd.x, smsrd.y)); // The path is from LowerX to (x,y) and (x,y) ot UpperX LCS(DataA, LowerA, smsrd.x, DataB, LowerB, smsrd.y); LCS(DataA, smsrd.x, UpperA, DataB, smsrd.y, UpperB); // 2002.09.20: no need for 2 points } } // LCS() /// <summary>Scan the tables of which lines are inserted and deleted, /// producing an edit script in forward order. /// </summary> /// dynamic array private static DiffItem[] CreateDiffs(DiffData DataA, DiffData DataB) { ArrayList a = new ArrayList(); DiffItem aItem; DiffItem []result; int StartA, StartB; int LineA, LineB; LineA = 0; LineB = 0; while (LineA < DataA.Length || LineB < DataB.Length) { if ((LineA < DataA.Length) && (! DataA.modified[LineA]) && (LineB < DataB.Length) && (! DataB.modified[LineB])) { // equal lines LineA++; LineB++; } else { // maybe deleted and/or inserted lines StartA = LineA; StartB = LineB; while (LineA < DataA.Length && (LineB >= DataB.Length || DataA.modified[LineA])) // while (LineA < DataA.Length && DataA.modified[LineA]) LineA++; while (LineB < DataB.Length && (LineA >= DataA.Length || DataB.modified[LineB])) // while (LineB < DataB.Length && DataB.modified[LineB]) LineB++; if ((StartA < LineA) || (StartB < LineB)) { // store a new difference-item aItem = new DiffItem(); aItem.StartA = StartA; aItem.StartB = StartB; aItem.deletedA = LineA - StartA; aItem.insertedB = LineB - StartB; a.Add(aItem); } // if } // if } // while result = new DiffItem[a.Count]; a.CopyTo(result); return (result); } } // class Diff /// <summary>Data on one input file being compared. /// </summary> internal class DiffData { /// <summary>Number of elements (lines).</summary> internal int Length; /// <summary>Buffer of numbers that will be compared.</summary> internal int[] data; /// <summary> /// Array of booleans that flag for modified data. /// This is the result of the diff. /// This means deletedA in the first Data or inserted in the second Data. /// </summary> internal bool[] modified; /// <summary> /// Initialize the Diff-Data buffer. /// </summary> /// <param name="data">reference to the buffer</param> internal DiffData(int[] initData) { data = initData; Length = initData.Length; modified = new bool[Length + 2]; } // DiffData } // class DiffData } // namespace
using System; using System.Diagnostics; using System.Text; using i64 = System.Int64; using u8 = System.Byte; using u32 = System.UInt32; using Pgno = System.UInt32; namespace System.Data.SQLite { using sqlite3_int64 = System.Int64; using DbPage = Sqlite3.PgHdr; internal partial class Sqlite3 { /* ** 2009 January 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the implementation of the sqlite3_backup_XXX() ** API functions and the related features. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ //#include "sqliteInt.h" //#include "btreeInt.h" /* Macro to find the minimum of two numeric values. */ #if !MIN //# define MIN(x,y) ((x)<(y)?(x):(y)) #endif /* ** Structure allocated for each backup operation. */ public class sqlite3_backup { /// <summary> /// Destination database handle /// </summary> public sqlite3 pDestDb; /// <summary> /// The destination b-tree file. /// </summary> public Btree pDest; /// <summary> /// Original schema cookie in destination. /// </summary> public u32 iDestSchema; /// <summary> /// true one a write-transation is open on <see cref="pDestDb"/> /// </summary> public int bDestLocked; /// <summary> /// Page number of the next source page to copy. /// </summary> public Pgno iNext; /// <summary> /// Source database handle /// </summary> public sqlite3 pSrcDb; /// <summary> /// Source b-tree file. /// </summary> public Btree pSrc; /// <summary> /// Backup process error code. /// </summary> public int rc; /* These two variables are set by every call to backup_step(). They are ** read by calls to backup_remaining() and backup_pagecount(). */ /// <summary> /// The number of pages left to copy /// </summary> public Pgno nRemaining; /// <summary> /// total number of pages to copy. /// </summary> public Pgno nPagecount; /// <summary> /// True once backup has been registered wiht pager /// </summary> public int isAttached; /// <summary> /// Next backup associated with source pager /// </summary> public sqlite3_backup pNext; }; /* ** THREAD SAFETY NOTES: ** ** Once it has been created using backup_init(), a single sqlite3_backup ** structure may be accessed via two groups of thread-safe entry points: ** ** * Via the sqlite3_backup_XXX() API function backup_step() and ** backup_finish(). Both these functions obtain the source database ** handle mutex and the mutex associated with the source BtShared ** structure, in that order. ** ** * Via the BackupUpdate() and BackupRestart() functions, which are ** invoked by the pager layer to report various state changes in ** the page cache associated with the source database. The mutex ** associated with the source database BtShared structure will always ** be held when either of these functions are invoked. ** ** The other sqlite3_backup_XXX() API functions, backup_remaining() and ** backup_pagecount() are not thread-safe functions. If they are called ** while some other thread is calling backup_step() or backup_finish(), ** the values returned may be invalid. There is no way for a call to ** BackupUpdate() or BackupRestart() to interfere with backup_remaining() ** or backup_pagecount(). ** ** Depending on the SQLite configuration, the database handles and/or ** the Btree objects may have their own mutexes that require locking. ** Non-sharable Btrees (in-memory databases for example), do not have ** associated mutexes. */ /// <summary> /// Return a pointer corresponding to database zDb (i.e. "main", "temp") /// in connection handle pDb. If such a database cannot be found, return /// a NULL pointer and write an error message to pErrorDb. /// /// If the "temp" database is requested, it may need to be opened by this /// function. If an error occurs while doing so, return 0 and write an /// error message to pErrorDb. /// </summary> static Btree findBtree(sqlite3 pErrorDb, sqlite3 pDb, string zDb) { int i = sqlite3FindDbName(pDb, zDb); if (i == 1) { Parse pParse; int rc = 0; pParse = new Parse();//sqlite3StackAllocZero(pErrorDb, sizeof(*pParse)); if (pParse == null) { sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory"); rc = SQLITE_NOMEM; } else { pParse.db = pDb; if (sqlite3OpenTempDatabase(pParse) != 0) { sqlite3Error(pErrorDb, pParse.rc, "%s", pParse.zErrMsg); rc = SQLITE_ERROR; } sqlite3DbFree(pErrorDb, ref pParse.zErrMsg); //sqlite3StackFree( pErrorDb, pParse ); } if (rc != 0) { return null; } } if (i < 0) { sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb); return null; } return pDb.aDb[i].pBt; } /// <summary> /// Attempt to set the page size of the destination to match the page size /// of the source. /// </summary> static int setDestPgsz(sqlite3_backup p) { int rc; rc = sqlite3BtreeSetPageSize(p.pDest, sqlite3BtreeGetPageSize(p.pSrc), -1, 0); return rc; } /// <summary> /// Create an sqlite3_backup process to copy the contents of zSrcDb from /// connection handle pSrcDb to zDestDb in pDestDb. If successful, return /// a pointer to the new sqlite3_backup object. /// /// If an error occurs, NULL is returned and an error code and error message /// stored in database handle pDestDb. /// </summary> /// <param name='pDestDb'> /// Database to write to /// </param> /// <param name='zDestDb'> /// Name of database within <see cref="pDestDb"/> /// </param> /// <param name='pSrcDb'> /// Database connection to read from /// </param> /// <param name='zSrcDb'> /// Name of database within <see cref="pSrcDb"/> /// </param> static public sqlite3_backup sqlite3_backup_init(sqlite3 pDestDb, string zDestDb, sqlite3 pSrcDb, string zSrcDb) { sqlite3_backup p; /* Value to return */ /* Lock the source database handle. The destination database ** handle is not locked in this routine, but it is locked in ** sqlite3_backup_step(). The user is required to ensure that no ** other thread accesses the destination handle for the duration ** of the backup operation. Any attempt to use the destination ** database connection while a backup is in progress may cause ** a malfunction or a deadlock. */ sqlite3_mutex_enter(pSrcDb.mutex); sqlite3_mutex_enter(pDestDb.mutex); if (pSrcDb == pDestDb) { sqlite3Error( pDestDb, SQLITE_ERROR, "source and destination must be distinct" ); p = null; } else { /* Allocate space for a new sqlite3_backup object... ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a ** call to sqlite3_backup_init() and is destroyed by a call to ** sqlite3_backup_finish(). */ p = new sqlite3_backup();// (sqlite3_backup)sqlite3_malloc( sizeof( sqlite3_backup ) ); //if ( null == p ) //{ // sqlite3Error( pDestDb, SQLITE_NOMEM, 0 ); //} } /* If the allocation succeeded, populate the new object. */ if (p != null) { // memset( p, 0, sizeof( sqlite3_backup ) ); p.pSrc = findBtree(pDestDb, pSrcDb, zSrcDb); p.pDest = findBtree(pDestDb, pDestDb, zDestDb); p.pDestDb = pDestDb; p.pSrcDb = pSrcDb; p.iNext = 1; p.isAttached = 0; if (null == p.pSrc || null == p.pDest || setDestPgsz(p) == SQLITE_NOMEM) { /* One (or both) of the named databases did not exist or an OOM ** error was hit. The error has already been written into the ** pDestDb handle. All that is left to do here is free the ** sqlite3_backup structure. */ //sqlite3_free( ref p ); p = null; } } if (p != null) { p.pSrc.nBackup++; } sqlite3_mutex_leave(pDestDb.mutex); sqlite3_mutex_leave(pSrcDb.mutex); return p; } /// <summary> /// Argument rc is an SQLite error code. Return true if this error is /// considered fatal if encountered during a backup operation. All errors /// are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED. /// </summary> static bool isFatalError(int rc) { return (rc != SQLITE_OK && rc != SQLITE_BUSY && ALWAYS(rc != SQLITE_LOCKED)); } /// <summary> /// Parameter zSrcData points to a buffer containing the data for /// page iSrcPg from the source database. Copy this data into the /// destination database. /// </summary> static int backupOnePage(sqlite3_backup p, Pgno iSrcPg, byte[] zSrcData) { Pager pDestPager = sqlite3BtreePager(p.pDest); int nSrcPgsz = sqlite3BtreeGetPageSize(p.pSrc); int nDestPgsz = sqlite3BtreeGetPageSize(p.pDest); int nCopy = MIN(nSrcPgsz, nDestPgsz); i64 iEnd = (i64)iSrcPg * (i64)nSrcPgsz; #if SQLITE_HAS_CODEC int nSrcReserve = sqlite3BtreeGetReserve(p.pSrc); int nDestReserve = sqlite3BtreeGetReserve(p.pDest); #endif int rc = SQLITE_OK; i64 iOff; Debug.Assert(p.bDestLocked != 0); Debug.Assert(!isFatalError(p.rc)); Debug.Assert(iSrcPg != PENDING_BYTE_PAGE(p.pSrc.pBt)); Debug.Assert(zSrcData != null); /* Catch the case where the destination is an in-memory database and the ** page sizes of the source and destination differ. */ if (nSrcPgsz != nDestPgsz && sqlite3PagerIsMemdb(pDestPager)) { rc = SQLITE_READONLY; } #if SQLITE_HAS_CODEC /* Backup is not possible if the page size of the destination is changing ** and a codec is in use. */ if ( nSrcPgsz != nDestPgsz && sqlite3PagerGetCodec( pDestPager ) != null ) { rc = SQLITE_READONLY; } /* Backup is not possible if the number of bytes of reserve space differ ** between source and destination. If there is a difference, try to ** fix the destination to agree with the source. If that is not possible, ** then the backup cannot proceed. */ if ( nSrcReserve != nDestReserve ) { u32 newPgsz = (u32)nSrcPgsz; rc = sqlite3PagerSetPagesize( pDestPager, ref newPgsz, nSrcReserve ); if ( rc == SQLITE_OK && newPgsz != nSrcPgsz ) rc = SQLITE_READONLY; } #endif /* This loop runs once for each destination page spanned by the source ** page. For each iteration, variable iOff is set to the byte offset ** of the destination page. */ for (iOff = iEnd - (i64)nSrcPgsz; rc == SQLITE_OK && iOff < iEnd; iOff += nDestPgsz) { DbPage pDestPg = null; u32 iDest = (u32)(iOff / nDestPgsz) + 1; if (iDest == PENDING_BYTE_PAGE(p.pDest.pBt)) continue; if (SQLITE_OK == (rc = sqlite3PagerGet(pDestPager, iDest, ref pDestPg)) && SQLITE_OK == (rc = sqlite3PagerWrite(pDestPg)) ) { //string zIn = &zSrcData[iOff%nSrcPgsz]; byte[] zDestData = sqlite3PagerGetData(pDestPg); //string zOut = &zDestData[iOff % nDestPgsz]; /* Copy the data from the source page into the destination page. ** Then clear the Btree layer MemPage.isInit flag. Both this module ** and the pager code use this trick (clearing the first byte ** of the page 'extra' space to invalidate the Btree layers ** cached parse of the page). MemPage.isInit is marked ** "MUST BE FIRST" for this purpose. */ Buffer.BlockCopy(zSrcData, (int)(iOff % nSrcPgsz), zDestData, (int)(iOff % nDestPgsz), nCopy);// memcpy( zOut, zIn, nCopy ); sqlite3PagerGetExtra(pDestPg).isInit = 0;// ( sqlite3PagerGetExtra( pDestPg ) )[0] = 0; } sqlite3PagerUnref(pDestPg); } return rc; } /// <summary> /// If pFile is currently larger than iSize bytes, then truncate it to /// exactly iSize bytes. If pFile is not larger than iSize bytes, then /// this function is a no-op. /// /// Return SQLITE_OK if everything is successful, or an SQLite error /// code if an error occurs. /// </summary> static int backupTruncateFile(sqlite3_file pFile, int iSize) { long iCurrent = 0; int rc = sqlite3OsFileSize(pFile, ref iCurrent); if (rc == SQLITE_OK && iCurrent > iSize) { rc = sqlite3OsTruncate(pFile, iSize); } return rc; } /// <summary> /// Register this backup object with the associated source pager for /// callbacks when pages are changed or the cache invalidated. /// </summary> static void attachBackupObject(sqlite3_backup p) { sqlite3_backup pp; Debug.Assert(sqlite3BtreeHoldsMutex(p.pSrc)); pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p.pSrc)); p.pNext = pp; sqlite3BtreePager(p.pSrc).pBackup = p; //*pp = p; p.isAttached = 1; } /// <summary> /// Copy nPage pages from the source b-tree to the destination. /// </summary> static public int sqlite3_backup_step(sqlite3_backup p, int nPage) { int rc; int destMode; /* Destination journal mode */ int pgszSrc = 0; /* Source page size */ int pgszDest = 0; /* Destination page size */ sqlite3_mutex_enter(p.pSrcDb.mutex); sqlite3BtreeEnter(p.pSrc); if (p.pDestDb != null) { sqlite3_mutex_enter(p.pDestDb.mutex); } rc = p.rc; if (!isFatalError(rc)) { Pager pSrcPager = sqlite3BtreePager(p.pSrc); /* Source pager */ Pager pDestPager = sqlite3BtreePager(p.pDest); /* Dest pager */ int ii; /* Iterator variable */ Pgno nSrcPage = 0; /* Size of source db in pages */ int bCloseTrans = 0; /* True if src db requires unlocking */ /* If the source pager is currently in a write-transaction, return ** SQLITE_BUSY immediately. */ if (p.pDestDb != null && p.pSrc.pBt.inTransaction == TRANS_WRITE) { rc = SQLITE_BUSY; } else { rc = SQLITE_OK; } /* Lock the destination database, if it is not locked already. */ if (SQLITE_OK == rc && p.bDestLocked == 0 && SQLITE_OK == (rc = sqlite3BtreeBeginTrans(p.pDest, 2)) ) { p.bDestLocked = 1; sqlite3BtreeGetMeta(p.pDest, BTREE_SCHEMA_VERSION, ref p.iDestSchema); } /* If there is no open read-transaction on the source database, open ** one now. If a transaction is opened here, then it will be closed ** before this function exits. */ if (rc == SQLITE_OK && !sqlite3BtreeIsInReadTrans(p.pSrc)) { rc = sqlite3BtreeBeginTrans(p.pSrc, 0); bCloseTrans = 1; } /* Do not allow backup if the destination database is in WAL mode ** and the page sizes are different between source and destination */ pgszSrc = sqlite3BtreeGetPageSize(p.pSrc); pgszDest = sqlite3BtreeGetPageSize(p.pDest); destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p.pDest)); if (SQLITE_OK == rc && destMode == PAGER_JOURNALMODE_WAL && pgszSrc != pgszDest) { rc = SQLITE_READONLY; } /* Now that there is a read-lock on the source database, query the ** source pager for the number of pages in the database. */ nSrcPage = sqlite3BtreeLastPage(p.pSrc); Debug.Assert(nSrcPage >= 0); for (ii = 0; (nPage < 0 || ii < nPage) && p.iNext <= nSrcPage && 0 == rc; ii++) { Pgno iSrcPg = p.iNext; /* Source page number */ if (iSrcPg != PENDING_BYTE_PAGE(p.pSrc.pBt)) { DbPage pSrcPg = null; /* Source page object */ rc = sqlite3PagerGet(pSrcPager, (u32)iSrcPg, ref pSrcPg); if (rc == SQLITE_OK) { rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg)); sqlite3PagerUnref(pSrcPg); } } p.iNext++; } if (rc == SQLITE_OK) { p.nPagecount = nSrcPage; p.nRemaining = (nSrcPage + 1 - p.iNext); if (p.iNext > nSrcPage) { rc = SQLITE_DONE; } else if (0 == p.isAttached) { attachBackupObject(p); } } /* Update the schema version field in the destination database. This ** is to make sure that the schema-version really does change in ** the case where the source and destination databases have the ** same schema version. */ if (rc == SQLITE_DONE && (rc = sqlite3BtreeUpdateMeta(p.pDest, 1, p.iDestSchema + 1)) == SQLITE_OK ) { Pgno nDestTruncate; if (p.pDestDb != null) { sqlite3ResetInternalSchema(p.pDestDb, -1); } /* Set nDestTruncate to the final number of pages in the destination ** database. The complication here is that the destination page ** size may be different to the source page size. ** ** If the source page size is smaller than the destination page size, ** round up. In this case the call to sqlite3OsTruncate() below will ** fix the size of the file. However it is important to call ** sqlite3PagerTruncateImage() here so that any pages in the ** destination file that lie beyond the nDestTruncate page mark are ** journalled by PagerCommitPhaseOne() before they are destroyed ** by the file truncation. */ Debug.Assert(pgszSrc == sqlite3BtreeGetPageSize(p.pSrc)); Debug.Assert(pgszDest == sqlite3BtreeGetPageSize(p.pDest)); if (pgszSrc < pgszDest) { int ratio = pgszDest / pgszSrc; nDestTruncate = (Pgno)((nSrcPage + ratio - 1) / ratio); if (nDestTruncate == (int)PENDING_BYTE_PAGE(p.pDest.pBt)) { nDestTruncate--; } } else { nDestTruncate = (Pgno)(nSrcPage * (pgszSrc / pgszDest)); } sqlite3PagerTruncateImage(pDestPager, nDestTruncate); if (pgszSrc < pgszDest) { /* If the source page-size is smaller than the destination page-size, ** two extra things may need to happen: ** ** * The destination may need to be truncated, and ** ** * Data stored on the pages immediately following the ** pending-byte page in the source database may need to be ** copied into the destination database. */ int iSize = (int)(pgszSrc * nSrcPage); sqlite3_file pFile = sqlite3PagerFile(pDestPager); i64 iOff; i64 iEnd; Debug.Assert(pFile != null); Debug.Assert((i64)nDestTruncate * (i64)pgszDest >= iSize || ( nDestTruncate == (int)(PENDING_BYTE_PAGE(p.pDest.pBt) - 1) && iSize >= PENDING_BYTE && iSize <= PENDING_BYTE + pgszDest )); /* This call ensures that all data required to recreate the original ** database has been stored in the journal for pDestPager and the ** journal synced to disk. So at this point we may safely modify ** the database file in any way, knowing that if a power failure ** occurs, the original database will be reconstructed from the ** journal file. */ rc = sqlite3PagerCommitPhaseOne(pDestPager, null, true); /* Write the extra pages and truncate the database file as required. */ iEnd = MIN(PENDING_BYTE + pgszDest, iSize); for ( iOff = PENDING_BYTE + pgszSrc; rc == SQLITE_OK && iOff < iEnd; iOff += pgszSrc ) { PgHdr pSrcPg = null; u32 iSrcPg = (u32)((iOff / pgszSrc) + 1); rc = sqlite3PagerGet(pSrcPager, iSrcPg, ref pSrcPg); if (rc == SQLITE_OK) { byte[] zData = sqlite3PagerGetData(pSrcPg); rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff); } sqlite3PagerUnref(pSrcPg); } if (rc == SQLITE_OK) { rc = backupTruncateFile(pFile, (int)iSize); } /* Sync the database file to disk. */ if (rc == SQLITE_OK) { rc = sqlite3PagerSync(pDestPager); } } else { rc = sqlite3PagerCommitPhaseOne(pDestPager, null, false); } /* Finish committing the transaction to the destination database. */ if (SQLITE_OK == rc && SQLITE_OK == (rc = sqlite3BtreeCommitPhaseTwo(p.pDest, 0)) ) { rc = SQLITE_DONE; } } /* If bCloseTrans is true, then this function opened a read transaction ** on the source database. Close the read transaction here. There is ** no need to check the return values of the btree methods here, as ** "committing" a read-only transaction cannot fail. */ if (bCloseTrans != 0) { #if !NDEBUG || SQLITE_COVERAGE_TEST //TESTONLY( int rc2 ); //TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p.pSrc, 0); //TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p.pSrc); int rc2; rc2 = sqlite3BtreeCommitPhaseOne( p.pSrc, "" ); rc2 |= sqlite3BtreeCommitPhaseTwo( p.pSrc, 0 ); Debug.Assert( rc2 == SQLITE_OK ); #else sqlite3BtreeCommitPhaseOne(p.pSrc, null); sqlite3BtreeCommitPhaseTwo(p.pSrc, 0); #endif } if (rc == SQLITE_IOERR_NOMEM) { rc = SQLITE_NOMEM; } p.rc = rc; } if (p.pDestDb != null) { sqlite3_mutex_leave(p.pDestDb.mutex); } sqlite3BtreeLeave(p.pSrc); sqlite3_mutex_leave(p.pSrcDb.mutex); return rc; } /// <summary> /// Release all resources associated with an sqlite3_backup* handle. /// </summary> static public int sqlite3_backup_finish(sqlite3_backup p) { sqlite3_backup pp; /* Ptr to head of pagers backup list */ sqlite3_mutex mutex; /* Mutex to protect source database */ int rc; /* Value to return */ /* Enter the mutexes */ if (p == null) return SQLITE_OK; sqlite3_mutex_enter(p.pSrcDb.mutex); sqlite3BtreeEnter(p.pSrc); mutex = p.pSrcDb.mutex; if (p.pDestDb != null) { sqlite3_mutex_enter(p.pDestDb.mutex); } /* Detach this backup from the source pager. */ if (p.pDestDb != null) { p.pSrc.nBackup--; } if (p.isAttached != 0) { pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p.pSrc)); while (pp != p) { pp = (pp).pNext; } sqlite3BtreePager(p.pSrc).pBackup = p.pNext; } /* If a transaction is still open on the Btree, roll it back. */ sqlite3BtreeRollback(p.pDest); /* Set the error code of the destination database handle. */ rc = (p.rc == SQLITE_DONE) ? SQLITE_OK : p.rc; sqlite3Error(p.pDestDb, rc, 0); /* Exit the mutexes and free the backup context structure. */ if (p.pDestDb != null) { sqlite3_mutex_leave(p.pDestDb.mutex); } sqlite3BtreeLeave(p.pSrc); if (p.pDestDb != null) { /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a ** call to sqlite3_backup_init() and is destroyed by a call to ** sqlite3_backup_finish(). */ //sqlite3_free( ref p ); } sqlite3_mutex_leave(mutex); return rc; } /// <summary> /// Return the number of pages still to be backed up as of the most recent /// call to sqlite3_backup_step(). /// </summary> static int sqlite3_backup_remaining(sqlite3_backup p) { return (int)p.nRemaining; } /// <summary> /// Return the total number of pages in the source database as of the most /// recent call to sqlite3_backup_step(). /// </summary> static int sqlite3_backup_pagecount(sqlite3_backup p) { return (int)p.nPagecount; } /// <summary> /// This function is called after the contents of page iPage of the /// source database have been modified. If page iPage has already been /// copied into the destination database, then the data written to the /// destination is now invalidated. The destination copy of iPage needs /// to be updated with the new data before the backup operation is /// complete. /// /// It is assumed that the mutex associated with the BtShared object /// corresponding to the source database is held when this function is /// called. /// </summary> static void sqlite3BackupUpdate(sqlite3_backup pBackup, Pgno iPage, byte[] aData) { sqlite3_backup p; /* Iterator variable */ for (p = pBackup; p != null; p = p.pNext) { Debug.Assert(sqlite3_mutex_held(p.pSrc.pBt.mutex)); if (!isFatalError(p.rc) && iPage < p.iNext) { /* The backup process p has already copied page iPage. But now it ** has been modified by a transaction on the source pager. Copy ** the new data into the backup. */ int rc; Debug.Assert(p.pDestDb != null); sqlite3_mutex_enter(p.pDestDb.mutex); rc = backupOnePage(p, iPage, aData); sqlite3_mutex_leave(p.pDestDb.mutex); Debug.Assert(rc != SQLITE_BUSY && rc != SQLITE_LOCKED); if (rc != SQLITE_OK) { p.rc = rc; } } } } /// <summary> /// Restart the backup process. This is called when the pager layer /// detects that the database has been modified by an external database /// connection. In this case there is no way of knowing which of the /// pages that have been copied into the destination database are still /// valid and which are not, so the entire process needs to be restarted. /// /// It is assumed that the mutex associated with the BtShared object /// corresponding to the source database is held when this function is /// called. /// </summary> static void sqlite3BackupRestart(sqlite3_backup pBackup) { sqlite3_backup p; /* Iterator variable */ for (p = pBackup; p != null; p = p.pNext) { Debug.Assert(sqlite3_mutex_held(p.pSrc.pBt.mutex)); p.iNext = 1; } } #if !SQLITE_OMIT_VACUUM /// <summary> /// Copy the complete content of pBtFrom into pBtTo. A transaction /// must be active for both files. /// /// The size of file pTo may be reduced by this operation. If anything /// goes wrong, the transaction on pTo is rolled back. If successful, the /// transaction is committed before returning. /// </summary> static int sqlite3BtreeCopyFile(Btree pTo, Btree pFrom) { int rc; sqlite3_backup b; sqlite3BtreeEnter(pTo); sqlite3BtreeEnter(pFrom); /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set ** to 0. This is used by the implementations of sqlite3_backup_step() ** and sqlite3_backup_finish() to detect that they are being called ** from this function, not directly by the user. */ b = new sqlite3_backup();// memset( &b, 0, sizeof( b ) ); b.pSrcDb = pFrom.db; b.pSrc = pFrom; b.pDest = pTo; b.iNext = 1; /* 0x7FFFFFFF is the hard limit for the number of pages in a database ** file. By passing this as the number of pages to copy to ** sqlite3_backup_step(), we can guarantee that the copy finishes ** within a single call (unless an error occurs). The Debug.Assert() statement ** checks this assumption - (p.rc) should be set to either SQLITE_DONE ** or an error code. */ sqlite3_backup_step(b, 0x7FFFFFFF); Debug.Assert(b.rc != SQLITE_OK); rc = sqlite3_backup_finish(b); if (rc == SQLITE_OK) { pTo.pBt.pageSizeFixed = false; } sqlite3BtreeLeave(pFrom); sqlite3BtreeLeave(pTo); return rc; } #endif //* SQLITE_OMIT_VACUUM */ } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Web; using ASC.CRM.Core; using ASC.CRM.Core.Entities; using ASC.Web.CRM.Controls.Settings; using ASC.Web.CRM.Resources; using ASC.Web.Studio.Utility; namespace ASC.Web.CRM { public partial class Settings : BasePage { protected string PageTitle { get; private set; } protected bool IsInvoiceItemsList { get; private set; } protected override void PageLoad() { if (!CRMSecurity.IsAdmin) Response.Redirect(PathProvider.StartURL()); Page.RegisterBodyScripts(PathProvider.GetFileStaticRelativePath, "settings.js", "settings.invoices.js" ); var typeValue = (HttpContext.Current.Request["type"] ?? "common").ToLower(); ListItemView listItemViewControl; var headerView = (SettingsHeaderView)LoadControl(SettingsHeaderView.Location); switch (typeValue) { case "common": PageTitle = CRMSettingResource.CommonSettings; headerView.HeaderText = CRMSettingResource.ExportData; TitleContentHolder.Controls.Add(headerView); CommonContainerHolder.Controls.Add(LoadControl(CommonSettingsView.Location)); break; case "currency": PageTitle = CRMSettingResource.CurrencySettings; headerView.HeaderText = PageTitle; TitleContentHolder.Controls.Add(headerView); CommonContainerHolder.Controls.Add(LoadControl(CurrencySettingsView.Location)); break; case "deal_milestone": PageTitle = CRMDealResource.DealMilestone; headerView.HeaderText = PageTitle; headerView.DescriptionText = CRMSettingResource.DescriptionTextDealMilestone; headerView.DescriptionTextEditDelete = CRMSettingResource.DescriptionTextDealMilestoneEditDelete; headerView.AddListButtonId = "createNewDealMilestone"; headerView.AddListButtonText = CRMSettingResource.CreateNewDealMilestoneListButton; TitleContentHolder.Controls.Add(headerView); CommonContainerHolder.Controls.Add(LoadControl(DealMilestoneView.Location)); break; case "task_category": PageTitle = CRMTaskResource.TaskCategories; headerView.HeaderText = PageTitle; headerView.DescriptionText = CRMSettingResource.DescriptionTextTaskCategory; headerView.DescriptionTextEditDelete = CRMSettingResource.DescriptionTextTaskCategoryEditDelete; headerView.AddListButtonText = CRMSettingResource.CreateNewCategoryListButton; TitleContentHolder.Controls.Add(headerView); listItemViewControl = (ListItemView)LoadControl(ListItemView.Location); listItemViewControl.CurrentTypeValue = ListType.TaskCategory; listItemViewControl.AddButtonText = CRMSettingResource.AddThisCategory; listItemViewControl.AddPopupWindowText = CRMSettingResource.CreateNewCategory; listItemViewControl.AjaxProgressText = CRMSettingResource.CreateCategoryInProgressing; listItemViewControl.DeleteText = CRMSettingResource.DeleteCategory; listItemViewControl.EditText = CRMSettingResource.EditCategory; listItemViewControl.EditPopupWindowText = CRMSettingResource.EditSelectedCategory; CommonContainerHolder.Controls.Add(listItemViewControl); break; case "history_category": PageTitle = CRMSettingResource.HistoryCategories; headerView.HeaderText = PageTitle; headerView.DescriptionText = CRMSettingResource.DescriptionTextHistoryCategory; headerView.DescriptionTextEditDelete = CRMSettingResource.DescriptionTextHistoryCategoryEditDelete; headerView.AddListButtonText = CRMSettingResource.CreateNewCategoryListButton; TitleContentHolder.Controls.Add(headerView); listItemViewControl = (ListItemView)LoadControl(ListItemView.Location); listItemViewControl.CurrentTypeValue = ListType.HistoryCategory; listItemViewControl.AddButtonText = CRMSettingResource.AddThisCategory; listItemViewControl.AddPopupWindowText = CRMSettingResource.CreateNewCategory; listItemViewControl.AjaxProgressText = CRMSettingResource.CreateCategoryInProgressing; listItemViewControl.DeleteText = CRMSettingResource.DeleteCategory; listItemViewControl.EditText = CRMSettingResource.EditCategory; listItemViewControl.EditPopupWindowText = CRMSettingResource.EditSelectedCategory; CommonContainerHolder.Controls.Add(listItemViewControl); break; case "contact_stage": PageTitle = CRMContactResource.ContactStages; headerView.HeaderText = PageTitle; headerView.DescriptionText = CRMSettingResource.DescriptionTextContactStage; headerView.DescriptionTextEditDelete = CRMSettingResource.DescriptionTextContactStageEditDelete; headerView.AddListButtonText = CRMSettingResource.CreateNewStageListButton; headerView.ShowContactStatusAskingDialog = true; TitleContentHolder.Controls.Add(headerView); listItemViewControl = (ListItemView)LoadControl(ListItemView.Location); listItemViewControl.CurrentTypeValue = ListType.ContactStatus; listItemViewControl.AddButtonText = CRMSettingResource.AddThisStage; listItemViewControl.AddPopupWindowText = CRMSettingResource.CreateNewStage; listItemViewControl.AjaxProgressText = CRMSettingResource.CreateContactStageInProgressing; listItemViewControl.DeleteText = CRMSettingResource.DeleteContactStage; listItemViewControl.EditText = CRMSettingResource.EditContactStage; listItemViewControl.EditPopupWindowText = CRMSettingResource.EditSelectedContactStage; CommonContainerHolder.Controls.Add(listItemViewControl); break; case "contact_type": PageTitle = CRMSettingResource.ContactTypes; headerView.HeaderText = PageTitle; headerView.DescriptionText = CRMSettingResource.DescriptionTextContactType; headerView.DescriptionTextEditDelete = CRMSettingResource.DescriptionTextContactTypeEditDelete; headerView.AddListButtonText = CRMSettingResource.CreateNewContactTypeListButton; TitleContentHolder.Controls.Add(headerView); listItemViewControl = (ListItemView)LoadControl(ListItemView.Location); listItemViewControl.CurrentTypeValue = ListType.ContactType; listItemViewControl.AddButtonText = CRMSettingResource.AddThisContactType; listItemViewControl.AddPopupWindowText = CRMSettingResource.CreateNewContactType; listItemViewControl.AjaxProgressText = CRMSettingResource.CreateContactTypeInProgressing; listItemViewControl.DeleteText = CRMSettingResource.DeleteContactType; listItemViewControl.EditText = CRMSettingResource.EditContactType; listItemViewControl.EditPopupWindowText = CRMSettingResource.EditSelectedContactType; CommonContainerHolder.Controls.Add(listItemViewControl); break; case "tag": PageTitle = CRMCommonResource.Tags; headerView.HeaderText = PageTitle; headerView.TabsContainerId = "TagSettingsTabs"; headerView.AddListButtonId = "createNewTagSettings"; headerView.AddListButtonText = CRMSettingResource.CreateNewTagListButton; headerView.ShowTagAskingDialog = true; TitleContentHolder.Controls.Add(headerView); CommonContainerHolder.Controls.Add(LoadControl(TagSettingsView.Location)); break; case "web_to_lead_form": PageTitle = CRMSettingResource.WebToLeadsForm; CommonContainerHolder.Controls.Add(LoadControl(WebToLeadFormView.Location)); break; //case "task_template": // PageTitle = CRMSettingResource.TaskTemplates; // CommonContainerHolder.Controls.Add(LoadControl(TaskTemplateView.Location)); // break; case "invoice_items": var actionValue = (HttpContext.Current.Request["action"] ?? "").ToLower(); if (!String.IsNullOrEmpty(actionValue) && actionValue == "manage") { var idParam = HttpContext.Current.Request["id"]; InvoiceItem targetInvoiceItem = null; if (!String.IsNullOrEmpty(idParam)) { targetInvoiceItem = DaoFactory.InvoiceItemDao.GetByID(Convert.ToInt32(idParam)); if (targetInvoiceItem == null) { Response.Redirect(PathProvider.StartURL() + "Settings.aspx?type=invoice_items"); } } PageTitle = targetInvoiceItem == null ? CRMInvoiceResource.CreateNewInvoiceItem : String.Format(CRMInvoiceResource.UpdateInvoiceItem, targetInvoiceItem.Title); headerView.HeaderText = PageTitle; TitleContentHolder.Controls.Add(headerView); var invoiceProductsViewControl = (InvoiceItemActionView)LoadControl(InvoiceItemActionView.Location); invoiceProductsViewControl.TargetInvoiceItem = targetInvoiceItem; CommonContainerHolder.Controls.Add(invoiceProductsViewControl); } else { PageTitle = CRMCommonResource.ProductsAndServices; headerView.HeaderText = PageTitle; TitleContentHolder.Controls.Add(headerView); IsInvoiceItemsList = true; CommonContainerHolder.Controls.Add(LoadControl(InvoiceItemsView.Location)); } break; case "invoice_tax": PageTitle = CRMCommonResource.InvoiceTaxes; headerView.HeaderText = PageTitle; headerView.DescriptionText = CRMInvoiceResource.InvoiceTaxesDescriptionText; headerView.DescriptionTextEditDelete = CRMInvoiceResource.InvoiceTaxesDescriptionTextEditDelete; headerView.AddListButtonId = "createNewTax"; headerView.AddListButtonText = CRMInvoiceResource.CreateInvoiceTax; TitleContentHolder.Controls.Add(headerView); CommonContainerHolder.Controls.Add(LoadControl(InvoiceTaxesView.Location)); break; case "organisation_profile": PageTitle = CRMCommonResource.OrganisationProfile; CommonContainerHolder.Controls.Add(LoadControl(OrganisationProfile.Location)); break; case "voip.common": PageTitle = CRMCommonResource.VoIPCommonSettings; CommonContainerHolder.Controls.Add(LoadControl(VoipCommon.Location)); break; case "voip.numbers": PageTitle = CRMCommonResource.VoIPNumbersSettings; CommonContainerHolder.Controls.Add(LoadControl(VoipNumbers.Location)); break; default: PageTitle = CRMSettingResource.CustomFields; headerView.HeaderText = PageTitle; headerView.TabsContainerId = "CustomFieldsTabs"; headerView.AddListButtonId = "createNewField"; headerView.AddListButtonText = CRMSettingResource.CreateNewFieldListButton; TitleContentHolder.Controls.Add(headerView); CommonContainerHolder.Controls.Add(LoadControl(CustomFieldsView.Location)); break; } Title = HeaderStringHelper.GetPageTitle(Master.CurrentPageCaption ?? PageTitle); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Frapid.ApplicationState.Cache; using Frapid.Configuration; using Frapid.Configuration.Db; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.DbPolicy; using Frapid.i18n; using Frapid.Mapper; using Frapid.Mapper.Database; using Serilog; namespace Frapid.WebApi.DataAccess { public class ViewRepository : DbAccess, IViewRepository { private const int PageSize = 10; public ViewRepository(string schemaName, string tableName, string database, long loginId, int userId) { var appUser = AppUsers.GetCurrentAsync().GetAwaiter().GetResult(); this._ObjectNamespace = Sanitizer.SanitizeIdentifierName(schemaName); this._ObjectName = Sanitizer.SanitizeIdentifierName(tableName.Replace("-", "_")); this.LoginId = appUser.LoginId; this.OfficeId = appUser.OfficeId; this.UserId = appUser.UserId; this.Database = database; this.LoginId = loginId; this.UserId = userId; if (!string.IsNullOrWhiteSpace(this._ObjectNamespace) && !string.IsNullOrWhiteSpace(this._ObjectName)) { this.FullyQualifiedObjectName = this._ObjectNamespace + "." + this._ObjectName; this.PrimaryKey = this.GetCandidateKeyByConvention(); this.LookupField = this.GetLookupFieldByConvention(); this.NameColumn = this.GetNameColumnByConvention(); this.IsValid = true; } } public sealed override string _ObjectNamespace { get; } public sealed override string _ObjectName { get; } public string FullyQualifiedObjectName { get; set; } public string PrimaryKey { get; set; } public string LookupField { get; set; } public string NameColumn { get; set; } public string Database { get; set; } public int UserId { get; set; } public bool IsValid { get; set; } public long LoginId { get; set; } public int OfficeId { get; set; } public async Task<long> CountAsync() { if (string.IsNullOrWhiteSpace(this.Database)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information($"Access to count entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}"); throw new UnauthorizedException(Resources.AccessIsDenied); } } string sql = $"SELECT COUNT(*) FROM {this.FullyQualifiedObjectName};"; return await Factory.ScalarAsync<long>(this.Database, sql).ConfigureAwait(false); } public async Task<IEnumerable<dynamic>> GetAsync() { if (string.IsNullOrWhiteSpace(this.Database)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.ExportData, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information($"Access to the export entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}"); throw new UnauthorizedException(Resources.AccessIsDenied); } } string sql = $"SELECT * FROM {this.FullyQualifiedObjectName} ORDER BY {this.PrimaryKey}"; return await Factory.GetAsync<dynamic>(this.Database, sql).ConfigureAwait(false); } public async Task<IEnumerable<DisplayField>> GetDisplayFieldsAsync() { if (string.IsNullOrWhiteSpace(this.Database)) { return new List<DisplayField>(); } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information($"Access to get display field for entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}", this.LoginId); throw new UnauthorizedException(Resources.AccessIsDenied); } } string sql = $"SELECT {this.PrimaryKey} AS \"key\", {this.NameColumn} as \"value\" FROM {this.FullyQualifiedObjectName} ORDER BY 1;"; return await Factory.GetAsync<DisplayField>(this.Database, sql).ConfigureAwait(false); } public async Task<IEnumerable<DisplayField>> GetLookupFieldsAsync() { if (string.IsNullOrWhiteSpace(this.Database)) { return new List<DisplayField>(); } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information($"Access to get display field for entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}", this.LoginId); throw new UnauthorizedException(Resources.AccessIsDenied); } } string sql = $"SELECT {this.LookupField} AS \"key\", {this.NameColumn} as \"value\" FROM {this.FullyQualifiedObjectName} ORDER BY 1;"; return await Factory.GetAsync<DisplayField>(this.Database, sql).ConfigureAwait(false); } public async Task<IEnumerable<dynamic>> GetPaginatedResultAsync() { if (string.IsNullOrWhiteSpace(this.Database)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information($"Access to the first page of the entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}."); throw new UnauthorizedException(Resources.AccessIsDenied); } } //"SELECT * FROM {this.FullyQualifiedObjectName} //ORDER BY {this.PrimaryKey} LIMIT PageSize OFFSET 0;"; var sql = new Sql($"SELECT * FROM {this.FullyQualifiedObjectName}"); sql.OrderBy(this.PrimaryKey); sql.Append(FrapidDbServer.AddOffset(this.Database, "@0"), 0); sql.Append(FrapidDbServer.AddLimit(this.Database, "@0"), PageSize); return await Factory.GetAsync<dynamic>(this.Database, sql).ConfigureAwait(false); } public async Task<IEnumerable<dynamic>> GetPaginatedResultAsync(long pageNumber) { if (string.IsNullOrWhiteSpace(this.Database)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information($"Access to Page #{pageNumber} of the entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}."); throw new UnauthorizedException(Resources.AccessIsDenied); } } long offset = (pageNumber - 1)*PageSize; //"SELECT * FROM {this.FullyQualifiedObjectName} //ORDER BY {this.PrimaryKey} LIMIT PageSize OFFSET @0;"; var sql = new Sql($"SELECT * FROM {this.FullyQualifiedObjectName}"); sql.OrderBy(this.PrimaryKey); sql.Append(FrapidDbServer.AddOffset(this.Database, "@0"), offset); sql.Append(FrapidDbServer.AddLimit(this.Database, "@0"), PageSize); return await Factory.GetAsync<dynamic>(this.Database, sql).ConfigureAwait(false); } public async Task<IEnumerable<Filter>> GetFiltersAsync(string database, string filterName) { string sql = $"SELECT * FROM config.filters WHERE object_name='{this.FullyQualifiedObjectName}' AND lower(filter_name)=lower(@0);"; return await Factory.GetAsync<Filter>(database, sql, filterName).ConfigureAwait(false); } public async Task<long> CountWhereAsync(List<Filter> filters) { if (string.IsNullOrWhiteSpace(this.Database)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information($"Access to count entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}. Filters: {filters}."); throw new UnauthorizedException(Resources.AccessIsDenied); } } var sql = new Sql($"SELECT COUNT(*) FROM {this.FullyQualifiedObjectName} WHERE 1 = 1"); FilterManager.AddFilters(ref sql, filters); return await Factory.ScalarAsync<long>(this.Database, sql).ConfigureAwait(false); } public async Task<IEnumerable<dynamic>> GetWhereAsync(long pageNumber, List<Filter> filters) { if (string.IsNullOrWhiteSpace(this.Database)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information($"Access to Page #{pageNumber} of the filtered entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}. Filters: {filters}."); throw new UnauthorizedException(Resources.AccessIsDenied); } } long offset = (pageNumber - 1)*PageSize; var sql = new Sql($"SELECT * FROM {this.FullyQualifiedObjectName} WHERE 1 = 1"); FilterManager.AddFilters(ref sql, filters); sql.OrderBy("1"); if (pageNumber > 0) { sql.Append(FrapidDbServer.AddOffset(this.Database, "@0"), offset); sql.Append(FrapidDbServer.AddLimit(this.Database, "@0"), PageSize); } return await Factory.GetAsync<dynamic>(this.Database, sql).ConfigureAwait(false); } public async Task<long> CountFilteredAsync(string filterName) { if (string.IsNullOrWhiteSpace(this.Database)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information($"Access to count entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}. Filter: {filterName}."); throw new UnauthorizedException(Resources.AccessIsDenied); } } var filters = await this.GetFiltersAsync(this.Database, filterName).ConfigureAwait(false); var sql = new Sql($"SELECT COUNT(*) FROM {this.FullyQualifiedObjectName} WHERE 1 = 1"); FilterManager.AddFilters(ref sql, filters.ToList()); return await Factory.ScalarAsync<long>(this.Database, sql).ConfigureAwait(false); } public async Task<IEnumerable<dynamic>> GetFilteredAsync(long pageNumber, string filterName) { if (string.IsNullOrWhiteSpace(this.Database)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information( $"Access to Page #{pageNumber} of the filtered entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}. Filter: {filterName}."); throw new UnauthorizedException(Resources.AccessIsDenied); } } var filters = await this.GetFiltersAsync(this.Database, filterName).ConfigureAwait(false); long offset = (pageNumber - 1)*PageSize; var sql = new Sql($"SELECT * FROM {this.FullyQualifiedObjectName} WHERE 1 = 1"); FilterManager.AddFilters(ref sql, filters.ToList()); sql.OrderBy("1"); if (pageNumber > 0) { sql.Append(FrapidDbServer.AddOffset(this.Database, "@0"), offset); sql.Append(FrapidDbServer.AddLimit(this.Database, "@0"), PageSize); } return await Factory.GetAsync<dynamic>(this.Database, sql).ConfigureAwait(false); } public async Task<IEnumerable<DisplayField>> GetDisplayFieldsAsync(List<Filter> filters) { if (string.IsNullOrWhiteSpace(this.Database)) { return new List<DisplayField>(); } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information($"Access to get display field for entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}", this.LoginId); throw new UnauthorizedException(Resources.AccessIsDenied); } } var sql = new Sql($"SELECT {this.PrimaryKey} AS \"key\", {this.NameColumn} as \"value\" FROM {this.FullyQualifiedObjectName} WHERE 1=1"); FilterManager.AddFilters(ref sql, filters); sql.OrderBy("1"); return await Factory.GetAsync<DisplayField>(this.Database, sql).ConfigureAwait(false); } public async Task<IEnumerable<DisplayField>> GetLookupFieldsAsync(List<Filter> filters) { if (string.IsNullOrWhiteSpace(this.Database)) { return new List<DisplayField>(); } if (!this.SkipValidation) { if (!this.Validated) { await this.ValidateAsync(AccessTypeEnum.Read, this.LoginId, this.Database, false).ConfigureAwait(false); } if (!this.HasAccess) { Log.Information($"Access to get display field for entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}", this.LoginId); throw new UnauthorizedException(Resources.AccessIsDenied); } } var sql = new Sql($"SELECT {this.LookupField} AS \"key\", {this.NameColumn} as \"value\" FROM {this.FullyQualifiedObjectName} WHERE 1=1"); FilterManager.AddFilters(ref sql, filters); sql.OrderBy("1"); return await Factory.GetAsync<DisplayField>(this.Database, sql).ConfigureAwait(false); } #region View to Table Convention private string GetTableByConvention() { string tableName = this._ObjectName; tableName = tableName.Replace("_verification_scrud_view", ""); tableName = tableName.Replace("_scrud_view", ""); tableName = tableName.Replace("_selector_view", ""); tableName = tableName.Replace("_view", ""); return tableName; } private string GetCandidateKeyByConvention() { string candidateKey = Inflector.MakeSingular(this.GetTableByConvention()); if (!string.IsNullOrWhiteSpace(candidateKey)) { candidateKey += "_id"; } candidateKey = candidateKey ?? ""; return Sanitizer.SanitizeIdentifierName(candidateKey); } private string GetLookupFieldByConvention() { string candidateKey = Inflector.MakeSingular(this.GetTableByConvention()); if (!string.IsNullOrWhiteSpace(candidateKey)) { candidateKey += "_code"; } candidateKey = candidateKey?.Replace("_code_code", "_code") ?? ""; return Sanitizer.SanitizeIdentifierName(candidateKey); } private string GetNameColumnByConvention() { string nameKey = Inflector.MakeSingular(this.GetTableByConvention()); if (!string.IsNullOrWhiteSpace(nameKey)) { nameKey += "_name"; } return nameKey?.Replace("_name_name", "_name") ?? ""; } #endregion } }
#pragma warning disable 162,108,618 using Casanova.Prelude; using System.Linq; using System; using System.Collections.Generic; using UnityEngine; namespace Game {public class World : MonoBehaviour{ public static int frame; void Update () { Update(Time.deltaTime, this); frame++; } public bool JustEntered = true; public void Start() { System.Collections.Generic.List<UnityPlanet> ___unity_planets00; ___unity_planets00 = UnityPlanet.FindAll(); List<Player> ___players00; ___players00 = ( (UnityPlayer.FindAll()).Select(__ContextSymbol0 => new { ___p00 = __ContextSymbol0 }) .Select(__ContextSymbol1 => new Player(__ContextSymbol1.___p00.Name,new GameStatistic(1f,1f,1f,1f))) .ToList<Player>()).ToList<Player>(); List<Planet> ___planets00; ___planets00 = ( (___unity_planets00).Select(__ContextSymbol2 => new { ___unity_planet00 = __ContextSymbol2 }) .Select(__ContextSymbol3 => new {___owner00 = ( (___players00).Select(__ContextSymbol4 => new { ___player00 = __ContextSymbol4,prev = __ContextSymbol3 }) .Where(__ContextSymbol5 => ((((__ContextSymbol5.prev.___unity_planet00.InitialOwnerName) == (__ContextSymbol5.___player00.Name))) && (!(((__ContextSymbol5.prev.___unity_planet00.InitialOwnerName) == ("")))))) .Select(__ContextSymbol6 => __ContextSymbol6.___player00) .ToList<Player>()).ToList<Player>(), prev = __ContextSymbol3 }) .Select(__ContextSymbol7 => new {___owner01 = Utils.IfThenElse<Option<Player>>((()=> ((__ContextSymbol7.___owner00.Count) > (0))), (()=> (new Just<Player>(__ContextSymbol7.___owner00.Head())) ),(()=> (new Nothing<Player>()) )), prev = __ContextSymbol7 }) .Select(__ContextSymbol8 => new Planet(__ContextSymbol8.prev.prev.___unity_planet00,new GameStatistic(1f,1f,1f,1f),__ContextSymbol8.___owner01)) .ToList<Planet>()).ToList<Planet>(); System.Collections.Generic.List<UnityLine> ___unity_links00; ___unity_links00 = UnityLine.FindAll(); List<Link> ___links100; ___links100 = ( (___unity_links00).Select(__ContextSymbol9 => new { ___unity_link00 = __ContextSymbol9 }) .SelectMany(__ContextSymbol10=> (___planets00).Select(__ContextSymbol11 => new { ___source00 = __ContextSymbol11, prev = __ContextSymbol10 }) .SelectMany(__ContextSymbol12=> (___planets00).Select(__ContextSymbol13 => new { ___destination00 = __ContextSymbol13, prev = __ContextSymbol12 }) .Where(__ContextSymbol14 => ((((__ContextSymbol14.prev.prev.___unity_link00.f) == (__ContextSymbol14.prev.___source00.UnityPlanet.gameObject))) && (((__ContextSymbol14.prev.prev.___unity_link00.t) == (__ContextSymbol14.___destination00.UnityPlanet.gameObject))))) .Select(__ContextSymbol15 => new Link(__ContextSymbol15.prev.prev.___unity_link00,__ContextSymbol15.prev.___source00,__ContextSymbol15.___destination00)) .ToList<Link>()))).ToList<Link>(); List<Link> ___links200; ___links200 = ( (___unity_links00).Select(__ContextSymbol16 => new { ___unity_link01 = __ContextSymbol16 }) .SelectMany(__ContextSymbol17=> (___planets00).Select(__ContextSymbol18 => new { ___source01 = __ContextSymbol18, prev = __ContextSymbol17 }) .SelectMany(__ContextSymbol19=> (___planets00).Select(__ContextSymbol20 => new { ___destination01 = __ContextSymbol20, prev = __ContextSymbol19 }) .Where(__ContextSymbol21 => ((((__ContextSymbol21.prev.prev.___unity_link01.f) == (__ContextSymbol21.prev.___source01.UnityPlanet.gameObject))) && (((__ContextSymbol21.prev.prev.___unity_link01.t) == (__ContextSymbol21.___destination01.UnityPlanet.gameObject))))) .Select(__ContextSymbol22 => new Link(__ContextSymbol22.prev.prev.___unity_link01,__ContextSymbol22.___destination01,__ContextSymbol22.prev.___source01)) .ToList<Link>()))).ToList<Link>(); Players = ___players00; Planets = ___planets00; Links = (___links100).Concat(___links200).ToList<Link>(); } public List<Link> __Links; public List<Link> Links{ get { return __Links; } set{ __Links = value; foreach(var e in value){if(e.JustEntered){ e.JustEntered = false; } } } } public List<Planet> __Planets; public List<Planet> Planets{ get { return __Planets; } set{ __Planets = value; foreach(var e in value){if(e.JustEntered){ e.JustEntered = false; } } } } public List<Player> Players; System.DateTime init_time = System.DateTime.Now; public void Update(float dt, World world) { var t = System.DateTime.Now; for(int x0 = 0; x0 < Links.Count; x0++) { Links[x0].Update(dt, world); } for(int x0 = 0; x0 < Planets.Count; x0++) { Planets[x0].Update(dt, world); } for(int x0 = 0; x0 < Players.Count; x0++) { Players[x0].Update(dt, world); } } } public class Battle{ public int frame; public bool JustEntered = true; private Planet planet; public int ID; public Battle(Planet planet) {JustEntered = false; frame = World.frame; MySource = planet; FleetsToMerge = ( Enumerable.Empty<AttackingFleetToMerge>()).ToList<AttackingFleetToMerge>(); FleetsToDestroyNextTurn = ( Enumerable.Empty<AttackingFleet>()).ToList<AttackingFleet>(); DefenceLost = (new Nothing<System.Int32>()); AttackingFleets = ( Enumerable.Empty<AttackingFleet>()).ToList<AttackingFleet>(); AttackLost = (new Nothing<System.Int32>()); } public Option<System.Int32> AttackLost; public List<AttackingFleet> AttackingFleets; public Option<System.Int32> DefenceLost; public List<AttackingFleet> FleetsToDestroyNextTurn; public List<AttackingFleetToMerge> FleetsToMerge; public Planet MySource; public List<AttackingFleet> ___new_attacking_fleets20; public List<AttackingFleet> ___filtered_attacking_fleets20; public System.Single count_down1; public System.Single count_down2; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule3(dt, world); this.Rule4(dt, world); if(AttackLost.IsSome){ } for(int x0 = 0; x0 < AttackingFleets.Count; x0++) { AttackingFleets[x0].Update(dt, world); } if(DefenceLost.IsSome){ } for(int x0 = 0; x0 < FleetsToDestroyNextTurn.Count; x0++) { FleetsToDestroyNextTurn[x0].Update(dt, world); } for(int x0 = 0; x0 < FleetsToMerge.Count; x0++) { FleetsToMerge[x0].Update(dt, world); } } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: FleetsToMerge = ( (MySource.InboundFleets).Select(__ContextSymbol29 => new { ___i_f00 = __ContextSymbol29 }) .SelectMany(__ContextSymbol30=> (AttackingFleets).Select(__ContextSymbol31 => new { ___a_f00 = __ContextSymbol31, prev = __ContextSymbol30 }) .Where(__ContextSymbol32 => ((!(__ContextSymbol32.___a_f00.MyFleet.Destroyed)) && (((__ContextSymbol32.prev.___i_f00.Link) == (__ContextSymbol32.___a_f00.MyFleet.Link))))) .Select(__ContextSymbol33 => new AttackingFleetToMerge(__ContextSymbol33.prev.___i_f00,__ContextSymbol33.___a_f00)) .ToList<AttackingFleetToMerge>())).ToList<AttackingFleetToMerge>(); s0 = -1; return; default: return;}} int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: FleetsToDestroyNextTurn = ( (AttackingFleets).Select(__ContextSymbol34 => new { ___f10 = __ContextSymbol34 }) .Where(__ContextSymbol35 => ((MySource.Owner.IsSome) && (((__ContextSymbol35.___f10.MyFleet.Owner) == (MySource.Owner.Value))))) .Select(__ContextSymbol36 => __ContextSymbol36.___f10) .ToList<AttackingFleet>()).ToList<AttackingFleet>(); s1 = -1; return; default: return;}} int s2=-1; public void Rule2(float dt, World world){ switch (s2) { case -1: ___new_attacking_fleets20 = ( (MySource.InboundFleets).Select(__ContextSymbol37 => new { ___f21 = __ContextSymbol37 }) .Select(__ContextSymbol38 => new {___is_ship_to_merge20 = ( (FleetsToMerge).Select(__ContextSymbol39 => new { ___flee_to_merge20 = __ContextSymbol39,prev = __ContextSymbol38 }) .Where(__ContextSymbol40 => ((__ContextSymbol40.___flee_to_merge20.MyFleet) == (__ContextSymbol40.prev.___f21))) .Select(__ContextSymbol41 => 1) .Aggregate(default(System.Int32), (acc, __x) => acc + __x)), prev = __ContextSymbol38 }) .Where(__ContextSymbol43 => ((((__ContextSymbol43.___is_ship_to_merge20) == (0))) && (((MySource.Owner.IsNone) || (!(((__ContextSymbol43.prev.___f21.Owner) == (MySource.Owner.Value)))))))) .Select(__ContextSymbol44 => new AttackingFleet(__ContextSymbol44.prev.___f21,this)) .ToList<AttackingFleet>()).ToList<AttackingFleet>(); ___filtered_attacking_fleets20 = ( (AttackingFleets).Select(__ContextSymbol45 => new { ___f22 = __ContextSymbol45 }) .Where(__ContextSymbol46 => ((!(__ContextSymbol46.___f22.MyFleet.Destroyed)) && (((MySource.Owner.IsSome) && (!(((__ContextSymbol46.___f22.MyFleet.Owner) == (MySource.Owner.Value)))))))) .Select(__ContextSymbol47 => __ContextSymbol47.___f22) .ToList<AttackingFleet>()).ToList<AttackingFleet>(); AttackingFleets = (___new_attacking_fleets20).Concat(___filtered_attacking_fleets20).ToList<AttackingFleet>(); s2 = -1; return; default: return;}} int s3=-1; public void Rule3(float dt, World world){ switch (s3) { case -1: if(!(((!(((AttackingFleets.Count) > (1)))) || (true)))) { s3 = -1; return; }else { goto case 0; } case 0: if(!(((AttackingFleets.Count) > (1)))) { goto case 2; }else { if(true) { goto case 3; }else { s3 = 0; return; } } case 2: AttackingFleets = AttackingFleets; s3 = -1; return; case 3: count_down1 = UnityEngine.Random.Range(1f,2f); goto case 7; case 7: if(((count_down1) > (0f))) { count_down1 = ((count_down1) - (dt)); s3 = 7; return; }else { goto case 5; } case 5: AttackingFleets = (AttackingFleets.Tail()).Concat(( (new Cons<AttackingFleet>(AttackingFleets.Head(),(new Empty<AttackingFleet>()).ToList<AttackingFleet>())).ToList<AttackingFleet>()).ToList<AttackingFleet>()).ToList<AttackingFleet>(); s3 = -1; return; default: return;}} int s4=-1; public void Rule4(float dt, World world){ switch (s4) { case -1: AttackLost = (new Nothing<System.Int32>()); DefenceLost = (new Nothing<System.Int32>()); s4 = 3; return; case 3: count_down2 = 1f; goto case 4; case 4: if(((count_down2) > (0f))) { count_down2 = ((count_down2) - (dt)); s4 = 4; return; }else { goto case 0; } case 0: if(((AttackingFleets.Count) > (0))) { goto case 1; }else { s4 = -1; return; } case 1: AttackLost = (new Just<System.Int32>(1)); DefenceLost = (new Just<System.Int32>(1)); s4 = -1; return; default: return;}} } public class Planet{ public int frame; public bool JustEntered = true; private UnityPlanet up; private GameStatistic statistics; private Option<Player> owner; public int ID; public Planet(UnityPlanet up, GameStatistic statistics, Option<Player> owner) {JustEntered = false; frame = World.frame; UnityPlanet = up; Statistics = statistics; Owner = owner; MinApproachingDist = 0.5f; LocalFleets = 0; LandingFleets = ( Enumerable.Empty<LandingFleet>()).ToList<LandingFleet>(); InboundFleets = ( Enumerable.Empty<Fleet>()).ToList<Fleet>(); Battle = (new Nothing<Battle>()); } public Option<Battle> Battle; public List<Fleet> InboundFleets; public System.String Info{ get { return UnityPlanet.Info; } set{UnityPlanet.Info = value; } } public System.String InitialOwnerName{ get { return UnityPlanet.InitialOwnerName; } } public System.Boolean IsHit{ get { return UnityPlanet.IsHit; } } public List<LandingFleet> LandingFleets; public System.Int32 LocalFleets; public System.Single MinApproachingDist; public Option<Player> Owner; public UnityEngine.Vector3 Position{ get { return UnityPlanet.Position; } } public System.Boolean RightSelected{ get { return UnityPlanet.RightSelected; } set{UnityPlanet.RightSelected = value; } } public System.Boolean Selected{ get { return UnityPlanet.Selected; } set{UnityPlanet.Selected = value; } } public GameStatistic Statistics; public UnityPlanet UnityPlanet; public System.Boolean enabled{ get { return UnityPlanet.enabled; } set{UnityPlanet.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityPlanet.gameObject; } } public UnityEngine.HideFlags hideFlags{ get { return UnityPlanet.hideFlags; } set{UnityPlanet.hideFlags = value; } } public UnityEngine.GameObject initial_owner{ get { return UnityPlanet.initial_owner; } set{UnityPlanet.initial_owner = value; } } public System.Boolean isActiveAndEnabled{ get { return UnityPlanet.isActiveAndEnabled; } } public System.String name{ get { return UnityPlanet.name; } set{UnityPlanet.name = value; } } public System.Boolean rightSelected{ get { return UnityPlanet.rightSelected; } set{UnityPlanet.rightSelected = value; } } public System.Boolean selected{ get { return UnityPlanet.selected; } set{UnityPlanet.selected = value; } } public System.String tag{ get { return UnityPlanet.tag; } set{UnityPlanet.tag = value; } } public UnityEngine.Transform transform{ get { return UnityPlanet.transform; } } public System.Boolean useGUILayout{ get { return UnityPlanet.useGUILayout; } set{UnityPlanet.useGUILayout = value; } } public System.Int32 ___fleets_to_add30; public System.Single count_down3; public Player ___new_owner50; public System.Int32 ___fleets_to_add51; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule3(dt, world); this.Rule4(dt, world); this.Rule5(dt, world); this.Rule6(dt, world); this.Rule7(dt, world); this.Rule8(dt, world); this.Rule9(dt, world); if(Battle.IsSome){ Battle.Value.Update(dt, world); } for(int x0 = 0; x0 < InboundFleets.Count; x0++) { InboundFleets[x0].Update(dt, world); } for(int x0 = 0; x0 < LandingFleets.Count; x0++) { LandingFleets[x0].Update(dt, world); } Statistics.Update(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: InboundFleets = ( (world.Links).Select(__ContextSymbol53 => new { ___l00 = __ContextSymbol53 }) .Where(__ContextSymbol54 => ((__ContextSymbol54.___l00.Destination) == (this))) .SelectMany(__ContextSymbol55=> (__ContextSymbol55.___l00.TravellingFleets).Select(__ContextSymbol56 => new { ___f03 = __ContextSymbol56, prev = __ContextSymbol55 }) .Where(__ContextSymbol57 => !(((UnityEngine.Vector3.Distance(__ContextSymbol57.___f03.MyFleet.Position,Position)) > (MinApproachingDist)))) .Select(__ContextSymbol58 => __ContextSymbol58.___f03.MyFleet) .ToList<Fleet>())).ToList<Fleet>(); s0 = -1; return; default: return;}} int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: if(Owner.IsSome) { goto case 1; }else { goto case 2; } case 1: LandingFleets = ( (InboundFleets).Select(__ContextSymbol59 => new { ___inbound_fleet10 = __ContextSymbol59 }) .Where(__ContextSymbol60 => ((__ContextSymbol60.___inbound_fleet10.Owner) == (Owner.Value))) .Select(__ContextSymbol61 => new LandingFleet(__ContextSymbol61.___inbound_fleet10)) .ToList<LandingFleet>()).ToList<LandingFleet>(); s1 = -1; return; case 2: LandingFleets = ( Enumerable.Empty<LandingFleet>()).ToList<LandingFleet>(); s1 = -1; return; default: return;}} int s2=-1; public void Rule2(float dt, World world){ switch (s2) { case -1: if(((((((Owner.IsNone) && (Battle.IsNone))) && (!(((LandingFleets.Count) == (InboundFleets.Count)))))) || (((Owner.IsSome) && (!(((LandingFleets.Count) == (InboundFleets.Count)))))))) { goto case 6; }else { goto case 7; } case 6: Battle = (new Just<Battle>(new Battle(this))); s2 = 10; return; case 10: if(!(!(((Battle.Value.AttackingFleets.Count) > (0))))) { s2 = 10; return; }else { goto case 9; } case 9: Battle = (new Nothing<Battle>()); s2 = -1; return; case 7: Battle = (new Nothing<Battle>()); s2 = -1; return; default: return;}} int s3=-1; public void Rule3(float dt, World world){ switch (s3) { case -1: ___fleets_to_add30 = ( (LandingFleets).Select(__ContextSymbol63 => new { ___f34 = __ContextSymbol63 }) .Select(__ContextSymbol64 => __ContextSymbol64.___f34.MyFleet.Ships) .Aggregate(default(System.Int32), (acc, __x) => acc + __x)); LocalFleets = ((LocalFleets) + (___fleets_to_add30)); s3 = -1; return; default: return;}} int s4=-1; public void Rule4(float dt, World world){ switch (s4) { case -1: if(!(((((Battle.IsSome) && (Battle.Value.DefenceLost.IsSome))) || (((Battle.IsSome) || (((Owner.IsNone) || (true)))))))) { s4 = -1; return; }else { goto case 0; } case 0: if(((Battle.IsSome) && (Battle.Value.DefenceLost.IsSome))) { goto case 2; }else { if(Battle.IsSome) { goto case 3; }else { if(Owner.IsNone) { goto case 4; }else { if(true) { goto case 5; }else { s4 = 0; return; } } } } case 2: LocalFleets = ((LocalFleets) - (Battle.Value.DefenceLost.Value)); s4 = -1; return; case 3: LocalFleets = LocalFleets; s4 = -1; return; case 4: LocalFleets = 0; s4 = -1; return; case 5: count_down3 = UnityEngine.Random.Range(1,3); goto case 11; case 11: if(((count_down3) > (0f))) { count_down3 = ((count_down3) - (dt)); s4 = 11; return; }else { goto case 9; } case 9: LocalFleets = ((LocalFleets) + (1)); s4 = -1; return; default: return;}} int s5=-1; public void Rule5(float dt, World world){ switch (s5) { case -1: if(((((Battle.IsSome) && (((LocalFleets) == (0))))) && (((Battle.Value.AttackingFleets.Count) > (0))))) { goto case 13; }else { s5 = -1; return; } case 13: ___new_owner50 = Battle.Value.AttackingFleets.Head().MyFleet.Owner; ___fleets_to_add51 = ( (Battle.Value.AttackingFleets).Select(__ContextSymbol66 => new { ___f55 = __ContextSymbol66 }) .Where(__ContextSymbol67 => ((((__ContextSymbol67.___f55.MyFleet.Owner) == (___new_owner50))) && (((__ContextSymbol67.___f55.MyFleet.Ships) > (0))))) .Select(__ContextSymbol68 => __ContextSymbol68.___f55.MyFleet.Ships) .Aggregate(default(System.Int32), (acc, __x) => acc + __x)); Owner = (new Just<Player>(Battle.Value.AttackingFleets.Head().MyFleet.Owner)); LocalFleets = ___fleets_to_add51; s5 = -1; return; default: return;}} int s6=-1; public void Rule6(float dt, World world){ switch (s6) { case -1: if(Owner.IsSome) { goto case 17; }else { goto case 18; } case 17: Info = ((Owner.Value.Name) + (" ")); s6 = -1; return; case 18: Info = ""; s6 = -1; return; default: return;}} int s7=-1; public void Rule7(float dt, World world){ switch (s7) { case -1: Info = ((Info) + (LocalFleets.ToString())); s7 = -1; return; default: return;}} int s8=-1; public void Rule8(float dt, World world){ switch (s8) { case -1: if(!(((UnityEngine.Input.GetMouseButtonDown(0)) && (((UnityEngine.Input.GetKey(KeyCode.LeftShift)) || (UnityEngine.Input.GetKey(KeyCode.LeftControl))))))) { s8 = -1; return; }else { goto case 0; } case 0: if(IsHit) { goto case 1; }else { s8 = -1; return; } case 1: RightSelected = true; s8 = 2; return; case 2: RightSelected = false; s8 = -1; return; default: return;}} int s9=-1; public void Rule9(float dt, World world){ switch (s9) { case -1: if(!(((UnityEngine.Input.GetMouseButtonDown(0)) && (!(((UnityEngine.Input.GetKey(KeyCode.LeftShift)) || (UnityEngine.Input.GetKey(KeyCode.LeftControl)))))))) { s9 = -1; return; }else { goto case 0; } case 0: Selected = IsHit; s9 = -1; return; default: return;}} } public class Fleet{ public int frame; public bool JustEntered = true; private GameStatistic statistics; private System.Int32 ships; private Player owner; private UnityEngine.Vector3 position; private Link link; public int ID; public Fleet(GameStatistic statistics, System.Int32 ships, Player owner, UnityEngine.Vector3 position, Link link) {JustEntered = false; frame = World.frame; UnityFleet = UnityFleet.Instantiate(position,link.Destination.Position); Statistics = statistics; Ships = ships; Owner = owner; Link = link; } public System.Boolean Destroyed{ get { return UnityFleet.Destroyed; } set{UnityFleet.Destroyed = value; } } public System.String Info{ get { return UnityFleet.Info; } set{UnityFleet.Info = value; } } public Link Link; public Player Owner; public UnityEngine.Vector3 Position{ get { return UnityFleet.Position; } set{UnityFleet.Position = value; } } public System.Int32 Ships; public GameStatistic Statistics; public UnityFleet UnityFleet; public System.Boolean enabled{ get { return UnityFleet.enabled; } set{UnityFleet.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityFleet.gameObject; } } public UnityEngine.HideFlags hideFlags{ get { return UnityFleet.hideFlags; } set{UnityFleet.hideFlags = value; } } public System.Boolean isActiveAndEnabled{ get { return UnityFleet.isActiveAndEnabled; } } public System.String name{ get { return UnityFleet.name; } set{UnityFleet.name = value; } } public System.String tag{ get { return UnityFleet.tag; } set{UnityFleet.tag = value; } } public UnityEngine.Transform transform{ get { return UnityFleet.transform; } } public System.Boolean useGUILayout{ get { return UnityFleet.useGUILayout; } set{UnityFleet.useGUILayout = value; } } public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); this.Rule1(dt, world); Statistics.Update(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: if(!(!(((Ships) > (0))))) { s0 = -1; return; }else { goto case 0; } case 0: Destroyed = true; s0 = -1; return; default: return;}} int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: Info = Ships.ToString(); s1 = -1; return; default: return;}} } public class AttackingFleetToMerge{ public int frame; public bool JustEntered = true; private Fleet fleet; private AttackingFleet fleet_to_merge_with; public int ID; public AttackingFleetToMerge(Fleet fleet, AttackingFleet fleet_to_merge_with) {JustEntered = false; frame = World.frame; MyFleet = fleet; FleetToMergeWith = fleet_to_merge_with; } public AttackingFleet FleetToMergeWith; public Fleet MyFleet; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: MyFleet.Destroyed = true; s0 = -1; return; default: return;}} } public class AttackingFleet{ public int frame; public bool JustEntered = true; private Fleet myFleet; private Battle myBattle; public int ID; public AttackingFleet(Fleet myFleet, Battle myBattle) {JustEntered = false; frame = World.frame; MyFleet = myFleet; MyBattle = myBattle; } public Battle MyBattle; public Fleet MyFleet; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule3(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: if(!(((MyBattle.AttackLost.IsSome) && (((MyBattle.AttackingFleets.Head()) == (this)))))) { s0 = -1; return; }else { goto case 0; } case 0: MyFleet.Ships = ((MyFleet.Ships) - (MyBattle.AttackLost.Value)); s0 = -1; return; default: return;}} int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: MyFleet.Ships = ((( (MyBattle.FleetsToMerge).Select(__ContextSymbol70 => new { ___f16 = __ContextSymbol70 }) .Where(__ContextSymbol71 => ((__ContextSymbol71.___f16.FleetToMergeWith) == (this))) .Select(__ContextSymbol72 => __ContextSymbol72.___f16.MyFleet.Ships) .Aggregate(default(System.Int32), (acc, __x) => acc + __x))) + (MyFleet.Ships)); s1 = -1; return; default: return;}} int s2=-1; public void Rule2(float dt, World world){ switch (s2) { case -1: MyFleet.Info = MyFleet.Ships.ToString(); s2 = -1; return; default: return;}} int s3=-1; public void Rule3(float dt, World world){ switch (s3) { case -1: if(!(((((MyBattle.MySource.Owner.IsSome) && (((MyFleet.Owner) == (MyBattle.MySource.Owner.Value))))) || (!(((MyFleet.Ships) > (0))))))) { s3 = -1; return; }else { goto case 0; } case 0: MyFleet.Destroyed = true; s3 = -1; return; default: return;}} } public class LandingFleet{ public int frame; public bool JustEntered = true; private Fleet myFleet; public int ID; public LandingFleet(Fleet myFleet) {JustEntered = false; frame = World.frame; MyFleet = myFleet; } public Fleet MyFleet; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); MyFleet.Update(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: MyFleet.Destroyed = true; s0 = -1; return; default: return;}} } public class TravellingFleet{ public int frame; public bool JustEntered = true; private Fleet myfleet; private Planet destination; public int ID; public TravellingFleet(Fleet myfleet, Planet destination) {JustEntered = false; frame = World.frame; UnityEngine.Vector3 ___velocity00; ___velocity00 = (destination.Position) - (myfleet.Position); UnityEngine.Vector3 ___velocity_norm00; ___velocity_norm00 = ___velocity00.normalized; Velocity = ___velocity_norm00; MyFleet = myfleet; MaxVelocity = 1f; Destination = destination; } public Planet Destination; public System.Single MaxVelocity; public Fleet MyFleet; public UnityEngine.Vector3 Velocity; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); MyFleet.Update(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: MyFleet.Position = ((MyFleet.Position) + (((((Velocity) * (MaxVelocity))) * (dt)))); s0 = -1; return; default: return;}} } public class Link{ public int frame; public bool JustEntered = true; private UnityLine ul; private Planet s; private Planet d; public int ID; public Link(UnityLine ul, Planet s, Planet d) {JustEntered = false; frame = World.frame; UnityLine = ul; TravellingFleets = ( Enumerable.Empty<TravellingFleet>()).ToList<TravellingFleet>(); Source = s; IsAutoRouteActive = false; Destination = d; } public System.Boolean ActiveAutoRoute{ get { return UnityLine.ActiveAutoRoute; } set{UnityLine.ActiveAutoRoute = value; } } public Planet Destination; public UnityPlanet FromPlanet{ set{UnityLine.FromPlanet = value; } } public System.Boolean IsAutoRouteActive; public Planet Source; public List<TravellingFleet> TravellingFleets; public UnityLine UnityLine; public System.Collections.Generic.Dictionary<UnityPlanet,UnityArrow> arrows{ get { return UnityLine.arrows; } set{UnityLine.arrows = value; } } public UnityEngine.Color c1{ get { return UnityLine.c1; } set{UnityLine.c1 = value; } } public UnityEngine.Color c2{ get { return UnityLine.c2; } set{UnityLine.c2 = value; } } public System.Boolean enabled{ get { return UnityLine.enabled; } set{UnityLine.enabled = value; } } public UnityEngine.GameObject f{ get { return UnityLine.f; } set{UnityLine.f = value; } } public UnityEngine.GameObject gameObject{ get { return UnityLine.gameObject; } } public UnityEngine.HideFlags hideFlags{ get { return UnityLine.hideFlags; } set{UnityLine.hideFlags = value; } } public System.Boolean isActiveAndEnabled{ get { return UnityLine.isActiveAndEnabled; } } public System.Int32 lengthOfLineRenderer{ get { return UnityLine.lengthOfLineRenderer; } set{UnityLine.lengthOfLineRenderer = value; } } public System.String name{ get { return UnityLine.name; } set{UnityLine.name = value; } } public UnityEngine.GameObject t{ get { return UnityLine.t; } set{UnityLine.t = value; } } public System.String tag{ get { return UnityLine.tag; } set{UnityLine.tag = value; } } public UnityEngine.Transform transform{ get { return UnityLine.transform; } } public System.Boolean useGUILayout{ get { return UnityLine.useGUILayout; } set{UnityLine.useGUILayout = value; } } public Fleet ___new_fleet10; public System.Single count_down4; public Fleet ___new_fleet21; public System.Boolean ___autoroute_value30; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule3(dt, world); for(int x0 = 0; x0 < TravellingFleets.Count; x0++) { TravellingFleets[x0].Update(dt, world); } } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: TravellingFleets = ( (TravellingFleets).Select(__ContextSymbol76 => new { ___f07 = __ContextSymbol76 }) .Where(__ContextSymbol77 => ((!(__ContextSymbol77.___f07.MyFleet.Destroyed)) && (((UnityEngine.Vector3.Distance(__ContextSymbol77.___f07.MyFleet.Position,Destination.Position)) > (Destination.MinApproachingDist))))) .Select(__ContextSymbol78 => __ContextSymbol78.___f07) .ToList<TravellingFleet>()).ToList<TravellingFleet>(); s0 = -1; return; default: return;}} int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: if(!(((((((((((Source.Selected) && (Destination.RightSelected))) && (Source.Owner.IsSome))) && (Source.Battle.IsNone))) && (UnityEngine.Input.GetKey(KeyCode.LeftShift)))) && (((Source.LocalFleets) > (0)))))) { s1 = -1; return; }else { goto case 1; } case 1: ___new_fleet10 = new Fleet(new GameStatistic(1f,1f,1f,1f),Source.LocalFleets,Source.Owner.Value,Source.Position,this); TravellingFleets = new Cons<TravellingFleet>(new TravellingFleet(___new_fleet10,Destination), (TravellingFleets)).ToList<TravellingFleet>(); Source.LocalFleets = 0; s1 = -1; return; default: return;}} int s2=-1; public void Rule2(float dt, World world){ switch (s2) { case -1: if(!(IsAutoRouteActive)) { s2 = -1; return; }else { goto case 4; } case 4: count_down4 = UnityEngine.Random.Range(2f,3f); goto case 5; case 5: if(((count_down4) > (0f))) { count_down4 = ((count_down4) - (dt)); s2 = 5; return; }else { goto case 0; } case 0: if(((((Source.LocalFleets) / (2))) > (0))) { goto case 1; }else { s2 = -1; return; } case 1: ___new_fleet21 = new Fleet(new GameStatistic(1f,1f,1f,1f),(Source.LocalFleets) / (2),Source.Owner.Value,Source.Position,this); TravellingFleets = new Cons<TravellingFleet>(new TravellingFleet(___new_fleet21,Destination), (TravellingFleets)).ToList<TravellingFleet>(); Source.LocalFleets = ((Source.LocalFleets) / (2)); s2 = -1; return; default: return;}} int s3=-1; public void Rule3(float dt, World world){ switch (s3) { case -1: if(!(((((Source.Selected) && (Destination.RightSelected))) && (UnityEngine.Input.GetKey(KeyCode.LeftControl))))) { s3 = -1; return; }else { goto case 2; } case 2: ___autoroute_value30 = !(IsAutoRouteActive); IsAutoRouteActive = ___autoroute_value30; ActiveAutoRoute = ___autoroute_value30; FromPlanet = Source.UnityPlanet; s3 = 0; return; case 0: if(!(UnityEngine.Input.GetKeyUp(KeyCode.LeftControl))) { s3 = 0; return; }else { s3 = -1; return; } default: return;}} } public class Player{ public int frame; public bool JustEntered = true; private System.String name; private GameStatistic statistics; public int ID; public Player(System.String name, GameStatistic statistics) {JustEntered = false; frame = World.frame; Statistics = statistics; Name = name; } public System.String Name; public GameStatistic Statistics; public void Update(float dt, World world) { frame = World.frame; Statistics.Update(dt, world); } } public class GameStatistic{ public int frame; public bool JustEntered = true; private System.Single a; private System.Single d; private System.Single p; private System.Single r; public int ID; public GameStatistic(System.Single a, System.Single d, System.Single p, System.Single r) {JustEntered = false; frame = World.frame; Research = r; Production = p; Defence = d; Attack = a; } public System.Single Attack; public System.Single Defence; public System.Single Production; public System.Single Research; public void Update(float dt, World world) { frame = World.frame; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; namespace System.Linq.Expressions { /// <summary> /// Represents indexing a property or array. /// </summary> [DebuggerTypeProxy(typeof(IndexExpressionProxy))] public sealed class IndexExpression : Expression, IArgumentProvider { private IReadOnlyList<Expression> _arguments; internal IndexExpression( Expression instance, PropertyInfo indexer, IReadOnlyList<Expression> arguments) { if (indexer == null) { Debug.Assert(instance != null && instance.Type.IsArray); Debug.Assert(instance.Type.GetArrayRank() == arguments.Count); } Object = instance; Indexer = indexer; _arguments = arguments; } /// <summary> /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.Index; /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { if (Indexer != null) { return Indexer.PropertyType; } return Object.Type.GetElementType(); } } /// <summary> /// An object to index. /// </summary> public Expression Object { get; } /// <summary> /// Gets the <see cref="PropertyInfo"/> for the property if the expression represents an indexed property, returns null otherwise. /// </summary> public PropertyInfo Indexer { get; } /// <summary> /// Gets the arguments to be used to index the property or array. /// </summary> public ReadOnlyCollection<Expression> Arguments { get { return ReturnReadOnly(ref _arguments); } } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="object">The <see cref="Object"/> property of the result.</param> /// <param name="arguments">The <see cref="Arguments"/> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public IndexExpression Update(Expression @object, IEnumerable<Expression> arguments) { if (@object == Object & arguments != null) { if (ExpressionUtils.SameElements(ref arguments, Arguments)) { return this; } } return MakeIndex(@object, Indexer, arguments); } /// <summary> /// Gets the argument expression with the specified <paramref name="index"/>. /// </summary> /// <param name="index">The index of the argument expression to get.</param> /// <returns>The expression representing the argument at the specified <paramref name="index"/>.</returns> public Expression GetArgument(int index) => _arguments[index]; /// <summary> /// Gets the number of argument expressions of the node. /// </summary> public int ArgumentCount => _arguments.Count; /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitIndex(this); } internal Expression Rewrite(Expression instance, Expression[] arguments) { Debug.Assert(instance != null); Debug.Assert(arguments == null || arguments.Length == _arguments.Count); return Expression.MakeIndex(instance, Indexer, arguments ?? _arguments); } } public partial class Expression { /// <summary> /// Creates an <see cref="IndexExpression"/> that represents accessing an indexed property in an object. /// </summary> /// <param name="instance">The object to which the property belongs. Should be null if the property is static(shared).</param> /// <param name="indexer">An <see cref="Expression"/> representing the property to index.</param> /// <param name="arguments">An <see cref="IEnumerable{Expression}"/> containing the arguments to be used to index the property.</param> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression MakeIndex(Expression instance, PropertyInfo indexer, IEnumerable<Expression> arguments) { if (indexer != null) { return Property(instance, indexer, arguments); } else { return ArrayAccess(instance, arguments); } } #region ArrayAccess /// <summary> /// Creates an <see cref="IndexExpression"/> to access an array. /// </summary> /// <param name="array">An expression representing the array to index.</param> /// <param name="indexes">An array containing expressions used to index the array.</param> /// <remarks>The expression representing the array can be obtained by using the <see cref="MakeMemberAccess"/> method, /// or through <see cref="NewArrayBounds"/> or <see cref="NewArrayInit"/>.</remarks> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression ArrayAccess(Expression array, params Expression[] indexes) { return ArrayAccess(array, (IEnumerable<Expression>)indexes); } /// <summary> /// Creates an <see cref="IndexExpression"/> to access an array. /// </summary> /// <param name="array">An expression representing the array to index.</param> /// <param name="indexes">An <see cref="IEnumerable{T}"/> containing expressions used to index the array.</param> /// <remarks>The expression representing the array can be obtained by using the <see cref="MakeMemberAccess"/> method, /// or through <see cref="NewArrayBounds"/> or <see cref="NewArrayInit"/>.</remarks> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression ArrayAccess(Expression array, IEnumerable<Expression> indexes) { RequiresCanRead(array, nameof(array)); Type arrayType = array.Type; if (!arrayType.IsArray) { throw Error.ArgumentMustBeArray(nameof(array)); } ReadOnlyCollection<Expression> indexList = indexes.ToReadOnly(); if (arrayType.GetArrayRank() != indexList.Count) { throw Error.IncorrectNumberOfIndexes(); } foreach (Expression e in indexList) { RequiresCanRead(e, nameof(indexes)); if (e.Type != typeof(int)) { throw Error.ArgumentMustBeArrayIndexType(nameof(indexes)); } } return new IndexExpression(array, null, indexList); } #endregion #region Property /// <summary> /// Creates an <see cref="IndexExpression"/> representing the access to an indexed property. /// </summary> /// <param name="instance">The object to which the property belongs. If the property is static/shared, it must be null.</param> /// <param name="propertyName">The name of the indexer.</param> /// <param name="arguments">An array of <see cref="Expression"/> objects that are used to index the property.</param> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression Property(Expression instance, string propertyName, params Expression[] arguments) { RequiresCanRead(instance, nameof(instance)); ContractUtils.RequiresNotNull(propertyName, nameof(propertyName)); PropertyInfo pi = FindInstanceProperty(instance.Type, propertyName, arguments); return MakeIndexProperty(instance, pi, nameof(propertyName), arguments.ToReadOnly()); } #region methods for finding a PropertyInfo by its name /// <summary> /// The method finds the instance property with the specified name in a type. The property's type signature needs to be compatible with /// the arguments if it is a indexer. If the arguments is null or empty, we get a normal property. /// </summary> private static PropertyInfo FindInstanceProperty(Type type, string propertyName, Expression[] arguments) { // bind to public names first BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy; PropertyInfo pi = FindProperty(type, propertyName, arguments, flags); if (pi == null) { flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy; pi = FindProperty(type, propertyName, arguments, flags); } if (pi == null) { if (arguments == null || arguments.Length == 0) { throw Error.InstancePropertyWithoutParameterNotDefinedForType(propertyName, type); } else { throw Error.InstancePropertyWithSpecifiedParametersNotDefinedForType(propertyName, GetArgTypesString(arguments), type, nameof(propertyName)); } } return pi; } private static string GetArgTypesString(Expression[] arguments) { StringBuilder argTypesStr = new StringBuilder(); argTypesStr.Append('('); for (int i = 0; i < arguments.Length; i++) { if (i != 0) { argTypesStr.Append(", "); } argTypesStr.Append(arguments[i]?.Type.Name); } argTypesStr.Append(')'); return argTypesStr.ToString(); } private static PropertyInfo FindProperty(Type type, string propertyName, Expression[] arguments, BindingFlags flags) { PropertyInfo property = null; foreach (PropertyInfo pi in type.GetProperties(flags)) { if (pi.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase) && IsCompatible(pi, arguments)) { if (property == null) { property = pi; } else { throw Error.PropertyWithMoreThanOneMatch(propertyName, type); } } } return property; } private static bool IsCompatible(PropertyInfo pi, Expression[] args) { MethodInfo mi = pi.GetGetMethod(nonPublic: true); ParameterInfo[] parms; if (mi != null) { parms = mi.GetParametersCached(); } else { mi = pi.GetSetMethod(nonPublic: true); if (mi == null) { return false; } //The setter has an additional parameter for the value to set, //need to remove the last type to match the arguments. parms = mi.GetParametersCached(); if (parms.Length == 0) { return false; } parms = parms.RemoveLast(); } if (args == null) { return parms.Length == 0; } if (parms.Length != args.Length) return false; for (int i = 0; i < args.Length; i++) { if (args[i] == null) return false; if (!TypeUtils.AreReferenceAssignable(parms[i].ParameterType, args[i].Type)) { return false; } } return true; } #endregion /// <summary> /// Creates an <see cref="IndexExpression"/> representing the access to an indexed property. /// </summary> /// <param name="instance">The object to which the property belongs. If the property is static/shared, it must be null.</param> /// <param name="indexer">The <see cref="PropertyInfo"/> that represents the property to index.</param> /// <param name="arguments">An array of <see cref="Expression"/> objects that are used to index the property.</param> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression Property(Expression instance, PropertyInfo indexer, params Expression[] arguments) { return Property(instance, indexer, (IEnumerable<Expression>)arguments); } /// <summary> /// Creates an <see cref="IndexExpression"/> representing the access to an indexed property. /// </summary> /// <param name="instance">The object to which the property belongs. If the property is static/shared, it must be null.</param> /// <param name="indexer">The <see cref="PropertyInfo"/> that represents the property to index.</param> /// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects that are used to index the property.</param> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression Property(Expression instance, PropertyInfo indexer, IEnumerable<Expression> arguments) => MakeIndexProperty(instance, indexer, nameof(indexer), arguments.ToReadOnly()); private static IndexExpression MakeIndexProperty(Expression instance, PropertyInfo indexer, string paramName, ReadOnlyCollection<Expression> argList) { ValidateIndexedProperty(instance, indexer, paramName, ref argList); return new IndexExpression(instance, indexer, argList); } // CTS places no restrictions on properties (see ECMA-335 8.11.3), // so we validate that the property conforms to CLS rules here. // // Does reflection help us out at all? Expression.Property skips all of // these checks, so either it needs more checks or we need less here. private static void ValidateIndexedProperty(Expression instance, PropertyInfo indexer, string paramName, ref ReadOnlyCollection<Expression> argList) { // If both getter and setter specified, all their parameter types // should match, with exception of the last setter parameter which // should match the type returned by the get method. // Accessor parameters cannot be ByRef. ContractUtils.RequiresNotNull(indexer, paramName); if (indexer.PropertyType.IsByRef) { throw Error.PropertyCannotHaveRefType(paramName); } if (indexer.PropertyType == typeof(void)) { throw Error.PropertyTypeCannotBeVoid(paramName); } ParameterInfo[] getParameters = null; MethodInfo getter = indexer.GetGetMethod(nonPublic: true); if (getter != null) { if (getter.ReturnType != indexer.PropertyType) { throw Error.PropertyTypeMustMatchGetter(paramName); } getParameters = getter.GetParametersCached(); ValidateAccessor(instance, getter, getParameters, ref argList, paramName); } MethodInfo setter = indexer.GetSetMethod(nonPublic: true); if (setter != null) { ParameterInfo[] setParameters = setter.GetParametersCached(); if (setParameters.Length == 0) { throw Error.SetterHasNoParams(paramName); } // valueType is the type of the value passed to the setter (last parameter) Type valueType = setParameters[setParameters.Length - 1].ParameterType; if (valueType.IsByRef) { throw Error.PropertyCannotHaveRefType(paramName); } if (setter.ReturnType != typeof(void)) { throw Error.SetterMustBeVoid(paramName); } if (indexer.PropertyType != valueType) { throw Error.PropertyTypeMustMatchSetter(paramName); } if (getter != null) { if (getter.IsStatic ^ setter.IsStatic) { throw Error.BothAccessorsMustBeStatic(paramName); } if (getParameters.Length != setParameters.Length - 1) { throw Error.IndexesOfSetGetMustMatch(paramName); } for (int i = 0; i < getParameters.Length; i++) { if (getParameters[i].ParameterType != setParameters[i].ParameterType) { throw Error.IndexesOfSetGetMustMatch(paramName); } } } else { ValidateAccessor(instance, setter, setParameters.RemoveLast(), ref argList, paramName); } } else if (getter == null) { throw Error.PropertyDoesNotHaveAccessor(indexer, paramName); } } private static void ValidateAccessor(Expression instance, MethodInfo method, ParameterInfo[] indexes, ref ReadOnlyCollection<Expression> arguments, string paramName) { ContractUtils.RequiresNotNull(arguments, nameof(arguments)); ValidateMethodInfo(method, nameof(method)); if ((method.CallingConvention & CallingConventions.VarArgs) != 0) { throw Error.AccessorsCannotHaveVarArgs(paramName); } if (method.IsStatic) { if (instance != null) { throw Error.OnlyStaticPropertiesHaveNullInstance(nameof(instance)); } } else { if (instance == null) { throw Error.OnlyStaticPropertiesHaveNullInstance(nameof(instance)); } RequiresCanRead(instance, nameof(instance)); ValidateCallInstanceType(instance.Type, method); } ValidateAccessorArgumentTypes(method, indexes, ref arguments, paramName); } private static void ValidateAccessorArgumentTypes(MethodInfo method, ParameterInfo[] indexes, ref ReadOnlyCollection<Expression> arguments, string paramName) { if (indexes.Length > 0) { if (indexes.Length != arguments.Count) { throw Error.IncorrectNumberOfMethodCallArguments(method, paramName); } Expression[] newArgs = null; for (int i = 0, n = indexes.Length; i < n; i++) { Expression arg = arguments[i]; ParameterInfo pi = indexes[i]; RequiresCanRead(arg, nameof(arguments), i); Type pType = pi.ParameterType; if (pType.IsByRef) throw Error.AccessorsCannotHaveByRefArgs(nameof(indexes), i); TypeUtils.ValidateType(pType, nameof(indexes), i); if (!TypeUtils.AreReferenceAssignable(pType, arg.Type)) { if (!TryQuote(pType, ref arg)) { throw Error.ExpressionTypeDoesNotMatchMethodParameter(arg.Type, pType, method, nameof(arguments), i); } } if (newArgs == null && arg != arguments[i]) { newArgs = new Expression[arguments.Count]; for (int j = 0; j < i; j++) { newArgs[j] = arguments[j]; } } if (newArgs != null) { newArgs[i] = arg; } } if (newArgs != null) { arguments = new TrueReadOnlyCollection<Expression>(newArgs); } } else if (arguments.Count > 0) { throw Error.IncorrectNumberOfMethodCallArguments(method, paramName); } } #endregion } }
using System; using System.Reflection; using System.Collections; namespace Stetic.Editor { public class IconSelectorItem: Gtk.EventBox { ArrayList icons = new ArrayList (); ArrayList labels = new ArrayList (); ArrayList names = new ArrayList (); int columns = 12; int iconSize = 16; int spacing = 3; int selIndex = -1; int sectionGap = 10; int lastSel = -1; int xmax; int ymax; string title; Gtk.Window tipWindow; bool inited; public IconSelectorItem (IntPtr ptr): base (ptr) { } public IconSelectorItem (string title) { this.title = title; int w, h; Gtk.Icon.SizeLookup (Gtk.IconSize.Menu, out w, out h); iconSize = w; this.Events |= Gdk.EventMask.PointerMotionMask; } protected override void OnSizeRequested (ref Gtk.Requisition req) { if (!inited) { CreateIcons (); inited = true; } base.OnSizeRequested (ref req); CalcSize (); Gtk.Requisition nr = new Gtk.Requisition (); nr.Width = xmax; nr.Height = ymax; req = nr; } protected virtual void CreateIcons () { } public int SelectedIndex { get { return selIndex; } } public string SelectedIcon { get { if (selIndex != -1) return (string) names [selIndex]; else return null; } } protected void AddIcon (string name, Gdk.Pixbuf pix, string label) { icons.Add (pix); labels.Add (label); names.Add (name); } protected void AddSeparator (string separator) { icons.Add (null); labels.Add (null); names.Add (separator); } protected override bool OnMotionNotifyEvent (Gdk.EventMotion ev) { ProcessMotionEvent ((int) ev.X, (int) ev.Y); return true; } internal void ProcessMotionEvent (int x, int y) { int ix, iy; GetIconIndex (x, y, out selIndex, out ix, out iy); if (selIndex != -1) { string name = labels [selIndex] as string; if (name == null || name.Length == 0) name = names [selIndex] as string; if (selIndex != lastSel) { HideTip (); ShowTip (ix, iy + iconSize + spacing*2, name); } } else HideTip (); lastSel = selIndex; QueueDraw (); } void ShowTip (int x, int y, string text) { if (GdkWindow == null) return; if (tipWindow == null) { tipWindow = new TipWindow (); Gtk.Label lab = new Gtk.Label (text); lab.Xalign = 0; lab.Xpad = 3; lab.Ypad = 3; tipWindow.Add (lab); } ((Gtk.Label)tipWindow.Child).Text = text; int w = tipWindow.Child.SizeRequest().Width; int ox, oy; GdkWindow.GetOrigin (out ox, out oy); tipWindow.Move (ox + x - (w/2) + (iconSize/2), oy + y); tipWindow.ShowAll (); } void HideTip () { if (tipWindow != null) { tipWindow.Destroy (); tipWindow = null; } } public override void Dispose () { HideTip (); base.Dispose (); } protected override bool OnLeaveNotifyEvent (Gdk.EventCrossing ev) { HideTip (); return base.OnLeaveNotifyEvent (ev); } internal void ProcessLeaveNotifyEvent (Gdk.EventCrossing ev) { HideTip (); } protected override bool OnExposeEvent (Gdk.EventExpose ev) { Draw (); return true; } void Draw () { int a,b; Expose (true, -1, -1, out a, out b); } void CalcSize () { int a,b; Expose (false, -1, -1, out a, out b); } void GetIconIndex (int x, int y, out int index, out int ix, out int iy) { index = Expose (false, x, y, out ix, out iy); } int Expose (bool draw, int testx, int testy, out int ix, out int iy) { int x = spacing; int y = spacing; int sx = spacing; int maxx = columns * (iconSize + spacing) + spacing; bool calcSize = (testx == -1); Pango.Layout layout = new Pango.Layout (this.PangoContext); Pango.FontDescription des = this.Style.FontDescription.Copy(); des.Size = 10 * (int) Pango.Scale.PangoScale; layout.FontDescription = des; layout.SetMarkup (title); layout.Width = -1; int w, h; int tborder = 1; layout.GetPixelSize (out w, out h); if (draw) { GdkWindow.DrawRectangle (this.Style.DarkGC (Gtk.StateType.Normal), true, x, y, Allocation.Width + tborder*2, h + tborder*2); GdkWindow.DrawLayout (this.Style.ForegroundGC (Gtk.StateType.Normal), x + tborder + 2, y + tborder, layout); } if (calcSize) xmax = 0; y += h + spacing*2 + tborder*2; for (int n=0; n<icons.Count; n++) { string cmd = names [n] as string; Gdk.Pixbuf pix = icons [n] as Gdk.Pixbuf; if (cmd == "-") { if (x > sx) { y += iconSize + spacing; } x = sx; y -= spacing; if (draw) { Gdk.Rectangle rect = new Gdk.Rectangle (0, y+(sectionGap/2), Allocation.Width - x, 1); Gtk.Style.PaintHline (this.Style, this.GdkWindow, Gtk.StateType.Normal, rect, this, "", rect.X, rect.Right, rect.Y); } y += sectionGap; continue; } if (cmd == "|") { if (x == sx) continue; x += spacing; if (draw) { Gdk.Rectangle rect = new Gdk.Rectangle (x, y, 1, iconSize); Gtk.Style.PaintVline (this.Style, this.GdkWindow, Gtk.StateType.Normal, rect, this, "", rect.Y, rect.Bottom, rect.X); } x += spacing*2; continue; } if (testx != -1 && testx >= (x - spacing/2) && testx < (x + iconSize + spacing) && testy >= (y - spacing/2) && testy < (y + iconSize + spacing)) { ix = x; iy = y; return n; } if (draw) { Gtk.StateType state = (n == selIndex) ? Gtk.StateType.Selected : Gtk.StateType.Normal; if (n == selIndex) GdkWindow.DrawRectangle (this.Style.BackgroundGC (state), true, x-spacing, y-spacing, iconSize + spacing*2, iconSize + spacing*2); GdkWindow.DrawPixbuf (this.Style.ForegroundGC (state), pix, 0, 0, x, y, pix.Width, pix.Height, Gdk.RgbDither.None, 0, 0); } x += (iconSize + spacing); if (calcSize && x > xmax) xmax = x; if (x >= maxx) { x = sx; y += iconSize + spacing; } } if (calcSize) { if (x > sx) y += iconSize + spacing; ymax = y; } ix = iy = 0; return -1; } } class TipWindow: Gtk.Window { public TipWindow (): base (Gtk.WindowType.Popup) { } protected override bool OnExposeEvent (Gdk.EventExpose ev) { base.OnExposeEvent (ev); Gtk.Requisition req = SizeRequest (); Gtk.Style.PaintFlatBox (this.Style, this.GdkWindow, Gtk.StateType.Normal, Gtk.ShadowType.Out, Gdk.Rectangle.Zero, this, "tooltip", 0, 0, req.Width, req.Height); return true; } } }
using Kitware.VTK; using System; // input file is C:\VTK\Graphics\Testing\Tcl\TestRectilinearGridToTetrahedra.tcl // output file is AVTestRectilinearGridToTetrahedra.cs /// <summary> /// The testing class derived from AVTestRectilinearGridToTetrahedra /// </summary> public class AVTestRectilinearGridToTetrahedraClass { /// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVTestRectilinearGridToTetrahedra(String[] argv) { //Prefix Content is: "" //## SetUp the pipeline[] FormMesh = new vtkRectilinearGridToTetrahedra(); FormMesh.SetInput((double)4, (double)2, (double)2, (double)1, (double)1, (double)1, (double)0.001); FormMesh.RememberVoxelIdOn(); TetraEdges = new vtkExtractEdges(); TetraEdges.SetInputConnection((vtkAlgorithmOutput)FormMesh.GetOutputPort()); tubes = new vtkTubeFilter(); tubes.SetInputConnection((vtkAlgorithmOutput)TetraEdges.GetOutputPort()); tubes.SetRadius((double)0.05); tubes.SetNumberOfSides((int)6); //## Run the pipeline 3 times, with different conversions to TetMesh[] Tubes[0] = new vtkPolyData(); FormMesh.SetTetraPerCellTo5(); tubes.Update(); Tubes[0].DeepCopy((vtkDataObject)tubes.GetOutput()); Tubes[1] = new vtkPolyData(); FormMesh.SetTetraPerCellTo6(); tubes.Update(); Tubes[1].DeepCopy((vtkDataObject)tubes.GetOutput()); Tubes[2] = new vtkPolyData(); FormMesh.SetTetraPerCellTo12(); tubes.Update(); Tubes[2].DeepCopy((vtkDataObject)tubes.GetOutput()); //## Run the pipeline once more, this time converting some cells to[] //## 5 and some data to 12 TetMesh[] //## Determine which cells are which[] DivTypes = new vtkIntArray(); numCell = (long)((vtkDataSet)FormMesh.GetInput()).GetNumberOfCells(); DivTypes.SetNumberOfValues((int)numCell); i = 0; while ((i) < numCell) { DivTypes.SetValue((int)i, (int)5 + (7 * (i % 4))); i = i + 1; } //## Finish this pipeline[] Tubes[3] = new vtkPolyData(); FormMesh.SetTetraPerCellTo5And12(); ((vtkRectilinearGrid)FormMesh.GetInput()).GetCellData().SetScalars(DivTypes); tubes.Update(); Tubes[3].DeepCopy((vtkDataObject)tubes.GetOutput()); //## Finish the 4 pipelines[] i = 1; while ((i) < 5) { mapEdges[i] = vtkPolyDataMapper.New(); mapEdges[i].SetInput((vtkPolyData)Tubes[i - 1]); edgeActor[i] = new vtkActor(); edgeActor[i].SetMapper((vtkMapper)mapEdges[i]); edgeActor[i].GetProperty().SetColor((double)0.2000, 0.6300, 0.7900); edgeActor[i].GetProperty().SetSpecularColor((double)1, (double)1, (double)1); edgeActor[i].GetProperty().SetSpecular((double)0.3); edgeActor[i].GetProperty().SetSpecularPower((double)20); edgeActor[i].GetProperty().SetAmbient((double)0.2); edgeActor[i].GetProperty().SetDiffuse((double)0.8); ren[i] = vtkRenderer.New(); ren[i].AddActor((vtkProp)edgeActor[i]); ren[i].SetBackground((double)0, (double)0, (double)0); ren[i].ResetCamera(); ren[i].GetActiveCamera().Zoom((double)1); ren[i].GetActiveCamera().SetPosition((double)1.73906, (double)12.7987, (double)-0.257808); ren[i].GetActiveCamera().SetViewUp((double)0.992444, (double)0.00890284, (double)-0.122379); ren[i].GetActiveCamera().SetClippingRange((double)9.36398, (double)15.0496); i = i + 1; } // Create graphics objects[] // Create the rendering window, renderer, and interactive renderer[] renWin = vtkRenderWindow.New(); renWin.AddRenderer(ren[1]); renWin.AddRenderer(ren[2]); renWin.AddRenderer(ren[3]); renWin.AddRenderer(ren[4]); renWin.SetSize(600, 300); iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow((vtkRenderWindow)renWin); // Add the actors to the renderer, set the background and size[] ren[1].SetViewport((double).75, (double)0, (double)1, (double)1); ren[2].SetViewport((double).50, (double)0, (double).75, (double)1); ren[3].SetViewport((double).25, (double)0, (double).50, (double)1); ren[4].SetViewport((double)0, (double)0, (double).25, (double)1); // render the image[] //[] iren.Initialize(); // prevent the tk window from showing up then start the event loop[] //deleteAllVTKObjects(); } static string VTK_DATA_ROOT; static int threshold; static vtkRectilinearGridToTetrahedra FormMesh; static vtkExtractEdges TetraEdges; static vtkTubeFilter tubes; static vtkPolyData[] Tubes = new vtkPolyData[4]; static vtkIntArray DivTypes; static long numCell; static int i; static vtkPolyDataMapper[] mapEdges = new vtkPolyDataMapper[100]; static vtkActor[] edgeActor = new vtkActor[100]; static vtkRenderer[] ren = new vtkRenderer[100]; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; ///<summary> A Get Method for Static Variables </summary> public static string GetVTK_DATA_ROOT() { return VTK_DATA_ROOT; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_DATA_ROOT(string toSet) { VTK_DATA_ROOT = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getthreshold() { return threshold; } ///<summary> A Set Method for Static Variables </summary> public static void Setthreshold(int toSet) { threshold = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRectilinearGridToTetrahedra GetFormMesh() { return FormMesh; } ///<summary> A Set Method for Static Variables </summary> public static void SetFormMesh(vtkRectilinearGridToTetrahedra toSet) { FormMesh = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkExtractEdges GetTetraEdges() { return TetraEdges; } ///<summary> A Set Method for Static Variables </summary> public static void SetTetraEdges(vtkExtractEdges toSet) { TetraEdges = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkTubeFilter Gettubes() { return tubes; } ///<summary> A Set Method for Static Variables </summary> public static void Settubes(vtkTubeFilter toSet) { tubes = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyData[] GetTubes() { return Tubes; } ///<summary> A Set Method for Static Variables </summary> public static void SetTubes(vtkPolyData[] toSet) { Tubes = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkIntArray GetDivTypes() { return DivTypes; } ///<summary> A Set Method for Static Variables </summary> public static void SetDivTypes(vtkIntArray toSet) { DivTypes = toSet; } ///<summary> A Get Method for Static Variables </summary> public static long GetnumCell() { return numCell; } ///<summary> A Set Method for Static Variables </summary> public static void SetnumCell(int toSet) { numCell = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Geti() { return i; } ///<summary> A Set Method for Static Variables </summary> public static void Seti(int toSet) { i = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper[] GetmapEdges() { return mapEdges; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapEdges(vtkPolyDataMapper[] toSet) { mapEdges = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor[] GetedgeActor() { return edgeActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetedgeActor(vtkActor[] toSet) { edgeActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderer[] Getren() { return ren; } ///<summary> A Set Method for Static Variables </summary> public static void Setren(vtkRenderer[] toSet) { ren = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindow GetrenWin() { return renWin; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindowInteractor Getiren() { return iren; } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if (renWin != null) { renWin.Dispose(); } if (iren != null) { iren.Dispose(); } if (FormMesh != null) { FormMesh.Dispose(); } if (TetraEdges != null) { TetraEdges.Dispose(); } if (tubes != null) { tubes.Dispose(); } if (Tubes[0] != null) { Tubes[0].Dispose(); } if (Tubes[1] != null) { Tubes[1].Dispose(); } if (Tubes[2] != null) { Tubes[2].Dispose(); } if (Tubes[3] != null) { Tubes[3].Dispose(); } if (DivTypes != null) { DivTypes.Dispose(); } for (int i = 0; i < 100; i++) { if (mapEdges[i] != null) { mapEdges[i].Dispose(); } if (edgeActor[i] != null) { edgeActor[i].Dispose(); } if (ren[i] != null) { ren[i].Dispose(); } } } } //--- end of script --//
using System; using UnityEngine; [System.Serializable] public class Animations { public int lIdle = 0; public int rIdle = 1; public int lFallingIdle = 2; public int rFallingIdle = 3; public int lWallGrab = 4; public int rWallGrab = 5; public int lRun = 6; public int rRun = 7; public int lJump = 8; public int rJump = 9; public int lJumpLeft = 10; public int rJumpRight = 11; public int lCrouch = 12; public int rCrouch = 13; public int lAttack = 14; public int rAttack = 15; public int lRunningAttack = 16; public int rRunningAttack = 17; public int lDeath = 18; public int rDeath = 19; } public class ActorController : MonoBehaviour { public enum ActorAction { RunLeft, RunRight, Idle, Crouch, Jump, Attack, RunLeftAttack, RunRightAttack } private enum JumpMode { JumpUp, JumpLeft, JumpRight } public float maxHorizontalVelocity = 2.5f; public float maxHorizontalVelocityWhileAttacking = 1.0f; public float horizontalForce = 10; public float jumpForce = 600; public float jumpLength = 3; public float jumpTimeout = -10; public bool canWallJump = true; public float attackTimeout = 0.4f; public float movingAttackTimeout = 0.6f; public float normalHeight = 0.9f; public float normalWidth = 0.4f; public Vector3 normalOffset; public float crouchHeight = 0.5f; public float crouchWidth = 0.5f; public Vector3 crouchOffset; public float deadHeight = 0.8f; public float deadWidth = 0.3f; public Vector3 deadOffset; public Animations animations; public Vector3 leftFull = new Vector3(-1.0f, -0.15f, 0.0f); public Vector3 leftHalf = new Vector3(-1.0f, -0.2f, -1.0f); public Vector3 rightHalf = new Vector3(1.0f, -0.2f, -1.0f); public Vector3 rightFull = new Vector3(1.0f, -0.15f, 0.0f); public ActorState actorState; protected float horizontalIntention = 0; protected float horizontalLookIntention = 0; protected bool jumpIntention = false; protected bool crouchIntention = false; protected bool attackIntention = false; protected bool alive = true; protected ActorAction currentAction = ActorAction.Idle; protected Vector3 facingDirection; protected int lastActiveAnimation; protected bool isCrouching; private float attackTimer = 0; private Renderer healthbarRenderer; private int jumpFramesLeft = 0; private Vector3 jumpUpForce; private Vector3 jumpLeftForce; private Vector3 jumpRightForce; private JumpMode jumpMode = JumpMode.JumpUp; public void Start() { ActorControllerStart_ (); } public void FixedUpdate() { ActorControllerFixedUpdate_(); } public void OnDestroy() { ActorControllerOnDestroy_(); } protected virtual void BeginAttack() { } protected void ActorControllerStart_() { Transform healthbar = transform.Find ("Healthbar"); if (healthbar != null) { healthbarRenderer = healthbar.GetComponent<Renderer>(); if (healthbarRenderer != null) { actorState = new ActorState(healthbarRenderer); } } jumpUpForce = new Vector3(0, jumpForce * 0.9f, 0); jumpLeftForce = new Vector3(-jumpForce * 0.5f, jumpForce * 0.8f, 0); jumpRightForce = new Vector3(jumpForce * 0.5f, jumpForce * 0.8f, 0); leftFull.Normalize(); leftHalf.Normalize(); rightHalf.Normalize(); rightFull.Normalize(); facingDirection = leftHalf; } protected void ActorControllerFixedUpdate_() { // Calculate some useful stats about the current state of the actor CapsuleCollider collider = GetComponent<CapsuleCollider>(); Ray down = new Ray(transform.position + collider.center, transform.up * -1f); float downOffset = collider.height * 0.5f + 0.05f; Ray left = new Ray(transform.position + collider.center, transform.right * -1f); float leftOffset = collider.radius + 0.1f; Ray right = new Ray(transform.position + collider.center, transform.right); float rightOffset = collider.radius + 0.1f; bool onGround = Physics.Raycast(down, downOffset); bool onWallLeft = Physics.Raycast(left, rightOffset); bool onWallRight = Physics.Raycast(right, leftOffset); float hVelocity = rigidbody.velocity.x; // Calculate new currentAction, facingDirection, and jump* values. if (alive) { if (Mathf.Abs (horizontalIntention) > 0.1f) currentAction = horizontalIntention > 0 ? ActorAction.RunRight : ActorAction.RunLeft; else currentAction = ActorAction.Idle; if (crouchIntention) // && (!onGround || Mathf.Abs (hVelocity) < 0.2f)) currentAction = ActorAction.Crouch; if (Mathf.Abs(hVelocity) > 0.1f) facingDirection = hVelocity > 0 ? rightFull : leftFull; else if (Mathf.Abs (horizontalLookIntention) > 0.1f) facingDirection = horizontalLookIntention > 0 ? rightFull : leftFull; else facingDirection = facingDirection.x > 0 ? rightHalf : leftHalf; if (jumpIntention) { if (jumpFramesLeft <= jumpTimeout) { if (canWallJump && onWallLeft && !onWallRight) { jumpFramesLeft = (int)jumpLength; jumpMode = JumpMode.JumpRight; facingDirection = rightFull; } else if (canWallJump && onWallRight && !onWallLeft) { jumpFramesLeft = (int)jumpLength; jumpMode = JumpMode.JumpLeft; facingDirection = leftFull; } else if (onGround) { jumpFramesLeft = (int)jumpLength; jumpMode = JumpMode.JumpUp; } } } if (jumpFramesLeft > 0) currentAction = ActorAction.Jump; // Update attack info if (attackTimer > 0) attackTimer -= Time.fixedDeltaTime; else if (attackIntention) { if (currentAction == ActorAction.Idle) { currentAction = ActorAction.Attack; attackTimer = attackTimeout; } else if (currentAction == ActorAction.RunLeft) { currentAction = ActorAction.RunLeftAttack; attackTimer = movingAttackTimeout; } else if (currentAction == ActorAction.RunRight) { currentAction = ActorAction.RunRightAttack; attackTimer = movingAttackTimeout; } BeginAttack(); } } else // dead { currentAction = ActorAction.Idle; } // Update animation if necessary bool facingRight = facingDirection.x > 0; bool startAnimImmediately = false; bool actorCrouching = false; int animationId = facingRight ? animations.rIdle : animations.lIdle; if (!alive) { animationId = facingRight ? animations.rDeath : animations.lDeath; startAnimImmediately = true; } else if (currentAction == ActorAction.Jump) { if (jumpMode == JumpMode.JumpLeft) animationId = animations.lJumpLeft; else if (jumpMode == JumpMode.JumpRight) animationId = animations.rJumpRight; else animationId = facingRight ? animations.rJump : animations.lJump; startAnimImmediately = true; } else if (!onGround) { if (currentAction == ActorAction.RunLeft) animationId = animations.lRun; else if (currentAction == ActorAction.RunRight) animationId = animations.rRun; else if (currentAction == ActorAction.Attack) { animationId = facingRight ? animations.rAttack : animations.lAttack; startAnimImmediately = true; } else if (currentAction == ActorAction.RunLeftAttack) { animationId = animations.lRunningAttack; startAnimImmediately = true; } else if (currentAction == ActorAction.RunRightAttack) { animationId = animations.rRunningAttack; startAnimImmediately = true; } else if (onWallLeft && currentAction == ActorAction.Crouch) { animationId = animations.rWallGrab; facingDirection = rightFull; // this may be a confusing place for this but anywhere else would require redundant if statements startAnimImmediately = true; } else if (onWallRight && currentAction == ActorAction.Crouch) { animationId = animations.lWallGrab; facingDirection = leftFull; // this may be a confusing place for this but anywhere else would require redundant if statements startAnimImmediately = true; } else animationId = facingRight ? animations.rFallingIdle : animations.lFallingIdle; if (isCrouching && currentAction == ActorAction.Crouch) actorCrouching = true; } else // on ground, not jumping { if (currentAction == ActorAction.Attack || currentAction == ActorAction.RunLeftAttack || currentAction == ActorAction.RunRightAttack) { startAnimImmediately = true; if (hVelocity > 0.2f || (hVelocity > 0 && currentAction == ActorAction.RunRightAttack)) animationId = animations.rRunningAttack; else if (hVelocity < -0.2f || (hVelocity < 0 && currentAction == ActorAction.RunLeftAttack)) animationId = animations.lRunningAttack; else animationId = facingRight ? animations.rAttack : animations.lAttack; } else if (hVelocity > 0.2f || (hVelocity > 0 && currentAction == ActorAction.RunRight)) animationId = animations.rRun; else if (hVelocity < -0.2f || (hVelocity < 0 && currentAction == ActorAction.RunLeft)) animationId = animations.lRun; else if (currentAction == ActorAction.Crouch) { animationId = facingRight ? animations.rCrouch : animations.lCrouch; actorCrouching = true; } } if (actorCrouching != isCrouching) { isCrouching = actorCrouching; if (isCrouching) { collider.height = crouchHeight; collider.radius = crouchWidth * 0.5f; collider.center = crouchOffset; //collider.direction = 1; // y axis } else { collider.height = normalHeight; collider.radius = normalWidth * 0.5f; collider.center = normalOffset; //collider.direction = 1; // y axis } } if (animationId != lastActiveAnimation) { lastActiveAnimation = animationId; if (startAnimImmediately) GetComponent<SpriteController>().startAnimation(animationId); else GetComponent<SpriteController>().queueAnimation(animationId); if (!alive) { collider.height = deadHeight; collider.radius = deadWidth * 0.5f; collider.center = deadOffset; //collider.direction = 0; // change capsule direction to x axis. } } // Apply forces based on currentAction if (currentAction == ActorAction.Crouch) { if (onGround) { rigidbody.AddForce (Physics.gravity * 2.0f); } else if (canWallJump && (onWallLeft || onWallRight)) { Vector3 newVel = rigidbody.velocity; newVel.x *= 0.2f; newVel.y *= 0.9f; rigidbody.velocity = newVel; rigidbody.AddForce (Physics.gravity * -1.0f); } } if (currentAction == ActorAction.RunLeft || currentAction == ActorAction.RunRight) { if (onGround) { rigidbody.AddForce(Physics.gravity * -0.75f); if (Mathf.Abs (hVelocity) < maxHorizontalVelocity) rigidbody.AddForce ((currentAction == ActorAction.RunRight ? horizontalForce : -horizontalForce), 0.0f, 0.0f); } else if (Mathf.Abs (hVelocity) < maxHorizontalVelocity) { if (!onWallLeft && currentAction == ActorAction.RunLeft) { rigidbody.AddForce(horizontalForce * -0.75f, 0.0f, 0.0f); } else if (!onWallRight && currentAction == ActorAction.RunRight) { rigidbody.AddForce(horizontalForce * 0.75f, 0.0f, 0.0f); } } } else if (currentAction == ActorAction.RunLeftAttack || currentAction == ActorAction.RunRightAttack) { if (onGround) { rigidbody.AddForce(Physics.gravity * -0.75f); if (Mathf.Abs (hVelocity) < maxHorizontalVelocityWhileAttacking) rigidbody.AddForce ((currentAction == ActorAction.RunRightAttack ? horizontalForce : -horizontalForce), 0.0f, 0.0f); } else if (Mathf.Abs (hVelocity) < maxHorizontalVelocityWhileAttacking) { if (!onWallLeft && currentAction == ActorAction.RunLeftAttack) { rigidbody.AddForce(horizontalForce * -0.75f, 0.0f, 0.0f); } else if (!onWallRight && currentAction == ActorAction.RunRightAttack) { rigidbody.AddForce(horizontalForce * 0.75f, 0.0f, 0.0f); } } } else if (currentAction == ActorAction.Idle && !alive && onGround) { rigidbody.AddForce (Physics.gravity * 6.0f); } if (jumpFramesLeft > jumpTimeout) { if (jumpFramesLeft > 0) { if (jumpFramesLeft == jumpLength) { Vector3 newVel = rigidbody.velocity; newVel.y = Mathf.Abs(newVel.y) * 0.3f; if (jumpMode != JumpMode.JumpUp) newVel.x = Mathf.Abs (newVel.x) * 0.1f; rigidbody.velocity = newVel; } switch (jumpMode) { case JumpMode.JumpUp: rigidbody.AddForce(jumpUpForce); break; case JumpMode.JumpLeft: rigidbody.AddForce(jumpLeftForce); facingDirection = leftFull; break; case JumpMode.JumpRight: rigidbody.AddForce(jumpRightForce); facingDirection = rightFull; break; default: break; } } --jumpFramesLeft; } } protected void ActorControllerOnDestroy_() { if (healthbarRenderer != null) Destroy(healthbarRenderer.material); } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Linq; using Avalonia.Data.Core; using Avalonia.Markup.Parsers; using Xunit; namespace Avalonia.Markup.UnitTests.Parsers { public class SelectorGrammarTests { [Fact] public void OfType() { var result = SelectorGrammar.Parse("Button"); Assert.Equal( new[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button", Xmlns = "" } }, result); } [Fact] public void NamespacedOfType() { var result = SelectorGrammar.Parse("x|Button"); Assert.Equal( new[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button", Xmlns = "x" } }, result); } [Fact] public void Name() { var result = SelectorGrammar.Parse("#foo"); Assert.Equal( new[] { new SelectorGrammar.NameSyntax { Name = "foo" }, }, result); } [Fact] public void OfType_Name() { var result = SelectorGrammar.Parse("Button#foo"); Assert.Equal( new SelectorGrammar.ISyntax[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button" }, new SelectorGrammar.NameSyntax { Name = "foo" }, }, result); } [Fact] public void Is() { var result = SelectorGrammar.Parse(":is(Button)"); Assert.Equal( new[] { new SelectorGrammar.IsSyntax { TypeName = "Button", Xmlns = "" } }, result); } [Fact] public void Is_Name() { var result = SelectorGrammar.Parse(":is(Button)#foo"); Assert.Equal( new SelectorGrammar.ISyntax[] { new SelectorGrammar.IsSyntax { TypeName = "Button" }, new SelectorGrammar.NameSyntax { Name = "foo" }, }, result); } [Fact] public void NamespacedIs_Name() { var result = SelectorGrammar.Parse(":is(x|Button)#foo"); Assert.Equal( new SelectorGrammar.ISyntax[] { new SelectorGrammar.IsSyntax { TypeName = "Button", Xmlns = "x" }, new SelectorGrammar.NameSyntax { Name = "foo" }, }, result); } [Fact] public void Class() { var result = SelectorGrammar.Parse(".foo"); Assert.Equal( new[] { new SelectorGrammar.ClassSyntax { Class = "foo" } }, result); } [Fact] public void Pseudoclass() { var result = SelectorGrammar.Parse(":foo"); Assert.Equal( new[] { new SelectorGrammar.ClassSyntax { Class = ":foo" } }, result); } [Fact] public void OfType_Class() { var result = SelectorGrammar.Parse("Button.foo"); Assert.Equal( new SelectorGrammar.ISyntax[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button" }, new SelectorGrammar.ClassSyntax { Class = "foo" }, }, result); } [Fact] public void OfType_Child_Class() { var result = SelectorGrammar.Parse("Button > .foo"); Assert.Equal( new SelectorGrammar.ISyntax[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button" }, new SelectorGrammar.ChildSyntax { }, new SelectorGrammar.ClassSyntax { Class = "foo" }, }, result); } [Fact] public void OfType_Child_Class_No_Spaces() { var result = SelectorGrammar.Parse("Button>.foo"); Assert.Equal( new SelectorGrammar.ISyntax[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button" }, new SelectorGrammar.ChildSyntax { }, new SelectorGrammar.ClassSyntax { Class = "foo" }, }, result); } [Fact] public void OfType_Descendant_Class() { var result = SelectorGrammar.Parse("Button .foo"); Assert.Equal( new SelectorGrammar.ISyntax[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button" }, new SelectorGrammar.DescendantSyntax { }, new SelectorGrammar.ClassSyntax { Class = "foo" }, }, result); } [Fact] public void OfType_Template_Class() { var result = SelectorGrammar.Parse("Button /template/ .foo"); Assert.Equal( new SelectorGrammar.ISyntax[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button" }, new SelectorGrammar.TemplateSyntax { }, new SelectorGrammar.ClassSyntax { Class = "foo" }, }, result); } [Fact] public void OfType_Property() { var result = SelectorGrammar.Parse("Button[Foo=bar]"); Assert.Equal( new SelectorGrammar.ISyntax[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button" }, new SelectorGrammar.PropertySyntax { Property = "Foo", Value = "bar" }, }, result); } [Fact] public void Namespace_Alone_Fails() { Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse("ns|")); } [Fact] public void Dot_Alone_Fails() { Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse(". dot")); } [Fact] public void Invalid_Identifier_Fails() { Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse("%foo")); } [Fact] public void Invalid_Class_Fails() { Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse(".%foo")); } } }
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 HomeBot.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; } } }
/* Josip Medved <[email protected]> * www.medo64.com * MIT License */ //2021-11-25: Refactored to use pattern matching //2021-11-01: Added support for DateTimeOffset //2021-03-04: Refactored for .NET 5 //2017-09-17: Refactored for .NET Standard 2.0 // Allowing custom DateTime for GetCode // Removing GetCode overload for various digit lengths - use Digits instead //2015-02-12: Initial version namespace Medo.Security.Cryptography; using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; /// <summary> /// Implementation of HOTP (RFC 4226) and TOTP (RFC 6238) one-time password algorithms. /// </summary> /// <example> /// <code> /// var otp = new OneTimePassword("MZxw6\tyTboI="); /// // or otp = new OneTimePassword(); /// // var secret = otp.GetBase32Secret(SecretFormatFlags.None)); /// if (otp.IsCodeValid(755224)) { /// // do something /// } /// </code> /// </example> public sealed class OneTimePassword : IDisposable { /// <summary> /// Create new instance with random 160-bit secret. /// </summary> public OneTimePassword() : this(randomizeBuffer: true) { _secretLength = 20; //160 bits ProtectSecret(); } /// <summary> /// Create new instance with predefined secret. /// </summary> /// <param name="secret">Secret. It should not be shorter than 128 bits (16 bytes). Minimum of 160 bits (20 bytes) is strongly recommended.</param> /// <exception cref="ArgumentNullException">Secret cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Secret cannot be longer than 8192 bits (1024 bytes).</exception> public OneTimePassword(byte[] secret) : this(false) { if (secret == null) { throw new ArgumentNullException(nameof(secret), "Secret cannot be null."); } if (secret.Length > MaxSecretLength) { throw new ArgumentOutOfRangeException(nameof(secret), "Secret cannot be longer than 8192 bits (1024 bytes)."); } Buffer.BlockCopy(secret, 0, _secretBuffer, 0, secret.Length); _secretLength = secret.Length; ProtectSecret(); } /// <summary> /// Create new instance with predefined secret. /// </summary> /// <param name="secret">Secret in Base32 encoding. It should not be shorter than 128 bits (16 bytes). Minimum of 160 bits (20 bytes) is strongly recommended.</param> /// <exception cref="ArgumentNullException">Secret cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Secret is not a valid Base32 string. -or- Secret cannot be longer than 8192 bits (1024 bytes).</exception> public OneTimePassword(string secret) : this(false) { if (secret == null) { throw new ArgumentNullException(nameof(secret), "Secret cannot be null."); } try { FromBase32(secret, _secretBuffer, out _secretLength); } catch (IndexOutOfRangeException) { throw new ArgumentOutOfRangeException(nameof(secret), "Secret cannot be longer than 8192 bits (1024 bytes)."); } catch (Exception) { throw new ArgumentOutOfRangeException(nameof(secret), "Secret is not a valid Base32 string."); } ProtectSecret(); } private OneTimePassword(bool randomizeBuffer) { _secretBuffer = GC.AllocateUninitializedArray<byte>(MaxSecretLength, pinned: true); using var rng = RandomNumberGenerator.Create(); if (randomizeBuffer) { rng.GetBytes(_secretBuffer); } _randomIV = new byte[16]; RandomNumberGenerator.Create().GetBytes(_randomIV); _randomKey = new byte[16]; RandomNumberGenerator.Create().GetBytes(_randomKey); } #region Setup private int _digits = 6; /// <summary> /// Gets/Sets number of digits to return. /// Number of digits should be kept between 6 and 8 for best results. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Number of digits to return must be between 4 and 9.</exception> public int Digits { get { return _digits; } set { if (value is < 4 or > 9) { throw new ArgumentOutOfRangeException(nameof(value), "Number of digits to return must be between 4 and 9."); } _digits = value; } } private int _timeStep = 30; /// <summary> /// Gets/sets time step in seconds for TOTP algorithm. /// Value must be between 15 and 300 seconds. /// If value is zero, time step won't be used and HOTP will be resulting protocol. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Time step must be between 15 and 300 seconds.</exception> public int TimeStep { get { return _timeStep; } set { if (value == 0) { _timeStep = 0; Counter = 0; } else { if (value is < 15 or > 300) { throw new ArgumentOutOfRangeException(nameof(value), "Time step must be between 15 and 300 seconds."); } _timeStep = value; } } } private long _counter = 0; /// <summary> /// Gets/sets counter value. /// Value can only be set in HOTP mode (if time step is zero). /// </summary> /// <exception cref="ArgumentOutOfRangeException">Counter value must be a positive number.</exception> /// <exception cref="NotSupportedException">Counter value can only be set in HOTP mode (time step is zero).</exception> public long Counter { get { if (TimeStep == 0) { return _counter; } else { return GetTimeBasedCounter(DateTime.UtcNow, TimeStep); } } set { if (TimeStep == 0) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), "Counter value must be a positive number."); } _counter = value; } else { throw new NotSupportedException("Counter value can only be set in HOTP mode (time step is zero)."); } } } private static long GetTimeBasedCounter(DateTimeOffset time, int timeStep) { var seconds = time.ToUnixTimeSeconds(); return (seconds / timeStep); } private OneTimePasswordAlgorithm _algorithm = OneTimePasswordAlgorithm.Sha1; /// <summary> /// Gets/sets crypto algorithm. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Unknown algorithm.</exception> public OneTimePasswordAlgorithm Algorithm { get { return _algorithm; } set { switch (value) { case OneTimePasswordAlgorithm.Sha1: case OneTimePasswordAlgorithm.Sha256: case OneTimePasswordAlgorithm.Sha512: break; default: throw new ArgumentOutOfRangeException(nameof(value), "Unknown algorithm."); } _algorithm = value; } } #endregion Setup #region Code /// <summary> /// Returns code. /// In HOTP mode (time step is zero), counter will be automatically increased. /// </summary> public int GetCode() { var code = GetCode(Digits, Counter); if (TimeStep == 0) { Counter += 1; } return code; } /// <summary> /// Returns code. /// Number of digits should be kept between 6 and 8 for best results. /// </summary> /// <param name="time">UTC or Local time for code retrieval.</param> /// <exception cref="ArgumentOutOfRangeException">Time must be either UTC or Local.</exception> /// <exception cref="NotSupportedException">Cannot specify time in HOTP mode (time step is zero).</exception> public int GetCode(DateTime time) { if (time.Kind is not DateTimeKind.Utc and not DateTimeKind.Local) { throw new ArgumentOutOfRangeException(nameof(time), "Time must be either UTC or Local."); } return GetCode(new DateTimeOffset(time)); } /// <summary> /// Returns code. /// Number of digits should be kept between 6 and 8 for best results. /// </summary> /// <param name="utcTime">UTC time for code retrieval.</param> /// <exception cref="NotSupportedException">Cannot specify time in HOTP mode (time step is zero).</exception> public int GetCode(DateTimeOffset time) { if (TimeStep == 0) { throw new NotSupportedException("Cannot specify time in HOTP mode (time step is zero)."); } return GetCode(Digits, GetTimeBasedCounter(time, TimeStep)); } private int cachedDigits; private long cachedCounter = -1; private int cachedCode; private int GetCode(int digits, long counter) { if ((cachedCounter == counter) && (cachedDigits == digits)) { return cachedCode; } //to avoid recalculation if all is the same var counterBytes = BitConverter.GetBytes(counter); if (BitConverter.IsLittleEndian) { Array.Reverse(counterBytes, 0, 8); } byte[] hash; var secret = GetSecret(); try { using HMAC hmac = Algorithm switch { OneTimePasswordAlgorithm.Sha512 => new HMACSHA512(secret), OneTimePasswordAlgorithm.Sha256 => new HMACSHA256(secret), _ => new HMACSHA1(secret), }; hash = hmac.ComputeHash(counterBytes); } finally { ClearSecret(secret); } var offset = hash[^1] & 0x0F; var truncatedHash = new byte[] { (byte)(hash[offset + 0] & 0x7F), hash[offset + 1], hash[offset + 2], hash[offset + 3] }; if (BitConverter.IsLittleEndian) { Array.Reverse(truncatedHash, 0, 4); } var number = BitConverter.ToInt32(truncatedHash, 0); var code = number % DigitsDivisor[digits]; cachedCounter = counter; cachedDigits = digits; cachedCode = code; return code; } private static readonly int[] DigitsDivisor = new int[] { 0, 0, 0, 0, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; #endregion Code #region Validate /// <summary> /// Returns true if code has been validated. /// </summary> /// <param name="code">Code to validate.</param> /// <exception cref="ArgumentOutOfRangeException">Code must contain only numbers and whitespace.</exception> /// <exception cref="ArgumentNullException">Code cannot be null.</exception> public bool IsCodeValid(string code) { if (code == null) { throw new ArgumentNullException(nameof(code), "Code cannot be null."); } var number = 0; foreach (var ch in code) { if (char.IsWhiteSpace(ch)) { continue; } if (!char.IsDigit(ch)) { throw new ArgumentOutOfRangeException(nameof(code), "Code must contain only numbers and whitespace."); } if (number >= 100000000) { return false; } //number cannot be more than 9 digits number *= 10; number += (ch - 0x30); } return IsCodeValid(number); } /// <summary> /// Returns true if code has been validated. /// In HOTP mode (time step is zero) counter will increased if code is valid. /// </summary> /// <param name="code">Code to validate.</param> public bool IsCodeValid(int code) { var currCode = GetCode(Digits, Counter); var prevCode = GetCode(Digits, Counter - 1); var isCurrValid = (code == currCode); var isPrevValid = (code == prevCode) && (Counter > 0); //don't check previous code if counter is zero; but calculate it anyhow (to keep timing) var isValid = isCurrValid || isPrevValid; if ((TimeStep == 0) && isValid) { Counter++; } return isValid; } /// <summary> /// Returns true if code has been validated. /// In HOTP mode (time step is zero) counter will increased if code is valid. /// </summary> /// <param name="code">Code to validate.</param> /// <param name="utcTime">UTC time.</param> /// <exception cref="ArgumentOutOfRangeException">Time must be either UTC or Local.</exception> /// <exception cref="NotSupportedException">Cannot specify time in HOTP mode (time step is zero).</exception> public bool IsCodeValid(int code, DateTime time) { if (time.Kind is not DateTimeKind.Utc and not DateTimeKind.Local) { throw new ArgumentOutOfRangeException(nameof(time), "Time must be either UTC or Local."); } return IsCodeValid(code, new DateTimeOffset(time)); } /// <summary> /// Returns true if code has been validated. /// In HOTP mode (time step is zero) counter will increased if code is valid. /// </summary> /// <param name="code">Code to validate.</param> /// <param name="utcTime">UTC time.</param> /// <exception cref="NotSupportedException">Cannot specify time in HOTP mode (time step is zero).</exception> public bool IsCodeValid(int code, DateTimeOffset time) { if (TimeStep == 0) { throw new NotSupportedException("Cannot specify time in HOTP mode (time step is zero)."); } var counter = GetTimeBasedCounter(time, TimeStep); var currCode = GetCode(Digits, counter); var prevCode = GetCode(Digits, counter - 1); var isCurrValid = (code == currCode); var isPrevValid = (code == prevCode) && (Counter > 0); //don't check previous code if counter is zero; but calculate it anyhow (to keep timing) var isValid = isCurrValid || isPrevValid; return isValid; } #endregion Validate #region Secret buffer /// <summary> /// Returns secret in byte array. /// It is up to the caller to secure the given byte array. /// </summary> public byte[] GetSecret() { var buffer = GC.AllocateUninitializedArray<byte>(_secretLength, pinned: true); UnprotectSecret(); try { Buffer.BlockCopy(_secretBuffer, 0, buffer, 0, buffer.Length); } finally { ProtectSecret(); } return buffer; } /// <summary> /// Returns secret as a Base32 string. /// String will be shown in quads and without padding. /// It is up to the caller to secure given string. /// </summary> public string GetBase32Secret() { return GetBase32Secret(SecretFormatFlags.Spacing); } /// <summary> /// Returns secret as a Base32 string with custom formatting. /// It is up to the caller to secure given string. /// </summary> /// <param name="format">Format of Base32 string.</param> public string GetBase32Secret(SecretFormatFlags format) { UnprotectSecret(); try { return ToBase32(_secretBuffer, _secretLength, format); } finally { ProtectSecret(); } } private const int MaxSecretLength = 1024; // must be multiple of 8 for AES private readonly byte[] _secretBuffer; private readonly int _secretLength; private readonly byte[] _randomIV; private readonly byte[] _randomKey; private readonly Lazy<Aes> _aesAlgorithm = new(delegate { var aes = Aes.Create(); aes.Padding = PaddingMode.None; return aes; }); private void ProtectSecret() { // essentially obfuscation as ProtectedData is not really portable var aes = _aesAlgorithm.Value; using var encryptor = aes.CreateEncryptor(_randomKey, _randomIV); using var ms = new MemoryStream(); using var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); cs.Write(_secretBuffer, 0, _secretBuffer.Length); Buffer.BlockCopy(ms.ToArray(), 0, _secretBuffer, 0, _secretBuffer.Length); } private void UnprotectSecret() { var aes = _aesAlgorithm.Value; using var decryptor = aes.CreateDecryptor(_randomKey, _randomIV); using var ms = new MemoryStream(_secretBuffer); using var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); cs.Read(_secretBuffer, 0, _secretBuffer.Length); } private static void ClearSecret(byte[] array) { for (var i = 0; i < array.Length; i++) { array[i] = 0; } } #endregion Secret buffer #region Base32 private static readonly IList<char> Base32Alphabet = new List<char>("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567").AsReadOnly(); private static readonly byte[] Base32Bitmask = new byte[] { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F }; private static void FromBase32(string text, byte[] buffer, out int length) { var index = 0; var bitPosition = 0; byte partialByte = 0; foreach (var ch in text) { //always assume padding - easier to code than actually checking if (char.IsWhiteSpace(ch)) { continue; } //ignore whitespaces if (ch == '=') { // finish up bitPosition = -1; continue; } else if (bitPosition == -1) { throw new FormatException("Character '" + ch + "' found after padding ."); } var bits = Base32Alphabet.IndexOf(char.ToUpperInvariant(ch)); if (bits < 0) { throw new FormatException("Unknown character '" + ch + "'."); } var bitCount1 = (bitPosition < 3) ? 5 : 8 - bitPosition; //how many bits go in current partial byte var bitCount2 = 5 - bitCount1; //how many bits are for next byte partialByte <<= bitCount1; partialByte |= (byte)(bits >> (5 - bitCount1)); bitPosition += bitCount1; if (bitPosition >= 8) { buffer[index] = partialByte; index++; bitPosition = bitCount2; partialByte = (byte)(bits & Base32Bitmask[bitCount2]); } } if (bitPosition is > (-1) and >= 5) { partialByte <<= (8 - bitPosition); buffer[index] = partialByte; index++; } length = index; } private static string ToBase32(byte[] bytes, int length, SecretFormatFlags format) { if (length == 0) { return string.Empty; } var hasSpacing = (format & SecretFormatFlags.Spacing) == SecretFormatFlags.Spacing; var hasPadding = (format & SecretFormatFlags.Padding) == SecretFormatFlags.Padding; var isUpper = (format & SecretFormatFlags.Uppercase) == SecretFormatFlags.Uppercase; var bitLength = (length * 8); var textLength = bitLength / 5 + ((bitLength % 5) == 0 ? 0 : 1); var totalLength = textLength; var padLength = (textLength % 8 == 0) ? 0 : 8 - textLength % 8; totalLength += (hasPadding ? padLength : 0); var spaceLength = totalLength / 4 + ((totalLength % 4 == 0) ? -1 : 0); totalLength += (hasSpacing ? spaceLength : 0); var chars = new char[totalLength]; var index = 0; var bits = 0; var bitsRemaining = 0; for (var i = 0; i < length; i++) { bits = (bits << 8) | bytes[i]; bitsRemaining += 8; while (bitsRemaining >= 5) { var bitsIndex = (bits >> (bitsRemaining - 5)) & 0x1F; bitsRemaining -= 5; chars[index] = isUpper ? Base32Alphabet[bitsIndex] : char.ToLowerInvariant(Base32Alphabet[bitsIndex]); index++; if (hasSpacing && (index < chars.Length) && (bitsRemaining % 4 == 0)) { chars[index] = ' '; index++; } } } if (bitsRemaining > 0) { var bitsIndex = (bits & Base32Bitmask[bitsRemaining]) << (5 - bitsRemaining); chars[index] = isUpper ? Base32Alphabet[bitsIndex] : char.ToLowerInvariant(Base32Alphabet[bitsIndex]); index++; } if (hasPadding) { for (var i = 0; i < padLength; i++) { if (hasSpacing && (i % 4 == padLength % 4)) { chars[index] = ' '; index++; } chars[index] = '='; index++; } } return new string(chars); } #endregion Base32 #region IDispose private bool disposedValue; private void Dispose(bool disposing) { if (!disposedValue) { ClearSecret(_secretBuffer); // not unmanaged resource, but we want to get rid of data as soon as possible if (disposing) { ClearSecret(_randomKey); ClearSecret(_randomIV); if (_aesAlgorithm.IsValueCreated) { _aesAlgorithm.Value.Dispose(); } } disposedValue = true; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } #endregion IDispose } /// <summary> /// Enumerates formatting option for secret. /// </summary> [Flags()] public enum SecretFormatFlags { /// <summary> /// Secret will be returned as a minimal Base32 string. /// </summary> None = 0, /// <summary> /// Secret will have space every four characters. /// </summary> Spacing = 1, /// <summary> /// Secret will be properly padded to full Base32 length. /// </summary> Padding = 2, /// <summary> /// Secret will be returned in upper case characters. /// </summary> Uppercase = 4, } /// <summary> /// Algorithm for generating one time password. /// </summary> public enum OneTimePasswordAlgorithm { /// <summary> /// SHA-1. /// </summary> Sha1 = 0, /// <summary> /// SHA-256. /// </summary> Sha256 = 1, /// <summary> /// SHA-512. /// </summary> Sha512 = 2, }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using StructureMap; using LibGit2Sharp; using GitTfs.Commands; using Branch = LibGit2Sharp.Branch; using GitTfs.Util; namespace GitTfs.Core { public class GitRepository : GitHelpers, IGitRepository { private readonly IContainer _container; private readonly Globals _globals; private IDictionary<string, IGitTfsRemote> _cachedRemotes; private readonly Repository _repository; private readonly RemoteConfigConverter _remoteConfigReader; public GitRepository(string gitDir, IContainer container, Globals globals, RemoteConfigConverter remoteConfigReader) : base(container) { _container = container; _globals = globals; GitDir = gitDir; _repository = new Repository(GitDir); _remoteConfigReader = remoteConfigReader; } ~GitRepository() { if (_repository != null) _repository.Dispose(); } public GitCommit Commit(LogEntry logEntry) { var parents = logEntry.CommitParents.Select(sha => _repository.Lookup<Commit>(sha)); var commit = _repository.ObjectDatabase.CreateCommit( new Signature(logEntry.AuthorName, logEntry.AuthorEmail, logEntry.Date.ToUniversalTime()), new Signature(logEntry.CommitterName, logEntry.CommitterEmail, logEntry.Date.ToUniversalTime()), logEntry.Log, logEntry.Tree, parents, false); changesetsCache[logEntry.ChangesetId] = commit.Sha; return new GitCommit(commit); } public void UpdateRef(string gitRefName, string shaCommit, string message = null) { if (message == null) _repository.Refs.Add(gitRefName, shaCommit, allowOverwrite: true); else _repository.Refs.Add(gitRefName, shaCommit, message, true); } public static string ShortToLocalName(string branchName) { return "refs/heads/" + branchName; } public static string ShortToTfsRemoteName(string branchName) { return "refs/remotes/tfs/" + branchName; } public string GitDir { get; } protected override GitProcess Start(string[] command, Action<ProcessStartInfo> initialize) { return base.Start(command, initialize.And(SetUpPaths)); } private void SetUpPaths(ProcessStartInfo gitCommand) { if (GitDir != null) gitCommand.EnvironmentVariables["GIT_DIR"] = GitDir; } public string GetConfig(string key) { var entry = _repository.Config.Get<string>(key); return entry == null ? null : entry.Value; } public T GetConfig<T>(string key) { return GetConfig(key, default(T)); } public T GetConfig<T>(string key, T defaultValue) { try { var entry = _repository.Config.Get<T>(key); if (entry == null) return defaultValue; return entry.Value; } catch (Exception) { return defaultValue; } } public void SetConfig(string key, string value) { _repository.Config.Set<string>(key, value, ConfigurationLevel.Local); } public void SetConfig(string key, bool value) { SetConfig(key, value.ToString().ToLower()); } public IEnumerable<IGitTfsRemote> ReadAllTfsRemotes() { var remotes = GetTfsRemotes().Values; foreach (var remote in remotes) remote.EnsureTfsAuthenticated(); return remotes; } public IGitTfsRemote ReadTfsRemote(string remoteId) { if (!HasRemote(remoteId)) throw new GitTfsException("Unable to locate git-tfs remote with id = " + remoteId) .WithRecommendation("Try using `git tfs bootstrap` to auto-init TFS remotes."); var remote = GetTfsRemotes()[remoteId]; remote.EnsureTfsAuthenticated(); return remote; } private IGitTfsRemote ReadTfsRemote(string tfsUrl, string tfsRepositoryPath) { var allRemotes = GetTfsRemotes(); var matchingRemotes = allRemotes.Values.Where( remote => remote.MatchesUrlAndRepositoryPath(tfsUrl, tfsRepositoryPath)); switch (matchingRemotes.Count()) { case 0: return new DerivedGitTfsRemote(tfsUrl, tfsRepositoryPath); case 1: var remote = matchingRemotes.First(); return remote; default: Trace.WriteLine("More than one remote matched!"); goto case 1; } } public IEnumerable<string> GetGitRemoteBranches(string gitRemote) { gitRemote = gitRemote + "/"; var references = _repository.Branches.Where(b => b.IsRemote && b.FriendlyName.StartsWith(gitRemote) && !b.FriendlyName.EndsWith("/HEAD")); return references.Select(r => r.FriendlyName); } private IDictionary<string, IGitTfsRemote> GetTfsRemotes() { return _cachedRemotes ?? (_cachedRemotes = ReadTfsRemotes()); } public IGitTfsRemote CreateTfsRemote(RemoteInfo remote) { foreach (var entry in _remoteConfigReader.Dump(remote)) { if (entry.Value != null) { _repository.Config.Set(entry.Key, entry.Value); } else { _repository.Config.Unset(entry.Key); } } var gitTfsRemote = BuildRemote(remote); gitTfsRemote.EnsureTfsAuthenticated(); return _cachedRemotes[remote.Id] = gitTfsRemote; } public void DeleteTfsRemote(IGitTfsRemote remote) { if (remote == null) throw new GitTfsException("error: the name of the remote to delete is invalid!"); UnsetTfsRemoteConfig(remote.Id); _repository.Refs.Remove(remote.RemoteRef); } private void UnsetTfsRemoteConfig(string remoteId) { foreach (var entry in _remoteConfigReader.Delete(remoteId)) { _repository.Config.Unset(entry.Key); } _cachedRemotes = null; } public void MoveRemote(string oldRemoteName, string newRemoteName) { if (!Reference.IsValidName(ShortToLocalName(oldRemoteName))) throw new GitTfsException("error: the name of the remote to move is invalid!"); if (!Reference.IsValidName(ShortToLocalName(newRemoteName))) throw new GitTfsException("error: the new name of the remote is invalid!"); if (HasRemote(newRemoteName)) throw new GitTfsException(string.Format("error: this remote name \"{0}\" is already used!", newRemoteName)); var oldRemote = ReadTfsRemote(oldRemoteName); if (oldRemote == null) throw new GitTfsException(string.Format("error: the remote \"{0}\" doesn't exist!", oldRemoteName)); var remoteInfo = oldRemote.RemoteInfo; remoteInfo.Id = newRemoteName; CreateTfsRemote(remoteInfo); var newRemote = ReadTfsRemote(newRemoteName); _repository.Refs.Rename(oldRemote.RemoteRef, newRemote.RemoteRef); UnsetTfsRemoteConfig(oldRemoteName); } public Branch RenameBranch(string oldName, string newName) { var branch = _repository.Branches[oldName]; if (branch == null) return null; return _repository.Branches.Rename(branch, newName); } private IDictionary<string, IGitTfsRemote> ReadTfsRemotes() { // does this need to ensuretfsauthenticated? _repository.Config.Set("tfs.touch", "1"); // reload configuration, because `git tfs init` and `git tfs clone` use Process.Start to update the config, so _repository's copy is out of date. var remotes = _remoteConfigReader.Load(_repository.Config).Select(x => BuildRemote(x)).ToDictionary(x => x.Id); bool shouldExport = GetConfig(GitTfsConstants.ExportMetadatasConfigKey) == "true"; foreach(var remote in remotes.Values) { var metadataExportInitializer = new ExportMetadatasInitializer(_globals); metadataExportInitializer.InitializeRemote(remote, shouldExport); } return remotes; } private IGitTfsRemote BuildRemote(RemoteInfo remoteInfo) { return _container.With(remoteInfo).With<IGitRepository>(this).GetInstance<IGitTfsRemote>(); } public bool HasRemote(string remoteId) { return GetTfsRemotes().ContainsKey(remoteId); } public bool IsInSameTeamProjectAsDefaultRepository(string tfsRepositoryPath) { IGitTfsRemote defaultRepository; if (!GetTfsRemotes().TryGetValue(GitTfsConstants.DefaultRepositoryId, out defaultRepository)) { return true; } var teamProjectPath = defaultRepository.TfsRepositoryPath.ToTfsTeamProjectRepositoryPath(); //add ending '/' because there can be overlapping names ($/myproject/ and $/myproject other/) return tfsRepositoryPath.StartsWith(teamProjectPath + "/"); } public bool HasRef(string gitRef) { return _repository.Refs[gitRef] != null; } public void MoveTfsRefForwardIfNeeded(IGitTfsRemote remote) { MoveTfsRefForwardIfNeeded(remote, "HEAD"); } public void MoveTfsRefForwardIfNeeded(IGitTfsRemote remote, string @ref) { int currentMaxChangesetId = remote.MaxChangesetId; var untrackedTfsChangesets = from cs in GetLastParentTfsCommits(@ref) where cs.Remote.Id == remote.Id && cs.ChangesetId > currentMaxChangesetId orderby cs.ChangesetId select cs; foreach (var cs in untrackedTfsChangesets) { // UpdateTfsHead sets tag with TFS changeset id on each commit so we can't just update to latest remote.UpdateTfsHead(cs.GitCommit, cs.ChangesetId); } } public GitCommit GetCommit(string commitish) { var commit = _repository.Lookup<Commit>(commitish); return commit is null ? null : new GitCommit(commit); } public MergeResult Merge(string commitish) { var commit = _repository.Lookup<Commit>(commitish); if (commit == null) throw new GitTfsException("error: commit '" + commitish + "' can't be found and merged into!"); return _repository.Merge(commit, _repository.Config.BuildSignature(new DateTimeOffset(DateTime.Now))); } public String GetCurrentCommit() { return _repository.Head.Commits.First().Sha; } public IEnumerable<TfsChangesetInfo> GetLastParentTfsCommits(string head) { var changesets = new List<TfsChangesetInfo>(); var commit = _repository.Lookup<Commit>(head); if (commit == null) return changesets; FindTfsParentCommits(changesets, commit); return changesets; } private void FindTfsParentCommits(List<TfsChangesetInfo> changesets, Commit commit) { var commitsToFollow = new Stack<Commit>(); commitsToFollow.Push(commit); var alreadyVisitedCommits = new HashSet<string>(); while (commitsToFollow.Any()) { commit = commitsToFollow.Pop(); alreadyVisitedCommits.Add(commit.Sha); var changesetInfo = TryParseChangesetInfo(commit.Message, commit.Sha); if (changesetInfo == null) { // If commit was not a TFS commit, continue searching all new parents of the commit // Add parents in reverse order to keep topology (main parent should be treated first!) foreach (var parent in commit.Parents.Where(x => !alreadyVisitedCommits.Contains(x.Sha)).Reverse()) commitsToFollow.Push(parent); } else { changesets.Add(changesetInfo); } } Trace.WriteLine("Commits visited count:" + alreadyVisitedCommits.Count); } public TfsChangesetInfo GetTfsChangesetById(string remoteRef, int changesetId) { var commit = FindCommitByChangesetId(changesetId, remoteRef); if (commit == null) return null; return TryParseChangesetInfo(commit.Message, commit.Sha); } public TfsChangesetInfo GetCurrentTfsCommit() { var currentCommit = _repository.Head.Commits.First(); return TryParseChangesetInfo(currentCommit.Message, currentCommit.Sha); } public TfsChangesetInfo GetTfsCommit(GitCommit commit) { if (commit is null) throw new ArgumentNullException(nameof(commit)); return TryParseChangesetInfo(commit.Message, commit.Sha); } public TfsChangesetInfo GetTfsCommit(string sha) { var gitCommit = GetCommit(sha); return gitCommit is null ? null : GetTfsCommit(gitCommit); } private TfsChangesetInfo TryParseChangesetInfo(string gitTfsMetaInfo, string commit) { var match = GitTfsConstants.TfsCommitInfoRegex.Match(gitTfsMetaInfo); if (match.Success) { var commitInfo = _container.GetInstance<TfsChangesetInfo>(); commitInfo.Remote = ReadTfsRemote(match.Groups["url"].Value, match.Groups["repository"].Success ? match.Groups["repository"].Value : null); commitInfo.ChangesetId = Convert.ToInt32(match.Groups["changeset"].Value); commitInfo.GitCommit = commit; return commitInfo; } return null; } public IDictionary<string, GitObject> CreateObjectsDictionary() { return new Dictionary<string, GitObject>(StringComparer.InvariantCultureIgnoreCase); } public IDictionary<string, GitObject> GetObjects(string commit, IDictionary<string, GitObject> entries) { if (commit != null) { ParseEntries(entries, _repository.Lookup<Commit>(commit).Tree, commit); } return entries; } public IDictionary<string, GitObject> GetObjects(string commit) { var entries = CreateObjectsDictionary(); return GetObjects(commit, entries); } public IGitTreeBuilder GetTreeBuilder(string commit) { if (commit == null) { return new GitTreeBuilder(_repository.ObjectDatabase); } else { return new GitTreeBuilder(_repository.ObjectDatabase, _repository.Lookup<Commit>(commit).Tree); } } public string GetCommitMessage(string head, string parentCommitish) { var message = new System.Text.StringBuilder(); foreach (Commit comm in _repository.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = head, ExcludeReachableFrom = parentCommitish })) { // Normalize commit message line endings to CR+LF style, so that message // would be correctly shown in TFS commit dialog. message.AppendLine(NormalizeLineEndings(comm.Message)); } return GitTfsConstants.TfsCommitInfoRegex.Replace(message.ToString(), "").Trim(' ', '\r', '\n'); } private static string NormalizeLineEndings(string input) { return string.IsNullOrEmpty(input) ? input : input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n"); } private void ParseEntries(IDictionary<string, GitObject> entries, Tree treeInfo, string commit) { var treesToDescend = new Queue<Tree>(new[] { treeInfo }); while (treesToDescend.Any()) { var currentTree = treesToDescend.Dequeue(); foreach (var item in currentTree) { if (item.TargetType == TreeEntryTargetType.Tree) { treesToDescend.Enqueue((Tree)item.Target); } var path = item.Path.Replace('\\', '/'); entries[path] = new GitObject { Mode = item.Mode, Sha = item.Target.Sha, ObjectType = item.TargetType, Path = path, Commit = commit }; } } } public IEnumerable<IGitChangedFile> GetChangedFiles(string from, string to) { using (var diffOutput = CommandOutputPipe("diff-tree", "-r", "-M", "-z", from, to)) { var changes = GitChangeInfo.GetChangedFiles(diffOutput); foreach (var change in changes) { yield return BuildGitChangedFile(change); } } } private IGitChangedFile BuildGitChangedFile(GitChangeInfo change) { return change.ToGitChangedFile(_container.With((IGitRepository)this)); } public bool WorkingCopyHasUnstagedOrUncommitedChanges { get { if (IsBare) return false; return (from entry in _repository.RetrieveStatus() where entry.State != FileStatus.Ignored && entry.State != FileStatus.NewInWorkdir select entry).Any(); } } public void CopyBlob(string sha, string outputFile) { Blob blob; var destination = new FileInfo(outputFile); if (!destination.Directory.Exists) destination.Directory.Create(); if ((blob = _repository.Lookup<Blob>(sha)) != null) using (Stream stream = blob.GetContentStream(new FilteringOptions(string.Empty))) using (var outstream = File.Create(destination.FullName)) stream.CopyTo(outstream); } public string AssertValidBranchName(string gitBranchName) { if (!Reference.IsValidName(ShortToLocalName(gitBranchName))) throw new GitTfsException("The name specified for the new git branch is not allowed. Choose another one!"); return gitBranchName; } private bool IsRefNameUsed(string gitBranchName) { var parts = gitBranchName.Split('/'); var refName = parts.First(); for (int i = 1; i <= parts.Length; i++) { if (HasRef(ShortToLocalName(refName)) || HasRef(ShortToTfsRemoteName(refName))) return true; if (i < parts.Length) refName += '/' + parts[i]; } return false; } public bool CreateBranch(string gitBranchName, string target) { Reference reference; try { reference = _repository.Refs.Add(gitBranchName, target); } catch (Exception) { return false; } return reference != null; } private readonly Dictionary<int, string> changesetsCache = new Dictionary<int, string>(); private bool cacheIsFull = false; public string FindCommitHashByChangesetId(int changesetId) { var commit = FindCommitByChangesetId(changesetId); if (commit == null) return null; return commit.Sha; } private static readonly Regex tfsIdRegex = new Regex("^git-tfs-id: .*;C([0-9]+)\r?$", RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.RightToLeft); public static bool TryParseChangesetId(string commitMessage, out int changesetId) { var match = tfsIdRegex.Match(commitMessage); if (match.Success) { changesetId = int.Parse(match.Groups[1].Value); return true; } changesetId = 0; return false; } private Commit FindCommitByChangesetId(int changesetId, string remoteRef = null) { Trace.WriteLine("Looking for changeset " + changesetId + " in git repository..."); if (remoteRef == null) { string sha; if (changesetsCache.TryGetValue(changesetId, out sha)) { Trace.WriteLine("Changeset " + changesetId + " found at " + sha); return _repository.Lookup<Commit>(sha); } if (cacheIsFull) { Trace.WriteLine("Looking for changeset " + changesetId + " in git repository: CacheIsFull, stopped looking."); return null; } } var reachableFromRemoteBranches = new CommitFilter { IncludeReachableFrom = _repository.Branches.Where(p => p.IsRemote), SortBy = CommitSortStrategies.Time }; if (remoteRef != null) { var query = _repository.Branches.Where(p => p.IsRemote && p.CanonicalName.EndsWith(remoteRef)); Trace.WriteLine("Looking for changeset " + changesetId + " in git repository: Adding remotes:"); foreach (var reachable in query) { Trace.WriteLine(reachable.CanonicalName + "reachable from " + remoteRef); } reachableFromRemoteBranches.IncludeReachableFrom = query; } var commitsFromRemoteBranches = _repository.Commits.QueryBy(reachableFromRemoteBranches); Commit commit = null; foreach (var c in commitsFromRemoteBranches) { int id; if (TryParseChangesetId(c.Message, out id)) { changesetsCache[id] = c.Sha; if (id == changesetId) { commit = c; break; } } else { foreach (var note in c.Notes) { if (TryParseChangesetId(note.Message, out id)) { changesetsCache[id] = c.Sha; if (id == changesetId) { commit = c; break; } } } } } if (remoteRef == null && commit == null) cacheIsFull = true; // repository fully scanned Trace.WriteLine((commit == null) ? " => Commit " + changesetId + " not found!" : " => Commit " + changesetId + " found! hash: " + commit.Sha); return commit; } public void CreateTag(string name, string sha, string comment, string Owner, string emailOwner, DateTime creationDate) { if (_repository.Tags[name] == null) _repository.ApplyTag(name, sha, new Signature(Owner, emailOwner, new DateTimeOffset(creationDate)), comment); } public void CreateNote(string sha, string content, string owner, string emailOwner, DateTime creationDate) { Signature author = new Signature(owner, emailOwner, creationDate); _repository.Notes.Add(new ObjectId(sha), content, author, author, "commits"); } public void ResetHard(string sha) { _repository.Reset(ResetMode.Hard, sha); } public bool IsBare { get { return _repository.Info.IsBare; } } /// <summary> /// Gets all configured "subtree" remotes which point to the same Tfs URL as the given remote. /// If the given remote is itself a subtree, an empty enumerable is returned. /// </summary> public IEnumerable<IGitTfsRemote> GetSubtrees(IGitTfsRemote owner) { //a subtree remote cannot have subtrees itself. if (owner.IsSubtree) return Enumerable.Empty<IGitTfsRemote>(); return ReadAllTfsRemotes().Where(x => x.IsSubtree && string.Equals(x.OwningRemoteId, owner.Id, StringComparison.InvariantCultureIgnoreCase)); } public void ResetRemote(IGitTfsRemote remoteToReset, string target) { _repository.Refs.UpdateTarget(remoteToReset.RemoteRef, target); } public string GetCurrentBranch() { return _repository.Head.CanonicalName; } public void GarbageCollect(bool auto, string additionalMessage) { if (Globals.DisableGarbageCollect) return; try { if (auto) _globals.Repository.CommandNoisy("gc", "--auto"); else _globals.Repository.CommandNoisy("gc"); } catch (Exception e) { Trace.WriteLine(e); Trace.TraceWarning("Warning: `git gc` failed! " + additionalMessage); } } public bool Checkout(string commitish) { try { LibGit2Sharp.Commands.Checkout(_repository, commitish); return true; } catch (CheckoutConflictException) { return false; } } public IEnumerable<GitCommit> FindParentCommits(string @from, string to) { var commits = _repository.Commits.QueryBy( new CommitFilter() { IncludeReachableFrom = @from, ExcludeReachableFrom = to, SortBy = CommitSortStrategies.Reverse, FirstParentOnly = true }) .Select(c => new GitCommit(c)); var parent = to; foreach (var gitCommit in commits) { if (gitCommit.Parents.All(c => c.Sha != parent)) return new List<GitCommit>(); parent = gitCommit.Sha; } return commits; } public bool IsPathIgnored(string relativePath) { return _repository.Ignore.IsPathIgnored(relativePath); } public string CommitGitIgnore(string pathToGitIgnoreFile) { if (!File.Exists(pathToGitIgnoreFile)) { Trace.TraceWarning("warning: the .gitignore file specified '{0}' does not exist!", pathToGitIgnoreFile); } var gitTreeBuilder = new GitTreeBuilder(_repository.ObjectDatabase); gitTreeBuilder.Add(".gitignore", pathToGitIgnoreFile, LibGit2Sharp.Mode.NonExecutableFile); var tree = gitTreeBuilder.GetTree(); var signature = new Signature("git-tfs", "[email protected]", new DateTimeOffset(2000, 1, 1, 0, 0, 0, new TimeSpan(0))); var sha = _repository.ObjectDatabase.CreateCommit(signature, signature, ".gitignore", tree, new Commit[0], false).Sha; Trace.WriteLine(".gitignore commit created: " + sha); // Point our tfs remote branch to the .gitignore commit var defaultRef = ShortToTfsRemoteName("default"); _repository.Refs.Add(defaultRef, new ObjectId(sha)); // Also point HEAD to the .gitignore commit, if it isn't already. This // ensures a common initial commit for the git-tfs init --gitignore case. if (_repository.Head.CanonicalName != defaultRef) _repository.Refs.Add(_repository.Head.CanonicalName, new ObjectId(sha)); return sha; } public void UseGitIgnore(string pathToGitIgnoreFile) { //Should add ourself the rules to the temporary rules because committing directly to the git database //prevent libgit2sharp to detect the new .gitignore file _repository.Ignore.AddTemporaryRules(File.ReadLines(pathToGitIgnoreFile)); } public IDictionary<int, string> GetCommitChangeSetPairs() { var allCommits = _repository.Commits.QueryBy(new CommitFilter()); var pairs = new Dictionary<int, string>() ; foreach (var c in allCommits) { int changesetId; if (TryParseChangesetId(c.Message, out changesetId)) { pairs.Add(changesetId, c.Sha); } else { foreach (var note in c.Notes) { if (TryParseChangesetId(note.Message, out changesetId)) { pairs.Add(changesetId, c.Sha); } } } } return pairs; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.IO; using log4net; #if !LATE_BIND using HSVPROCESSFLOWLib; #endif using HFMCONSTANTSLib; using Command; using HFMCmd; using Utilities; namespace HFM { /// <summary> /// Enumeration of process management states /// </summary> public enum EProcessState : short { NotSupported = CEnumProcessFlowStates.PROCESS_FLOW_STATE_NOT_SUPPORTED, NotStarted = CEnumProcessFlowStates.PROCESS_FLOW_STATE_NOT_STARTED, FirstPass = CEnumProcessFlowStates.PROCESS_FLOW_STATE_FIRST_PASS, ReviewLevel1 = CEnumProcessFlowStates.PROCESS_FLOW_STATE_REVIEW1, ReviewLevel2 = CEnumProcessFlowStates.PROCESS_FLOW_STATE_REVIEW2, ReviewLevel3 = CEnumProcessFlowStates.PROCESS_FLOW_STATE_REVIEW3, ReviewLevel4 = CEnumProcessFlowStates.PROCESS_FLOW_STATE_REVIEW4, ReviewLevel5 = CEnumProcessFlowStates.PROCESS_FLOW_STATE_REVIEW5, ReviewLevel6 = CEnumProcessFlowStates.PROCESS_FLOW_STATE_REVIEW6, ReviewLevel7 = CEnumProcessFlowStates.PROCESS_FLOW_STATE_REVIEW7, ReviewLevel8 = CEnumProcessFlowStates.PROCESS_FLOW_STATE_REVIEW8, ReviewLevel9 = CEnumProcessFlowStates.PROCESS_FLOW_STATE_REVIEW9, ReviewLevel10 = CEnumProcessFlowStates.PROCESS_FLOW_STATE_REVIEW10, Submitted = CEnumProcessFlowStates.PROCESS_FLOW_STATE_SUBMITTED, Approved = CEnumProcessFlowStates.PROCESS_FLOW_STATE_APPROVED, Published = CEnumProcessFlowStates.PROCESS_FLOW_STATE_PUBLISHED } /// <summary> /// Enumeration of process management actions /// </summary> public enum EProcessAction : short { Approve = CEnumProcessFlowActions.PROCESS_FLOW_ACTION_APPROVE, Promote = CEnumProcessFlowActions.PROCESS_FLOW_ACTION_PROMOTE, Publish = CEnumProcessFlowActions.PROCESS_FLOW_ACTION_PUBLISH, Reject = CEnumProcessFlowActions.PROCESS_FLOW_ACTION_REJECT, SignOff = CEnumProcessFlowActions.PROCESS_FLOW_ACTION_SIGN_OFF, Start = CEnumProcessFlowActions.PROCESS_FLOW_ACTION_START, Submit = CEnumProcessFlowActions.PROCESS_FLOW_ACTION_SUBMIT } [Setting("POV", "A Point-of-View expression, such as 'S#Actual.Y#2010.P#May." + "E#E1.V#<Entity Currency>'. Use a POV expression to select members " + "from multiple dimensions in one go.\nNote that if a dimension member is " + "specified in the POV expression and via a setting for the dimension, the " + "dimension setting takes precedence.", ParameterType = typeof(string), Order = 0), Setting("Scenario", "Scenario member(s) to include in the definition", Alias = "Scenarios", ParameterType = typeof(IEnumerable<string>), Order = 1), Setting("Year", "Year member(s) to include in the definition", Alias = "Years", ParameterType = typeof(IEnumerable<string>), Order = 2), Setting("Period", "Period member(s) to include in the definition", Alias = "Periods", ParameterType = typeof(IEnumerable<string>), Order = 3), Setting("Entity", "Entity member(s) to include in the definition", Alias = "Entities", ParameterType = typeof(IEnumerable<string>), Order = 4), Setting("Value", "Value member(s) to include in the definition", Alias = "Values", ParameterType = typeof(IEnumerable<string>), Order = 5), Setting("Account", "Account member(s) to include in the definition", Alias = "Accounts", ParameterType = typeof(IEnumerable<string>), Order = 6), Setting("ICP", "ICP member(s) to include in the definition", Alias = "ICPs", ParameterType = typeof(IEnumerable<string>), Order = 7), DynamicSetting("CustomDimName", "<CustomDimName> member(s) to include in the definition", ParameterType = typeof(IEnumerable<string>), Order = 8)] public class ProcessUnits : Slice, IDynamicSettingsCollection { [Factory(SingleUse = true)] public ProcessUnits(Metadata metadata) : base(metadata) {} /// Returns an array of all process units in the slice public POV[] ProcessUnitPOVs { get { return GenerateProcessUnitPOVs(); } } // Returns an array of POV objects for each combination of process units in this slice protected POV[] GenerateProcessUnitPOVs() { MemberList[] lists = new MemberList[] { Scenario, Year, Period, Entity, Value }; return GenerateCombos(lists); } } /// <summary> /// Performs process management on an HFM application. /// </summary> public abstract class ProcessFlow { // Reference to class logger protected static readonly ILog _log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Reference to HFM HsvProcessFlow object #if LATE_BIND internal readonly dynamic _hsvProcessFlow; #else internal readonly HsvProcessFlow _hsvProcessFlow; #endif // Refernece to the Session object protected Session _session; // Reference to Metadata object protected Metadata _metadata; // Reference to Security object protected Security _security; /// Constructor internal ProcessFlow(Session session) { _log.Trace("Constructing ProcessFlow object"); _session = session; #if LATE_BIND _hsvProcessFlow = session.HsvSession.ProcessFlow; #else _hsvProcessFlow = (HsvProcessFlow)session.HsvSession.ProcessFlow; #endif _metadata = session.Metadata; _security = session.Security; } [Command("Returns the current process state")] public void EnumProcessState(ProcessUnits slice, IOutput output) { GetProcessState(slice, output); } [Command("Returns the submission group and submission phase for each cell in the slice")] public void EnumGroupPhases(ProcessUnits slice, IOutput output) { int group, phase; DefaultMembers(slice, false); output.SetHeader("Cell", 50, "Submission Group", "Submission Phase", 20); foreach(var pov in slice.POVs) { GetGroupPhase(pov, out group, out phase); output.WriteRecord(pov, group, phase); } output.End(); } protected void GetGroupPhase(POV pov, out int group, out int phase) { string sGroup = null, sPhase = null; if(HFM.HasVariableCustoms) { #if HFM_11_1_2_2 HFM.Try("Retrieving submission group and phase", () => _hsvProcessFlow.GetGroupPhaseFromCellExtDim(pov.HfmPovCOM, out sGroup, out sPhase)); #else HFM.ThrowIncompatibleLibraryEx(); #endif } else { HFM.Try("Retrieving submission group and phase", () => _hsvProcessFlow.GetGroupPhaseFromCell(pov.Scenario.Id, pov.Year.Id, pov.Period.Id, pov.Entity.Id, pov.Entity.ParentId, pov.Value.Id, pov.Account.Id, pov.ICP.Id, pov.Custom1.Id, pov.Custom2.Id, pov.Custom3.Id, pov.Custom4.Id, out sGroup, out sPhase)); } group = int.Parse(sGroup); phase = int.Parse(sPhase); } [Command("Returns the history of process management actions performed on process units")] public void GetProcessHistory(ProcessUnits slice, IOutput output) { POV[] PUs = GetProcessUnits(slice); foreach(var pu in PUs) { GetHistory(pu, output); } } /// Method to be implemented in sub-classes for retrieving the state of /// process unit(s) represented by the ProcessUnits. protected abstract void GetHistory(POV processUnit, IOutput output); protected void OutputHistory(IOutput output, POV pu, object oDates, object oUsers, object oActions, object oStates, object oAnnotations, object oPaths, object oFiles) { var dates = (double[])oDates; var users = HFM.Object2Array<string>(oUsers); var actions = (EProcessAction[])oActions; var states = (EProcessState[])oStates; var annotations = HFM.Object2Array<string>(oAnnotations); var paths = HFM.Object2Array<string>(oPaths); var files = HFM.Object2Array<string>(oFiles); output.WriteLine("Process history for {0} {1}:", ProcessUnitType, pu); output.SetHeader("Date", "User", 30, "Action", 10, "Process State", 14, "Annotation"); for(int i = 0; i < dates.Length; ++i) { output.WriteRecord(DateTime.FromOADate(dates[i]), users[i], actions[i], states[i], annotations[i]); } output.End(true); } [Command("Starts a process unit or phased submission, moving it from Not Started to First Pass")] public void Start( ProcessUnits slice, [Parameter("Annotations to be applied to each process unit or phased submission", DefaultValue = null)] string annotation, [Parameter("Document attachment(s) to be applied to each process unit or phased submission", DefaultValue = null)] IEnumerable<string> attachments, IOutput output) { SetProcessState(slice, EProcessAction.Start, ERole.ProcessFlowSupervisor, EProcessState.FirstPass, annotation, attachments, false, output); } [Command("Promotes a process unit or phased submission to the specified Review level")] public void Promote( ProcessUnits slice, [Parameter("Review level to promote to (a value between 1 and 10)")] string reviewLevel, [Parameter("Annotations to be applied to each process unit or phased submission", DefaultValue = null)] string annotation, [Parameter("Document attachment(s) to be applied to each process unit or phased submission", DefaultValue = null)] IEnumerable<string> attachments, [Parameter("Consolidate the process unit if consolidation is necessary to promote.", DefaultValue = true)] bool consolidateIfNeeded, IOutput output) { var re = new Regex("^(?:ReviewLevel)?([0-9]|10)$", RegexOptions.IgnoreCase); var match = re.Match(reviewLevel); EProcessState targetState; ERole roleNeeded; if(match.Success) { targetState = (EProcessState)Enum.Parse(typeof(EProcessState), "ReviewLevel" + match.Groups[1].Value); roleNeeded = (ERole)Enum.Parse(typeof(ERole), "ProcessFlowReviewer" + (int.Parse(match.Groups[1].Value) - 1)); } else { throw new ArgumentException("Review level must be a value between 1 and 10"); } SetProcessState(slice, EProcessAction.Promote, roleNeeded, targetState, annotation, attachments, consolidateIfNeeded, output); } [Command("Returns a process unit or phased submission to its prior state")] public void Reject( ProcessUnits slice, [Parameter("Annotations to be applied to each process unit or phased submission", DefaultValue = null)] string annotation, [Parameter("Document attachment(s) to be applied to each process unit or phased submission", DefaultValue = null)] IEnumerable<string> attachments, IOutput output) { SetProcessState(slice, EProcessAction.Reject, ERole.ProcessFlowReviewer1, EProcessState.NotSupported, annotation, attachments, false, output); } [Command("Sign-off a process unit or phased submission. This records sign-off of the data " + "at the current point in the process (which must be a review level), but does not " + "otherwise change the process level of the process unit or phased submission.")] public void SignOff( ProcessUnits slice, [Parameter("Annotations to be applied to each process unit or phased submission", DefaultValue = null)] string annotation, [Parameter("Document attachment(s) to be applied to each process unit or phased submission", DefaultValue = null)] IEnumerable<string> attachments, [Parameter("Consolidate the process unit if consolidation is necessary to submit.", DefaultValue = true)] bool consolidateIfNeeded, IOutput output) { SetProcessState(slice, EProcessAction.SignOff, ERole.ProcessFlowReviewer1, EProcessState.NotSupported, annotation, attachments, consolidateIfNeeded, output); } [Command("Submit a process unit or phased submission for approval.")] public void Submit( ProcessUnits slice, [Parameter("Annotations to be applied to each process unit or phased submission", DefaultValue = null)] string annotation, [Parameter("Document attachment(s) to be applied to each process unit or phased submission", DefaultValue = null)] IEnumerable<string> attachments, [Parameter("Consolidate the process unit if consolidation is necessary to submit.", DefaultValue = true)] bool consolidateIfNeeded, IOutput output) { SetProcessState(slice, EProcessAction.Submit, ERole.ProcessFlowSubmitter, EProcessState.Submitted, annotation, attachments, consolidateIfNeeded, output); } [Command("Approve a process unit or phased submission.")] public void Approve( ProcessUnits slice, [Parameter("Annotations to be applied to each process unit or phased submission", DefaultValue = null)] string annotation, [Parameter("Document attachment(s) to be applied to each process unit or phased submission", DefaultValue = null)] IEnumerable<string> attachments, [Parameter("Consolidate the process unit if consolidation is necessary to approve.", DefaultValue = true)] bool consolidateIfNeeded, IOutput output) { SetProcessState(slice, EProcessAction.Approve, ERole.ProcessFlowSupervisor, EProcessState.Approved, annotation, attachments, consolidateIfNeeded, output); } [Command("Publish a process unit or phased submission group.")] public void Publish( ProcessUnits slice, [Parameter("Annotations to be applied to each process unit or phased submission", DefaultValue = null)] string annotation, [Parameter("Document attachment(s) to be applied to each process unit or phased submission", DefaultValue = null)] IEnumerable<string> attachments, [Parameter("Consolidate the process unit if consolidation is necessary to publish.", DefaultValue = true)] bool consolidateIfNeeded, IOutput output) { SetProcessState(slice, EProcessAction.Publish, ERole.ProcessFlowSupervisor, EProcessState.Published, annotation, attachments, consolidateIfNeeded, output); } /// Property to return a label for a unit of process management protected abstract string ProcessUnitType { get; } /// Method to be implemented in sub-classes to return an array of POV /// instances for each process unit represented by the slice. protected abstract POV[] GetProcessUnits(ProcessUnits slice); /// Method to be implemented in sub-classes for retrieving the state of /// process unit(s) represented by the ProcessUnits. protected abstract void GetProcessState(ProcessUnits slice, IOutput output); /// Method to be implemented in sub-classes for setting the state of /// process unit(s) represented by the ProcessUnits. protected void SetProcessState(ProcessUnits slice, EProcessAction action, ERole role, EProcessState targetState, string annotation, IEnumerable<string> documents, bool consolidateIfNeeded, IOutput output) { string[] paths = null, files = null; int processed = 0, skipped = 0, errored = 0, invalid = 0; EProcessState state; _security.CheckPermissionFor(ETask.ProcessManagement); if(role != ERole.Default) { _security.CheckRole(role); } // Convert document references if(documents != null) { var docs = documents.ToArray(); paths = new string[docs.Length]; files = new string[docs.Length]; for(int i = 0; i < docs.Length; ++i) { paths[i] = Path.GetDirectoryName(docs[i]); files[i] = Path.GetFileName(docs[i]); } } // Iterate over process units, performing action var PUs = GetProcessUnits(slice); output.InitProgress("Processing " + action.ToString(), PUs.Length); foreach(var pu in PUs) { var access = _security.GetProcessUnitAccessRights(pu, out state); if(state == targetState) { _log.FineFormat("{1} {2} is already at {2}", ProcessUnitType, pu, targetState); skipped++; } else if(IsValidStateTransition(action, pu, state, targetState) && HasSufficientAccess(action, pu, access, state) && CanAction(action, pu, consolidateIfNeeded, output)) { try { SetProcessState(pu, action, targetState, annotation, paths, files); processed++; } catch(HFMException ex) { _log.Error(string.Format("Unable to {0} {1} {2}", action, ProcessUnitType, pu), ex); errored++; } } else { invalid++; } if(output.IterationComplete()) { break; } } output.EndProgress(); _log.InfoFormat("Results for {0} of {1} {2}s: {3} successful, {4} skipped, {5} errored, {6} invalid", action, PUs.Length, ProcessUnitType, processed, skipped, errored, invalid); if(errored > 0) { throw new Exception(string.Format("Failed to {0} {1} {2}s", action, errored, ProcessUnitType)); } } protected void DefaultMembers(ProcessUnits slice, bool overrideExisting) { // Default each dimension for which phased submission is not enabled if(!_metadata.IsPhasedSubmissionEnabledForDimension((int)EDimension.Account) && (overrideExisting || !slice.IsSpecified(EDimension.Account))) { slice[EDimension.Account] = "[None]"; } if(!_metadata.IsPhasedSubmissionEnabledForDimension((int)EDimension.ICP) && (overrideExisting || !slice.IsSpecified(EDimension.ICP))) { slice[EDimension.ICP] = "[ICP None]"; } foreach(var id in _metadata.CustomDimIds) { if(!_metadata.IsPhasedSubmissionEnabledForDimension(id) && (overrideExisting || !slice.IsSpecified(id))) { slice[id] = "[None]"; } } } /// Returns true if it is possible to go from start state to end state protected bool IsValidStateTransition(EProcessAction action, POV pu, EProcessState start, EProcessState end) { bool ok = false; switch(action) { case EProcessAction.Start: ok = start == EProcessState.NotStarted; break; case EProcessAction.Promote: ok = start >= EProcessState.FirstPass && start < EProcessState.ReviewLevel10 && end >= EProcessState.ReviewLevel1 && end <= EProcessState.ReviewLevel10 && end > start; break; case EProcessAction.Reject: ok = start != EProcessState.NotStarted; break; case EProcessAction.SignOff: ok = start >= EProcessState.ReviewLevel1; break; case EProcessAction.Submit: ok = start >= EProcessState.FirstPass && start < EProcessState.Submitted; break; case EProcessAction.Approve: ok = start == EProcessState.Submitted; break; case EProcessAction.Publish: ok = start >= EProcessState.Submitted && start < EProcessState.Published; break; } if(ok) { _log.TraceFormat("{0} {1} is in a valid state to {2}", ProcessUnitType.Capitalize(), pu, action); } else { _log.WarnFormat("{0} {1} is in the wrong state ({2}) to {3}", ProcessUnitType.Capitalize(), pu, start, action); } return ok; } // Check user has sufficient access rights for action protected bool HasSufficientAccess(EProcessAction action, POV pu, EAccessRights access, EProcessState state) { bool ok = false; switch(action) { case EProcessAction.Start: ok = access == EAccessRights.All; break; case EProcessAction.Promote: ok = access == EAccessRights.Promote || access == EAccessRights.All; break; case EProcessAction.Reject: ok = access == EAccessRights.All || ((access == EAccessRights.Read || access == EAccessRights.Promote) && state != EProcessState.Published); break; case EProcessAction.SignOff: ok = access == EAccessRights.Read || access == EAccessRights.Promote || access == EAccessRights.All; break; case EProcessAction.Submit: ok = access == EAccessRights.Promote || access == EAccessRights.All; break; case EProcessAction.Approve: ok = access == EAccessRights.Promote || access == EAccessRights.All; break; case EProcessAction.Publish: ok = access == EAccessRights.All; break; } if(ok) { _log.TraceFormat("User has sufficient privileges to {0} {1} {2}", action, ProcessUnitType, pu); } else { _log.WarnFormat("Insufficient privileges to {0} {1} {2}", action, ProcessUnitType, pu); } return ok; } // To be able to change the status of a process unit, it needs to be: // unlocked, calculated, and valid protected bool CanAction(EProcessAction action, POV pu, bool consolidateIfNeeded, IOutput output) { bool ok = true; if(action == EProcessAction.Promote || action == EProcessAction.SignOff || action == EProcessAction.Submit || action == EProcessAction.Approve || action == EProcessAction.Publish) { ok = CheckCalcStatus(action, pu, consolidateIfNeeded, output); ok = ok && CheckValidationStatus(action, pu); } return ok; } protected bool CheckCalcStatus(EProcessAction action, POV pu, bool consolidateIfNeeded, IOutput output) { bool ok = false; var calcStatus = _session.Data.GetCalcStatus(pu); if(_log.IsDebugEnabled) { var cs = StringUtilities.Join(ECalcStatusExtensions.GetCellStatuses(calcStatus), ", "); _log.DebugFormat("Process unit calculation status for {0}: ({1})", pu, cs); } if(ECalcStatus.OK.IsSet(calcStatus) || ECalcStatus.OKButSystemChanged.IsSet(calcStatus) || ECalcStatus.NoData.IsSet(calcStatus)) { if(ECalcStatus.Locked.IsSet(calcStatus)) { _log.ErrorFormat("Cannot {0} {1} {2} as it has been locked", action, ProcessUnitType, pu); } else { _log.TraceFormat("Calculation status check passed for {0} of {1}", action, pu); ok = true; } } else if(consolidateIfNeeded) { if(ECalcStatus.NeedsCalculate.IsSet(calcStatus)) { _session.Calculate.CalculatePOV(pu, false); } else { _session.Calculate.ConsolidatePOV(pu, EConsolidationType.Impacted, output); } ok = true; } else { _log.ErrorFormat("Cannot {0} {1} {2} until it has been consolidated", action, ProcessUnitType, pu); } return ok; } protected bool CheckValidationStatus(EProcessAction action, POV pu) { bool ok = true; int group, phase; GetGroupPhase(pu, out group, out phase); if(phase == 0) { // Cell does not participate in process management throw new ArgumentException(string.Format("POV {0} is not valid for process management", pu)); } var account = _metadata.GetPhaseValidationAccount(phase); if(account.Id != Member.NOT_USED) { var pov = pu.Copy(); // Set validation account POV pov.Account = account; pov.View = _metadata.View.GetMember("<Scenario View>"); pov.ICP = _metadata.ICP.GetMember("[ICP Top]"); foreach(var id in _metadata.CustomDimIds) { pov[id] = account.GetTopCustomMember(id); } var valAmt = _session.Data.GetCellValue(pov); ok = valAmt == null || valAmt == 0; if(ok) { _log.TraceFormat("Validation status passed for {0}", pu); } else { _log.ErrorFormat("Cannot {0} {1} {2} until it passes validation", action, ProcessUnitType, pu); } } return ok; } /// Method to be implemented in sub-classes for setting the state of a /// single process unit represented by the POV. protected abstract EProcessState SetProcessState(POV processUnit, EProcessAction action, EProcessState targetState, string annotation, string[] paths, string[] files); } /// <summary> /// ProcessFlow subclass for working with applications that use Process Unit /// based process management. Process management is applied to process /// units, which are combinations of Scenario, Year, Period, Entity and /// Value. /// </summary> public class ProcessUnitProcessFlow : ProcessFlow { protected override string ProcessUnitType { get { return "process unit"; } } internal ProcessUnitProcessFlow(Session session) : base(session) { } protected override POV[] GetProcessUnits(ProcessUnits slice) { DefaultMembers(slice, true); return slice.ProcessUnitPOVs; } protected override void GetProcessState(ProcessUnits slice, IOutput output) { short state = 0; output.SetHeader("Process Unit", 58, "Process State", 15); foreach(var pu in GetProcessUnits(slice)) { HFM.Try("Retrieving process state for {0}", pu, () => _hsvProcessFlow.GetState(pu.Scenario.Id, pu.Year.Id, pu.Period.Id, pu.Entity.Id, pu.Entity.ParentId, pu.Value.Id, out state)); output.WriteRecord(pu, (EProcessState)state); } output.End(); } protected override void GetHistory(POV pu, IOutput output) { object oDates = null, oUsers = null, oActions = null, oStates = null, oAnnotations = null, oPaths = null, oFiles = null; HFM.Try("Retrieving process history for {0}", pu, () => _hsvProcessFlow.GetHistory2(pu.Scenario.Id, pu.Year.Id, pu.Period.Id, pu.Entity.Id, pu.Entity.ParentId, pu.Value.Id, out oDates, out oUsers, out oActions, out oStates, out oAnnotations, out oPaths, out oFiles)); OutputHistory(output, pu, oDates, oUsers, oActions, oStates, oAnnotations, oPaths, oFiles); } protected override EProcessState SetProcessState(POV pu, EProcessAction action, EProcessState targetState, string annotation, string[] paths, string[] files) { short newState = 0; HFM.Try("Setting process unit state for {0}", pu, () => _hsvProcessFlow.ProcessManagementChangeStateForMultipleEntities2( pu.Scenario.Id, pu.Year.Id, pu.Period.Id, new int[] { pu.Entity.Id }, new int[] { pu.Entity.ParentId }, pu.Value.Id, annotation, (int)action, false, false, (short)targetState, paths, files, out newState)); return (EProcessState)newState; } } /// <summary> /// ProcessFlow subclass for working with applications that use Phased /// Submissions. This allows process management to be applied to sets of /// Accounts, ICP members, and Customs, in addition to the standard Scenario /// Year, Period, Entity and Value. /// </summary> public class PhasedSubmissionProcessFlow : ProcessFlow { protected override string ProcessUnitType { get { return "phased submission"; } } internal PhasedSubmissionProcessFlow(Session session) : base(session) { } protected override POV[] GetProcessUnits(ProcessUnits slice) { DefaultMembers(slice, true); return slice.POVs; } protected override void GetProcessState(ProcessUnits slice, IOutput output) { short state = 0; output.SetHeader("POV", 58, "Process State", 15); foreach(var pov in GetProcessUnits(slice)) { if(HFM.HasVariableCustoms) { #if HFM_11_1_2_2 HFM.Try("Retrieving phased submission process state for {0}", pov, () => _hsvProcessFlow.GetPhasedSubmissionStateExtDim(pov.HfmPovCOM, out state)); #else HFM.ThrowIncompatibleLibraryEx(); #endif } else { HFM.Try("Retrieving phased submission process state for {0}", pov, () => _hsvProcessFlow.GetPhasedSubmissionState(pov.Scenario.Id, pov.Year.Id, pov.Period.Id, pov.Entity.Id, pov.Entity.ParentId, pov.Value.Id, pov.Account.Id, pov.ICP.Id, pov.Custom1.Id, pov.Custom2.Id, pov.Custom3.Id, pov.Custom4.Id, out state)); } output.WriteRecord(pov, (EProcessState)state); } output.End(); } protected override void GetHistory(POV pov, IOutput output) { object oDates = null, oUsers = null, oActions = null, oStates = null, oAnnotations = null, oPaths = null, oFiles = null; if(HFM.HasVariableCustoms) { #if HFM_11_1_2_2 HFM.Try("Retrieving process history for {0}", pov, () => _hsvProcessFlow.PhasedSubmissionGetHistory2ExtDim(pov.HfmPovCOM, out oDates, out oUsers, out oActions, out oStates, out oAnnotations, out oPaths, out oFiles)); #else HFM.ThrowIncompatibleLibraryEx(); #endif } else { HFM.Try("Retrieving process history {0}", pov, () => _hsvProcessFlow.PhasedSubmissionGetHistory2(pov.Scenario.Id, pov.Year.Id, pov.Period.Id, pov.Entity.Id, pov.Entity.ParentId, pov.Value.Id, pov.Account.Id, pov.ICP.Id, pov.Custom1.Id, pov.Custom2.Id, pov.Custom3.Id, pov.Custom4.Id, out oDates, out oUsers, out oActions, out oStates, out oAnnotations, out oPaths, out oFiles)); } OutputHistory(output, pov, oDates, oUsers, oActions, oStates, oAnnotations, oPaths, oFiles); } protected override EProcessState SetProcessState(POV pov, EProcessAction action, EProcessState targetState, string annotation, string[] paths, string[] files) { short newState = 0; if(HFM.HasVariableCustoms) { #if HFM_11_1_2_2 HFM.Try("Setting phased submission state for {0}", pov, () => _hsvProcessFlow.PhasedSubmissionProcessManagementChangeStateForMultipleEntities2ExtDim( pov.HfmSliceCOM, annotation, (int)action, false, false, (short)targetState, paths, files, out newState)); #else HFM.ThrowIncompatibleLibraryEx(); #endif } else { HFM.Try("Setting phased submission state for {0}", pov, () => _hsvProcessFlow.PhasedSubmissionProcessManagementChangeStateForMultipleEntities2( pov.Scenario.Id, pov.Year.Id, pov.Period.Id, new int[] { pov.Entity.Id }, new int[] { pov.Entity.ParentId }, pov.Value.Id, new int[] { pov.Account.Id }, new int[] { pov.ICP.Id }, new int[] { pov.Custom1.Id }, new int[] { pov.Custom2.Id }, new int[] { pov.Custom3.Id }, new int[] { pov.Custom4.Id }, annotation, (int)action, false, false, (short)targetState, paths, files, out newState)); } return (EProcessState)newState; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; // Ref: https://gist.github.com/jnm2/83b36ad497b4cb1cbcac namespace DbLocalizationProvider.Tests.InterfaceTests { public enum NameComparison { None, CaseSensitive, CaseInsensitive } public enum ConstantComparison { ByExpressionReference, ByCurrentValueReference, ByCurrentValueValue } public sealed class ExpressionComparer : IEqualityComparer<Expression> { public NameComparison CompareLambdaNames { get; set; } public NameComparison CompareParameterNames { get; set; } public ConstantComparison CompareConstants { get; set; } public ExpressionComparer() { this.CompareConstants = ConstantComparison.ByCurrentValueValue; } public bool Equals(Expression x, Expression y) { return EqualsImpl(x, y, null); } private bool EqualsImpl(Expression x, Expression y, ParameterContext parameterContext) { if (x == y) return true; if (x == null || y == null || x.NodeType != y.NodeType || x.Type != y.Type) return false; switch (x.NodeType) { case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.Power: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.ExclusiveOr: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.Assign: case ExpressionType.AddAssign: case ExpressionType.AndAssign: case ExpressionType.DivideAssign: case ExpressionType.ExclusiveOrAssign: case ExpressionType.LeftShiftAssign: case ExpressionType.ModuloAssign: case ExpressionType.MultiplyAssign: case ExpressionType.OrAssign: case ExpressionType.PowerAssign: case ExpressionType.RightShiftAssign: case ExpressionType.SubtractAssign: case ExpressionType.AddAssignChecked: case ExpressionType.SubtractAssignChecked: case ExpressionType.MultiplyAssignChecked: { var xt = (BinaryExpression)x; var yt = (BinaryExpression)y; return xt.Method == yt.Method && EqualsImpl(xt.Left, yt.Left, parameterContext) && EqualsImpl(xt.Right, yt.Right, parameterContext) && EqualsImpl(xt.Conversion, yt.Conversion, parameterContext); } case ExpressionType.Block: { var xt = (BlockExpression)x; var yt = (BlockExpression)y; if (xt.Expressions.Count != yt.Expressions.Count || xt.Variables.Count != yt.Variables.Count) return false; for (var i = 0; i < xt.Variables.Count; i++) if (!EqualsImpl(xt.Variables[i], yt.Variables[i], parameterContext)) return false; for (var i = 0; i < xt.Expressions.Count; i++) if (!EqualsImpl(xt.Expressions[i], yt.Expressions[i], parameterContext)) return false; return true; } case ExpressionType.Conditional: { var xt = (ConditionalExpression)x; var yt = (ConditionalExpression)y; return EqualsImpl(xt.Test, yt.Test, parameterContext) && EqualsImpl(xt.IfTrue, yt.IfTrue, parameterContext) && EqualsImpl(xt.IfFalse, yt.IfFalse, parameterContext); } case ExpressionType.Constant: { switch (this.CompareConstants) { case ConstantComparison.ByCurrentValueValue: return Equals(((ConstantExpression)x).Value, ((ConstantExpression)y).Value); case ConstantComparison.ByCurrentValueReference: return ((ConstantExpression)x).Value == ((ConstantExpression)y).Value; case ConstantComparison.ByExpressionReference: return x == y; default: throw new InvalidEnumArgumentException("CompareConstants", (int)this.CompareConstants, typeof(ConstantComparison)); } } case ExpressionType.Default: { return true; } case ExpressionType.Dynamic: { var xt = (DynamicExpression)x; var yt = (DynamicExpression)y; if (xt.Binder != yt.Binder || xt.DelegateType != yt.DelegateType || xt.Arguments.Count != yt.Arguments.Count) return false; for (var i = 0; i < xt.Arguments.Count; i++) if (!EqualsImpl(xt.Arguments[i], yt.Arguments[i], parameterContext)) return false; return true; } case ExpressionType.Index: { var xt = (IndexExpression)x; var yt = (IndexExpression)y; if (xt.Arguments.Count != yt.Arguments.Count || xt.Indexer != yt.Indexer || !EqualsImpl(xt.Object, yt.Object, parameterContext)) return false; for (var i = 0; i < xt.Arguments.Count; i++) if (!EqualsImpl(xt.Arguments[i], yt.Arguments[i], parameterContext)) return false; return true; } case ExpressionType.Invoke: { var xt = (InvocationExpression)x; var yt = (InvocationExpression)y; if (xt.Arguments.Count != yt.Arguments.Count || !EqualsImpl(xt.Expression, yt.Expression, parameterContext)) return false; for (var i = 0; i < xt.Arguments.Count; i++) if (!EqualsImpl(xt.Arguments[i], yt.Arguments[i], parameterContext)) return false; return true; } case ExpressionType.Lambda: { var xt = (LambdaExpression)x; var yt = (LambdaExpression)y; if (!CompareNames(xt.Name, yt.Name, this.CompareLambdaNames) || xt.Parameters.Count != yt.Parameters.Count) return false; for (var i = 0; i < xt.Parameters.Count; i++) if (!EqualsImpl(xt.Parameters[i], yt.Parameters[i], null)) return false; // This and the catch parameter are the only cases where we compare parameters by value instead of positionally return EqualsImpl(xt.Body, yt.Body, new ParameterContext(parameterContext, xt.Parameters.ToArray(), yt.Parameters.ToArray())); } case ExpressionType.ListInit: { var xt = (ListInitExpression)x; var yt = (ListInitExpression)y; return EqualsImpl(xt.NewExpression, yt.NewExpression, parameterContext) && EqualsImpl(xt.Initializers, yt.Initializers, parameterContext); } case ExpressionType.MemberAccess: { var xt = (MemberExpression)x; var yt = (MemberExpression)y; return xt.Member == yt.Member && EqualsImpl(xt.Expression, yt.Expression, parameterContext); } case ExpressionType.MemberInit: { var xt = (MemberInitExpression)x; var yt = (MemberInitExpression)y; if (xt.Bindings.Count != yt.Bindings.Count || !EqualsImpl(xt.NewExpression, yt.NewExpression, parameterContext)) return false; for (var i = 0; i < xt.Bindings.Count; i++) if (!EqualsImpl(xt.Bindings[i], yt.Bindings[i], parameterContext)) return false; return true; } case ExpressionType.Call: { var xt = (MethodCallExpression)x; var yt = (MethodCallExpression)y; if (xt.Arguments.Count != yt.Arguments.Count || xt.Method != yt.Method || !EqualsImpl(xt.Object, yt.Object, parameterContext)) return false; for (var i = 0; i < xt.Arguments.Count; i++) if (!EqualsImpl(xt.Arguments[i], yt.Arguments[i], parameterContext)) return false; return true; } case ExpressionType.NewArrayBounds: case ExpressionType.NewArrayInit: { var xt = (NewArrayExpression)x; var yt = (NewArrayExpression)y; if (xt.Expressions.Count != yt.Expressions.Count) return false; for (var i = 0; i < xt.Expressions.Count; i++) if (!EqualsImpl(xt.Expressions[i], yt.Expressions[i], parameterContext)) return false; return true; } case ExpressionType.New: { var xt = (NewExpression)x; var yt = (NewExpression)y; // I believe NewExpression.Members is guaranteed to be the same if NewExpression.Constructor is the same. if (xt.Arguments.Count != yt.Arguments.Count || xt.Constructor == yt.Constructor) return false; for (var i = 0; i < xt.Arguments.Count; i++) if (!EqualsImpl(xt.Arguments[i], yt.Arguments[i], parameterContext)) return false; return true; } case ExpressionType.Parameter: { var xt = (ParameterExpression)x; var yt = (ParameterExpression)y; if (parameterContext != null) { int xIndex; var currentContext = parameterContext; while (true) { xIndex = Array.IndexOf(currentContext.XParameters, xt); if (xIndex != -1) break; currentContext = currentContext.ParentContext; if (currentContext == null) throw new InvalidOperationException("X parameter " + xt + " is not contained in a parent lambda context or catch block variable context. Since parameter equality is determined positionally, the equality is ambiguous."); } var yIndex = Array.IndexOf(currentContext.YParameters, yt); if (yIndex == -1) throw new InvalidOperationException("Y parameter " + yt + " is not defined in the same parent lambda context or catch block variable context as the x parameter " + xt + "."); return xIndex == yIndex; } return CompareNames(xt.Name, yt.Name, this.CompareParameterNames) && xt.IsByRef == yt.IsByRef; } case ExpressionType.Switch: { var xt = (SwitchExpression)x; var yt = (SwitchExpression)y; if (xt.Comparison != yt.Comparison || xt.Cases.Count != yt.Cases.Count || !EqualsImpl(xt.SwitchValue, yt.SwitchValue, parameterContext) || !EqualsImpl(xt.DefaultBody, yt.DefaultBody, parameterContext)) return false; for (var i = 0; i < xt.Cases.Count; i++) { var xCase = xt.Cases[i]; var yCase = yt.Cases[i]; if (xCase.TestValues.Count != yCase.TestValues.Count || !EqualsImpl(xCase.Body, yCase.Body, parameterContext)) return false; for (var ti = 0; ti < xCase.TestValues.Count; ti++) if (!EqualsImpl(xCase.TestValues[ti], yCase.TestValues[ti], parameterContext)) return false; } return true; } case ExpressionType.Try: { var xt = (TryExpression)x; var yt = (TryExpression)y; if (xt.Handlers.Count != yt.Handlers.Count || !EqualsImpl(xt.Body, yt.Body, parameterContext) || !EqualsImpl(xt.Fault, yt.Fault, parameterContext) || !EqualsImpl(xt.Finally, yt.Finally, parameterContext)) return false; for (var i = 0; i < xt.Handlers.Count; i++) { var xHandler = xt.Handlers[i]; var yHandler = yt.Handlers[i]; var newParameterContext = new ParameterContext(parameterContext, new [] { xHandler.Variable }, new[] { yHandler.Variable }); if (xHandler.Test != yHandler.Test || !EqualsImpl(xHandler.Body, yHandler.Body, newParameterContext) || !EqualsImpl(xHandler.Filter, yHandler.Filter, newParameterContext) ||!EqualsImpl(xHandler.Variable, yHandler.Variable, null)) return false; // This and the lambda definition are the only cases where we compare parameters by value instead of positionally } return true; } case ExpressionType.TypeIs: { var xt = (TypeBinaryExpression)x; var yt = (TypeBinaryExpression)y; return xt.TypeOperand == yt.TypeOperand && EqualsImpl(xt.Expression, yt.Expression, parameterContext); } case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.IsFalse: case ExpressionType.IsTrue: case ExpressionType.OnesComplement: case ExpressionType.ArrayLength: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.Throw: case ExpressionType.TypeAs: case ExpressionType.Quote: case ExpressionType.UnaryPlus: case ExpressionType.Unbox: case ExpressionType.Increment: case ExpressionType.Decrement: case ExpressionType.PreIncrementAssign: case ExpressionType.PostIncrementAssign: case ExpressionType.PreDecrementAssign: case ExpressionType.PostDecrementAssign: { var xt = (UnaryExpression)x; var yt = (UnaryExpression)y; return xt.Method == yt.Method && EqualsImpl(xt.Operand, yt.Operand, parameterContext); } default: throw new NotImplementedException(x.NodeType.ToString()); } } private bool EqualsImpl(MemberBinding x, MemberBinding y, ParameterContext parameterContext) { if (x.Member != y.Member || x.BindingType != y.BindingType) return false; switch (x.BindingType) { case MemberBindingType.Assignment: return EqualsImpl(((MemberAssignment)x).Expression, ((MemberAssignment)y).Expression, parameterContext); case MemberBindingType.MemberBinding: { var xtBinding = (MemberMemberBinding)x; var ytBinding = (MemberMemberBinding)y; if (xtBinding.Bindings.Count != ytBinding.Bindings.Count) return false; for (var i = 0; i < xtBinding.Bindings.Count; i++) if (!EqualsImpl(xtBinding.Bindings[i], ytBinding.Bindings[i], parameterContext)) return false; return true; } case MemberBindingType.ListBinding: return EqualsImpl(((MemberListBinding)x).Initializers, ((MemberListBinding)y).Initializers, parameterContext); default: throw new NotImplementedException(x.BindingType.GetType() + " " + x.BindingType); } } private bool EqualsImpl(IList<ElementInit> x, IList<ElementInit> y, ParameterContext parameterContext) { if (x.Count != y.Count) return false; for (var i = 0; i < x.Count; i++) { var xInitializer = x[i]; var yInitializer = y[i]; if (xInitializer.AddMethod != yInitializer.AddMethod || xInitializer.Arguments.Count != yInitializer.Arguments.Count) return false; for (var ai = 0; ai < xInitializer.Arguments.Count; ai++) if (!EqualsImpl(xInitializer.Arguments[ai], yInitializer.Arguments[ai], parameterContext)) return false; } return true; } private sealed class ParameterContext { public readonly ParameterContext ParentContext; public readonly ParameterExpression[] XParameters; public readonly ParameterExpression[] YParameters; public ParameterContext(ParameterContext parentContext, ParameterExpression[] xParameters, ParameterExpression[] yParameters) { ParentContext = parentContext; XParameters = xParameters; YParameters = yParameters; } } private bool CompareNames(string name1, string name2, NameComparison comparison) { switch (comparison) { case NameComparison.None: return true; case NameComparison.CaseSensitive: return StringComparer.Ordinal.Equals(name1, name2); case NameComparison.CaseInsensitive: return StringComparer.OrdinalIgnoreCase.Equals(name1, name2); default: throw new InvalidEnumArgumentException("comparison", (int)comparison, typeof(NameComparison)); } } public int GetHashCode(Expression obj) { // Better to put everything in one bin than to let the default reference-based GetHashCode cause a false negative. return 0; } } }
using System; using System.Collections.ObjectModel; using System.Text.RegularExpressions; using NUnit.Framework; using OpenQA.Selenium.Environment; using System.Text; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { [TestFixture] public class CookieImplementationTest : DriverTestFixture { private Random random = new Random(); private bool isOnAlternativeHostName; private string hostname; [SetUp] public void GoToSimplePageAndDeleteCookies() { GotoValidDomainAndClearCookies("animals"); AssertNoCookiesArePresent(); } [Test] public void ShouldGetCookieByName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key = string.Format("key_{0}", new Random().Next()); ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key); Cookie cookie = driver.Manage().Cookies.GetCookieNamed(key); Assert.AreEqual("set", cookie.Value); } [Test] public void ShouldBeAbleToAddCookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key = GenerateUniqueKey(); string value = "foo"; Cookie cookie = new Cookie(key, value); AssertCookieIsNotPresentWithName(key); driver.Manage().Cookies.AddCookie(cookie); AssertCookieHasValue(key, value); Assert.That(driver.Manage().Cookies.AllCookies.Contains(cookie), "Cookie was not added successfully"); } [Test] public void GetAllCookies() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key1 = GenerateUniqueKey(); string key2 = GenerateUniqueKey(); AssertCookieIsNotPresentWithName(key1); AssertCookieIsNotPresentWithName(key2); ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies; int count = cookies.Count; Cookie one = new Cookie(key1, "value"); Cookie two = new Cookie(key2, "value"); driver.Manage().Cookies.AddCookie(one); driver.Manage().Cookies.AddCookie(two); driver.Url = simpleTestPage; cookies = driver.Manage().Cookies.AllCookies; Assert.AreEqual(count + 2, cookies.Count); Assert.That(cookies, Does.Contain(one)); Assert.That(cookies, Does.Contain(two)); } [Test] public void DeleteAllCookies() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = 'foo=set';"); AssertSomeCookiesArePresent(); driver.Manage().Cookies.DeleteAllCookies(); AssertNoCookiesArePresent(); } [Test] public void DeleteCookieWithName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key1 = GenerateUniqueKey(); string key2 = GenerateUniqueKey(); ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key1); ((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key2); AssertCookieIsPresentWithName(key1); AssertCookieIsPresentWithName(key2); driver.Manage().Cookies.DeleteCookieNamed(key1); AssertCookieIsNotPresentWithName(key1); AssertCookieIsPresentWithName(key2); } [Test] public void ShouldNotDeleteCookiesWithASimilarName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieOneName = "fish"; Cookie cookie1 = new Cookie(cookieOneName, "cod"); Cookie cookie2 = new Cookie(cookieOneName + "x", "earth"); IOptions options = driver.Manage(); AssertCookieIsNotPresentWithName(cookie1.Name); options.Cookies.AddCookie(cookie1); options.Cookies.AddCookie(cookie2); AssertCookieIsPresentWithName(cookie1.Name); options.Cookies.DeleteCookieNamed(cookieOneName); Assert.That(driver.Manage().Cookies.AllCookies, Does.Not.Contain(cookie1)); Assert.That(driver.Manage().Cookies.AllCookies, Does.Contain(cookie2)); } [Test] public void AddCookiesWithDifferentPathsThatAreRelatedToOurs() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string basePath = EnvironmentManager.Instance.UrlBuilder.Path; Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals"); Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/"); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); options.Cookies.AddCookie(cookie2); UrlBuilder builder = EnvironmentManager.Instance.UrlBuilder; driver.Url = builder.WhereIs("animals"); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; AssertCookieIsPresentWithName(cookie1.Name); AssertCookieIsPresentWithName(cookie2.Name); driver.Url = builder.WhereIs("simpleTest.html"); AssertCookieIsNotPresentWithName(cookie1.Name); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome does not retrieve cookies when in frame.")] public void GetCookiesInAFrame() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals"); Cookie cookie1 = new Cookie("fish", "cod", "/common/animals"); driver.Manage().Cookies.AddCookie(cookie1); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("frameWithAnimals.html"); AssertCookieIsNotPresentWithName(cookie1.Name); driver.SwitchTo().Frame("iframe1"); AssertCookieIsPresentWithName(cookie1.Name); } [Test] [IgnoreBrowser(Browser.Opera)] public void CannotGetCookiesWithPathDifferingOnlyInCase() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieName = "fish"; driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod", "/Common/animals")); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals"); Assert.That(driver.Manage().Cookies.GetCookieNamed(cookieName), Is.Null); } [Test] public void ShouldNotGetCookieOnDifferentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieName = "fish"; driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod")); AssertCookieIsPresentWithName(cookieName); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html"); AssertCookieIsNotPresentWithName(cookieName); } [Test] public void ShouldBeAbleToAddToADomainWhichIsRelatedToTheCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } AssertCookieIsNotPresentWithName("name"); Regex replaceRegex = new Regex(".*?\\."); string shorter = replaceRegex.Replace(this.hostname, ".", 1); Cookie cookie = new Cookie("name", "value", shorter, "/", GetTimeInTheFuture()); driver.Manage().Cookies.AddCookie(cookie); AssertCookieIsPresentWithName("name"); } [Test] public void ShouldNotGetCookiesRelatedToCurrentDomainWithoutLeadingPeriod() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string cookieName = "name"; AssertCookieIsNotPresentWithName(cookieName); Regex replaceRegex = new Regex(".*?\\."); string subdomain = replaceRegex.Replace(this.hostname, "subdomain.", 1); Cookie cookie = new Cookie(cookieName, "value", subdomain, "/", GetTimeInTheFuture()); string originalUrl = driver.Url; string subdomainUrl = originalUrl.Replace(this.hostname, subdomain); driver.Url = subdomainUrl; driver.Manage().Cookies.AddCookie(cookie); driver.Url = originalUrl; AssertCookieIsNotPresentWithName(cookieName); } [Test] public void ShouldBeAbleToIncludeLeadingPeriodInDomainName() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } AssertCookieIsNotPresentWithName("name"); // Replace the first part of the name with a period Regex replaceRegex = new Regex(".*?\\."); string shorter = replaceRegex.Replace(this.hostname, ".", 1); Cookie cookie = new Cookie("name", "value", shorter, "/", DateTime.Now.AddSeconds(100000)); driver.Manage().Cookies.AddCookie(cookie); AssertCookieIsPresentWithName("name"); } [Test] public void ShouldBeAbleToSetDomainToTheCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } Uri url = new Uri(driver.Url); String host = url.Host + ":" + url.Port.ToString(); Cookie cookie1 = new Cookie("fish", "cod", host, "/", null); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); driver.Url = javascriptPage; ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Contain(cookie1)); } [Test] public void ShouldWalkThePathToDeleteACookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string basePath = EnvironmentManager.Instance.UrlBuilder.Path; Cookie cookie1 = new Cookie("fish", "cod"); driver.Manage().Cookies.AddCookie(cookie1); int count = driver.Manage().Cookies.AllCookies.Count; driver.Url = childPage; Cookie cookie2 = new Cookie("rodent", "hamster", "/" + basePath + "/child"); driver.Manage().Cookies.AddCookie(cookie2); count = driver.Manage().Cookies.AllCookies.Count; driver.Url = grandchildPage; Cookie cookie3 = new Cookie("dog", "dalmation", "/" + basePath + "/child/grandchild/"); driver.Manage().Cookies.AddCookie(cookie3); count = driver.Manage().Cookies.AllCookies.Count; driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("child/grandchild")); driver.Manage().Cookies.DeleteCookieNamed("rodent"); count = driver.Manage().Cookies.AllCookies.Count; Assert.That(driver.Manage().Cookies.GetCookieNamed("rodent"), Is.Null); ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies; Assert.That(cookies, Has.Count.EqualTo(2)); Assert.That(cookies, Does.Contain(cookie1)); Assert.That(cookies, Does.Contain(cookie3)); driver.Manage().Cookies.DeleteAllCookies(); driver.Url = grandchildPage; AssertNoCookiesArePresent(); } [Test] public void ShouldIgnoreThePortNumberOfTheHostWhenSettingTheCookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } Uri uri = new Uri(driver.Url); string host = string.Format("{0}:{1}", uri.Host, uri.Port); string cookieName = "name"; AssertCookieIsNotPresentWithName(cookieName); Cookie cookie = new Cookie(cookieName, "value", host, "/", null); driver.Manage().Cookies.AddCookie(cookie); AssertCookieIsPresentWithName(cookieName); } [Test] [IgnoreBrowser(Browser.Opera)] public void CookieEqualityAfterSetAndGet() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); DateTime time = DateTime.Now.AddDays(1); Cookie cookie1 = new Cookie("fish", "cod", null, "/common/animals", time); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Cookie retrievedCookie = null; foreach (Cookie tempCookie in cookies) { if (cookie1.Equals(tempCookie)) { retrievedCookie = tempCookie; break; } } Assert.That(retrievedCookie, Is.Not.Null); //Cookie.equals only compares name, domain and path Assert.AreEqual(cookie1, retrievedCookie); } [Test] [IgnoreBrowser(Browser.Opera)] public void ShouldRetainCookieExpiry() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); // DateTime.Now contains milliseconds; the returned cookie expire date // will not. So we need to truncate the milliseconds. DateTime current = DateTime.Now; DateTime expireDate = new DateTime(current.Year, current.Month, current.Day, current.Hour, current.Minute, current.Second, DateTimeKind.Local).AddDays(1); Cookie addCookie = new Cookie("fish", "cod", "/common/animals", expireDate); IOptions options = driver.Manage(); options.Cookies.AddCookie(addCookie); Cookie retrieved = options.Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Not.Null); Assert.AreEqual(addCookie.Expiry, retrieved.Expiry, "Cookies are not equal"); } [Test] [IgnoreBrowser(Browser.IE, "Browser does not handle untrusted SSL certificates.")] public void CanHandleSecureCookie() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("animals"); Cookie addedCookie = new ReturnedCookie("fish", "cod", null, "/common/animals", null, true, false); driver.Manage().Cookies.AddCookie(addedCookie); driver.Navigate().Refresh(); Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Not.Null); } [Test] [IgnoreBrowser(Browser.IE, "Browser does not handle untrusted SSL certificates.")] public void ShouldRetainCookieSecure() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("animals"); ReturnedCookie addedCookie = new ReturnedCookie("fish", "cod", string.Empty, "/common/animals", null, true, false); driver.Manage().Cookies.AddCookie(addedCookie); driver.Navigate().Refresh(); Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Not.Null); Assert.That(retrieved.Secure, "Secure attribute not set to true"); } [Test] public void CanHandleHttpOnlyCookie() { StringBuilder url = new StringBuilder(EnvironmentManager.Instance.UrlBuilder.WhereIs("cookie")); url.Append("?action=add"); url.Append("&name=").Append("fish"); url.Append("&value=").Append("cod"); url.Append("&path=").Append("/common/animals"); url.Append("&httpOnly=").Append("true"); driver.Url = url.ToString(); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals"); Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Not.Null); } [Test] public void ShouldRetainHttpOnlyFlag() { StringBuilder url = new StringBuilder(EnvironmentManager.Instance.UrlBuilder.WhereElseIs("cookie")); url.Append("?action=add"); url.Append("&name=").Append("fish"); url.Append("&value=").Append("cod"); url.Append("&path=").Append("/common/animals"); url.Append("&httpOnly=").Append("true"); driver.Url = url.ToString(); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Not.Null); Assert.That(retrieved.IsHttpOnly, "HttpOnly attribute not set to true"); } [Test] public void SettingACookieThatExpiredInThePast() { string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); DateTime expires = DateTime.Now.AddSeconds(-1000); Cookie cookie = new Cookie("expired", "yes", "/common/animals", expires); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie); cookie = options.Cookies.GetCookieNamed("expired"); Assert.That(cookie, Is.Null, "Cookie expired before it was set, so nothing should be returned: " + cookie); } [Test] public void CanSetCookieWithoutOptionalFieldsSet() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string key = GenerateUniqueKey(); string value = "foo"; Cookie cookie = new Cookie(key, value); AssertCookieIsNotPresentWithName(key); driver.Manage().Cookies.AddCookie(cookie); AssertCookieHasValue(key, value); } [Test] public void DeleteNotExistedCookie() { String key = GenerateUniqueKey(); AssertCookieIsNotPresentWithName(key); driver.Manage().Cookies.DeleteCookieNamed(key); } [Test] public void DeleteAllCookiesDifferentUrls() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } Cookie cookie1 = new Cookie("fish1", "cod", EnvironmentManager.Instance.UrlBuilder.HostName, null, null); Cookie cookie2 = new Cookie("fish2", "tune", EnvironmentManager.Instance.UrlBuilder.AlternateHostName, null, null); string url1 = EnvironmentManager.Instance.UrlBuilder.WhereIs(""); string url2 = EnvironmentManager.Instance.UrlBuilder.WhereElseIs(""); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); AssertCookieIsPresentWithName(cookie1.Name); driver.Url = url2; options.Cookies.AddCookie(cookie2); AssertCookieIsNotPresentWithName(cookie1.Name); AssertCookieIsPresentWithName(cookie2.Name); driver.Url = url1; AssertCookieIsPresentWithName(cookie1.Name); AssertCookieIsNotPresentWithName(cookie2.Name); options.Cookies.DeleteAllCookies(); AssertCookieIsNotPresentWithName(cookie1.Name); driver.Url = url2; AssertCookieIsPresentWithName(cookie2.Name); } //------------------------------------------------------------------ // Tests below here are not included in the Java test suite //------------------------------------------------------------------ [Test] public void CanSetCookiesOnADifferentPathOfTheSameHost() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string basePath = EnvironmentManager.Instance.UrlBuilder.Path; Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals"); Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/galaxy"); IOptions options = driver.Manage(); ReadOnlyCollection<Cookie> count = options.Cookies.AllCookies; options.Cookies.AddCookie(cookie1); options.Cookies.AddCookie(cookie2); string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals"); driver.Url = url; ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Contain(cookie1)); Assert.That(cookies, Does.Not.Contain(cookie2)); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("galaxy"); cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Not.Contain(cookie1)); Assert.That(cookies, Does.Contain(cookie2)); } [Test] public void ShouldNotBeAbleToSetDomainToSomethingThatIsUnrelatedToTheCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } Cookie cookie1 = new Cookie("fish", "cod"); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html"); driver.Url = url; Assert.That(options.Cookies.GetCookieNamed("fish"), Is.Null); } [Test] public void GetCookieDoesNotRetriveBeyondCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } Cookie cookie1 = new Cookie("fish", "cod"); IOptions options = driver.Manage(); options.Cookies.AddCookie(cookie1); String url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs(""); driver.Url = url; ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Not.Contain(cookie1)); } [Test] public void ShouldAddCookieToCurrentDomainAndPath() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Homer", "Simpson", this.hostname, "/" + EnvironmentManager.Instance.UrlBuilder.Path, null); options.Cookies.AddCookie(cookie); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies.Contains(cookie), "Valid cookie was not returned"); } [Test] [IgnoreBrowser(Browser.Firefox)] public void ShouldNotShowCookieAddedToDifferentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { Assert.Ignore("Not on a standard domain for cookies (localhost doesn't count)."); } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Bart", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName + ".com", EnvironmentManager.Instance.UrlBuilder.Path, null); Assert.That(() => options.Cookies.AddCookie(cookie), Throws.InstanceOf<WebDriverException>().Or.InstanceOf<InvalidOperationException>()); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Not.Contain(cookie), "Invalid cookie was returned"); } [Test] public void ShouldNotShowCookieAddedToDifferentPath() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } // Cookies cannot be set on domain names with less than 2 dots, so // localhost is out. If we are in that boat, bail the test. string hostName = EnvironmentManager.Instance.UrlBuilder.HostName; string[] hostNameParts = hostName.Split(new char[] { '.' }); if (hostNameParts.Length < 3) { Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names."); } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Lisa", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName, "/" + EnvironmentManager.Instance.UrlBuilder.Path + "IDoNotExist", null); options.Cookies.AddCookie(cookie); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies, Does.Not.Contain(cookie), "Invalid cookie was returned"); } [Test] [IgnoreBrowser(Browser.Firefox, "Driver throws generic WebDriverException")] public void ShouldThrowExceptionWhenAddingCookieToNonExistingDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } driver.Url = macbethPage; driver.Url = "http://nonexistent-origin.seleniumhq-test.test"; IOptions options = driver.Manage(); Cookie cookie = new Cookie("question", "dunno"); Assert.That(() => options.Cookies.AddCookie(cookie), Throws.InstanceOf<InvalidCookieDomainException>().Or.InstanceOf<InvalidOperationException>()); } [Test] public void ShouldReturnNullBecauseCookieRetainsExpiry() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals"); driver.Url = url; driver.Manage().Cookies.DeleteAllCookies(); Cookie addCookie = new Cookie("fish", "cod", "/common/animals", DateTime.Now.AddHours(-1)); IOptions options = driver.Manage(); options.Cookies.AddCookie(addCookie); Cookie retrieved = options.Cookies.GetCookieNamed("fish"); Assert.That(retrieved, Is.Null); } [Test] public void ShouldAddCookieToCurrentDomain() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookie = new Cookie("Marge", "Simpson", "/"); options.Cookies.AddCookie(cookie); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; Assert.That(cookies.Contains(cookie), "Valid cookie was not returned"); } [Test] public void ShouldDeleteCookie() { if (!CheckIsOnValidHostNameForCookieTests()) { return; } driver.Url = macbethPage; IOptions options = driver.Manage(); Cookie cookieToDelete = new Cookie("answer", "42"); Cookie cookieToKeep = new Cookie("canIHaz", "Cheeseburguer"); options.Cookies.AddCookie(cookieToDelete); options.Cookies.AddCookie(cookieToKeep); ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies; options.Cookies.DeleteCookie(cookieToDelete); ReadOnlyCollection<Cookie> cookies2 = options.Cookies.AllCookies; Assert.That(cookies2, Does.Not.Contain(cookieToDelete), "Cookie was not deleted successfully"); Assert.That(cookies2.Contains(cookieToKeep), "Valid cookie was not returned"); } ////////////////////////////////////////////// // Support functions ////////////////////////////////////////////// private void GotoValidDomainAndClearCookies(string page) { this.hostname = null; String hostname = EnvironmentManager.Instance.UrlBuilder.HostName; if (IsValidHostNameForCookieTests(hostname)) { this.isOnAlternativeHostName = false; this.hostname = hostname; } hostname = EnvironmentManager.Instance.UrlBuilder.AlternateHostName; if (this.hostname == null && IsValidHostNameForCookieTests(hostname)) { this.isOnAlternativeHostName = true; this.hostname = hostname; } GoToPage(page); driver.Manage().Cookies.DeleteAllCookies(); } private bool CheckIsOnValidHostNameForCookieTests() { bool correct = this.hostname != null && IsValidHostNameForCookieTests(this.hostname); if (!correct) { System.Console.WriteLine("Skipping test: unable to find domain name to use"); } return correct; } private void GoToPage(String pageName) { driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName); } private void GoToOtherPage(String pageName) { driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName); } private bool IsValidHostNameForCookieTests(string hostname) { // TODO(JimEvan): Some coverage is better than none, so we // need to ignore the fact that localhost cookies are problematic. // Reenable this when we have a better solution per DanielWagnerHall. // ChromeDriver2 has trouble with localhost. IE and Firefox don't. // return !IsIpv4Address(hostname) && "localhost" != hostname; bool isLocalHostOkay = true; if ("localhost" == hostname && TestUtilities.IsChrome(driver)) { isLocalHostOkay = false; } return !IsIpv4Address(hostname) && isLocalHostOkay; } private static bool IsIpv4Address(string addrString) { return Regex.IsMatch(addrString, "\\d{1,3}(?:\\.\\d{1,3}){3}"); } private string GenerateUniqueKey() { return string.Format("key_{0}", random.Next()); } private string GetDocumentCookieOrNull() { IJavaScriptExecutor jsDriver = driver as IJavaScriptExecutor; if (jsDriver == null) { return null; } try { return (string)jsDriver.ExecuteScript("return document.cookie"); } catch (InvalidOperationException) { return null; } } private void AssertNoCookiesArePresent() { Assert.That(driver.Manage().Cookies.AllCookies.Count, Is.EqualTo(0), "Cookies were not empty"); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.AreEqual(string.Empty, documentCookie, "Cookies were not empty"); } } private void AssertSomeCookiesArePresent() { Assert.That(driver.Manage().Cookies.AllCookies.Count, Is.Not.EqualTo(0), "Cookies were empty"); String documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.AreNotEqual(string.Empty, documentCookie, "Cookies were empty"); } } private void AssertCookieIsNotPresentWithName(string key) { Assert.That(driver.Manage().Cookies.GetCookieNamed(key), Is.Null, "Cookie was present with name " + key); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.That(documentCookie, Does.Not.Contain(key + "=")); } } private void AssertCookieIsPresentWithName(string key) { Assert.That(driver.Manage().Cookies.GetCookieNamed(key), Is.Not.Null, "Cookie was present with name " + key); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.That(documentCookie, Does.Contain(key + "=")); } } private void AssertCookieHasValue(string key, string value) { Assert.AreEqual(value, driver.Manage().Cookies.GetCookieNamed(key).Value, "Cookie had wrong value"); string documentCookie = GetDocumentCookieOrNull(); if (documentCookie != null) { Assert.That(documentCookie, Does.Contain(key + "=" + value)); } } private DateTime GetTimeInTheFuture() { return DateTime.Now.Add(TimeSpan.FromMilliseconds(100000)); } } }
using System; namespace NBitcoin.BouncyCastle.Crypto.Utilities { internal sealed class Pack { private Pack() { } internal static void UInt16_To_BE(ushort n, byte[] bs) { bs[0] = (byte)(n >> 8); bs[1] = (byte)(n); } internal static void UInt16_To_BE(ushort n, byte[] bs, int off) { bs[off] = (byte)(n >> 8); bs[off + 1] = (byte)(n); } internal static ushort BE_To_UInt16(byte[] bs) { uint n = (uint)bs[0] << 8 | (uint)bs[1]; return (ushort)n; } internal static ushort BE_To_UInt16(byte[] bs, int off) { uint n = (uint)bs[off] << 8 | (uint)bs[off + 1]; return (ushort)n; } internal static byte[] UInt32_To_BE(uint n) { byte[] bs = new byte[4]; UInt32_To_BE(n, bs, 0); return bs; } internal static void UInt32_To_BE(uint n, byte[] bs) { bs[0] = (byte)(n >> 24); bs[1] = (byte)(n >> 16); bs[2] = (byte)(n >> 8); bs[3] = (byte)(n); } internal static void UInt32_To_BE(uint n, byte[] bs, int off) { bs[off] = (byte)(n >> 24); bs[off + 1] = (byte)(n >> 16); bs[off + 2] = (byte)(n >> 8); bs[off + 3] = (byte)(n); } internal static byte[] UInt32_To_BE(uint[] ns) { byte[] bs = new byte[4 * ns.Length]; UInt32_To_BE(ns, bs, 0); return bs; } internal static void UInt32_To_BE(uint[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt32_To_BE(ns[i], bs, off); off += 4; } } internal static uint BE_To_UInt32(byte[] bs) { return (uint)bs[0] << 24 | (uint)bs[1] << 16 | (uint)bs[2] << 8 | (uint)bs[3]; } internal static uint BE_To_UInt32(byte[] bs, int off) { return (uint)bs[off] << 24 | (uint)bs[off + 1] << 16 | (uint)bs[off + 2] << 8 | (uint)bs[off + 3]; } internal static void BE_To_UInt32(byte[] bs, int off, uint[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = BE_To_UInt32(bs, off); off += 4; } } internal static byte[] UInt64_To_BE(ulong n) { byte[] bs = new byte[8]; UInt64_To_BE(n, bs, 0); return bs; } internal static void UInt64_To_BE(ulong n, byte[] bs) { UInt32_To_BE((uint)(n >> 32), bs); UInt32_To_BE((uint)(n), bs, 4); } internal static void UInt64_To_BE(ulong n, byte[] bs, int off) { UInt32_To_BE((uint)(n >> 32), bs, off); UInt32_To_BE((uint)(n), bs, off + 4); } internal static ulong BE_To_UInt64(byte[] bs) { uint hi = BE_To_UInt32(bs); uint lo = BE_To_UInt32(bs, 4); return ((ulong)hi << 32) | (ulong)lo; } internal static ulong BE_To_UInt64(byte[] bs, int off) { uint hi = BE_To_UInt32(bs, off); uint lo = BE_To_UInt32(bs, off + 4); return ((ulong)hi << 32) | (ulong)lo; } internal static void UInt16_To_LE(ushort n, byte[] bs) { bs[0] = (byte)(n); bs[1] = (byte)(n >> 8); } internal static void UInt16_To_LE(ushort n, byte[] bs, int off) { bs[off] = (byte)(n); bs[off + 1] = (byte)(n >> 8); } internal static ushort LE_To_UInt16(byte[] bs) { uint n = (uint)bs[0] | (uint)bs[1] << 8; return (ushort)n; } internal static ushort LE_To_UInt16(byte[] bs, int off) { uint n = (uint)bs[off] | (uint)bs[off + 1] << 8; return (ushort)n; } internal static byte[] UInt32_To_LE(uint n) { byte[] bs = new byte[4]; UInt32_To_LE(n, bs, 0); return bs; } internal static void UInt32_To_LE(uint n, byte[] bs) { bs[0] = (byte)(n); bs[1] = (byte)(n >> 8); bs[2] = (byte)(n >> 16); bs[3] = (byte)(n >> 24); } internal static void UInt32_To_LE(uint n, byte[] bs, int off) { bs[off] = (byte)(n); bs[off + 1] = (byte)(n >> 8); bs[off + 2] = (byte)(n >> 16); bs[off + 3] = (byte)(n >> 24); } internal static byte[] UInt32_To_LE(uint[] ns) { byte[] bs = new byte[4 * ns.Length]; UInt32_To_LE(ns, bs, 0); return bs; } internal static void UInt32_To_LE(uint[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt32_To_LE(ns[i], bs, off); off += 4; } } internal static uint LE_To_UInt32(byte[] bs) { return (uint)bs[0] | (uint)bs[1] << 8 | (uint)bs[2] << 16 | (uint)bs[3] << 24; } internal static uint LE_To_UInt32(byte[] bs, int off) { return (uint)bs[off] | (uint)bs[off + 1] << 8 | (uint)bs[off + 2] << 16 | (uint)bs[off + 3] << 24; } internal static void LE_To_UInt32(byte[] bs, int off, uint[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = LE_To_UInt32(bs, off); off += 4; } } internal static void LE_To_UInt32(byte[] bs, int bOff, uint[] ns, int nOff, int count) { for (int i = 0; i < count; ++i) { ns[nOff + i] = LE_To_UInt32(bs, bOff); bOff += 4; } } internal static byte[] UInt64_To_LE(ulong n) { byte[] bs = new byte[8]; UInt64_To_LE(n, bs, 0); return bs; } internal static void UInt64_To_LE(ulong n, byte[] bs) { UInt32_To_LE((uint)(n), bs); UInt32_To_LE((uint)(n >> 32), bs, 4); } internal static void UInt64_To_LE(ulong n, byte[] bs, int off) { UInt32_To_LE((uint)(n), bs, off); UInt32_To_LE((uint)(n >> 32), bs, off + 4); } internal static ulong LE_To_UInt64(byte[] bs) { uint lo = LE_To_UInt32(bs); uint hi = LE_To_UInt32(bs, 4); return ((ulong)hi << 32) | (ulong)lo; } internal static ulong LE_To_UInt64(byte[] bs, int off) { uint lo = LE_To_UInt32(bs, off); uint hi = LE_To_UInt32(bs, off + 4); return ((ulong)hi << 32) | (ulong)lo; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using TIKSN.Finance.ForeignExchange.Bank; using TIKSN.Globalization; using TIKSN.Time; using Xunit; namespace TIKSN.Finance.ForeignExchange.Tests { public class BankOfCanadaTests { private readonly ICurrencyFactory _currencyFactory; private readonly ITimeProvider _timeProvider; public BankOfCanadaTests() { var services = new ServiceCollection(); _ = services.AddMemoryCache(); _ = services.AddSingleton<ICurrencyFactory, CurrencyFactory>(); _ = services.AddSingleton<IRegionFactory, RegionFactory>(); _ = services.AddSingleton<ITimeProvider, TimeProvider>(); var serviceProvider = services.BuildServiceProvider(); this._currencyFactory = serviceProvider.GetRequiredService<ICurrencyFactory>(); this._timeProvider = serviceProvider.GetRequiredService<ITimeProvider>(); } [Fact] public async Task Calculate001Async() { var bank = new BankOfCanada(this._currencyFactory, this._timeProvider); foreach (var pair in await bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true)) { var Before = new Money(pair.BaseCurrency, 10m); var rate = await bank.GetExchangeRateAsync(pair, DateTimeOffset.Now, default).ConfigureAwait(true); var After = await bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(After.Amount == rate * Before.Amount); Assert.True(After.Currency == pair.CounterCurrency); } } [Fact] public async Task ConversionDirection001Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var CanadianDollar = new CurrencyInfo(new RegionInfo("CA")); var PoundSterling = new CurrencyInfo(new RegionInfo("GB")); var BeforeInPound = new Money(PoundSterling, 100m); var AfterInDollar = await Bank.ConvertCurrencyAsync(BeforeInPound, CanadianDollar, DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(BeforeInPound.Amount < AfterInDollar.Amount); } [Fact] public async Task ConvertCurrency001Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { var Before = new Money(pair.BaseCurrency, decimal.One); var After = await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(After.Amount > decimal.Zero); } } [Fact] public async Task ConvertCurrency002Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { var Before = new Money(pair.BaseCurrency, decimal.One); var After = await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(After.Currency == pair.CounterCurrency); } } [Fact] public async Task ConvertCurrency003Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { var Before = new Money(pair.BaseCurrency, 10m); var After = await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, DateTimeOffset.Now, default).ConfigureAwait(true); var rate = await Bank.GetExchangeRateAsync(pair, DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(After.Currency == pair.CounterCurrency); Assert.True(After.Amount == rate * Before.Amount); } } [Fact] public async Task ConvertCurrency004Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var US = new RegionInfo("US"); var CA = new RegionInfo("CA"); var USD = new CurrencyInfo(US); var CAD = new CurrencyInfo(CA); var Before = new Money(USD, 100m); _ = await Assert.ThrowsAsync<ArgumentException>( async () => await Bank.ConvertCurrencyAsync(Before, CAD, DateTimeOffset.Now.AddMinutes(1d), default).ConfigureAwait(true)).ConfigureAwait(true); } [Fact] public async Task ConvertCurrency006Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var AO = new RegionInfo("AO"); var BW = new RegionInfo("BW"); var AOA = new CurrencyInfo(AO); var BWP = new CurrencyInfo(BW); var Before = new Money(AOA, 100m); _ = await Assert.ThrowsAsync<ArgumentException>( async () => await Bank.ConvertCurrencyAsync(Before, BWP, DateTimeOffset.Now, default).ConfigureAwait(true)).ConfigureAwait(true); } [Fact] public async Task CurrencyPairs001Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/USD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/AUD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/BRL"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/CNY"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/EUR"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/HKD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/INR"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/IDR"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/JPY"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/MXN"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/NZD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/NOK"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/PEN"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/RUB"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/SGD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/ZAR"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/KRW"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/SEK"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/CHF"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/TWD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/TRY"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CAD/GBP"); Assert.Contains(CurrencyPairs, C => C.ToString() == "USD/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "AUD/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "BRL/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CNY/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "EUR/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "HKD/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "INR/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "IDR/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "JPY/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "MXN/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "NZD/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "NOK/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "PEN/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "RUB/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "SGD/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "ZAR/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "KRW/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "SEK/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "CHF/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "TWD/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "TRY/CAD"); Assert.Contains(CurrencyPairs, C => C.ToString() == "GBP/CAD"); } [Fact] public async Task CurrencyPairs002Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { var reversePair = new CurrencyPair(pair.CounterCurrency, pair.BaseCurrency); Assert.Contains(CurrencyPairs, C => C == reversePair); } } [Fact] public async Task CurrencyPairs003Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var pairSet = new HashSet<CurrencyPair>(); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { _ = pairSet.Add(pair); } Assert.True(pairSet.Count == CurrencyPairs.Count()); } [Fact] public async Task CurrencyPairs005Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); _ = await Assert.ThrowsAsync<ArgumentException>( async () => await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now.AddDays(10), default).ConfigureAwait(true)).ConfigureAwait(true); } [Fact] public async Task Fetch001Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); _ = await Bank.GetExchangeRatesAsync(DateTimeOffset.Now, default).ConfigureAwait(true); } [Fact] public async Task GetExchangeRate001Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { var rate = await Bank.GetExchangeRateAsync(pair, DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(rate > decimal.Zero); } } [Fact] public async Task GetExchangeRate002Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var US = new RegionInfo("US"); var CA = new RegionInfo("CA"); var USD = new CurrencyInfo(US); var CAD = new CurrencyInfo(CA); var pair = new CurrencyPair(CAD, USD); _ = await Assert.ThrowsAsync<ArgumentException>( async () => await Bank.GetExchangeRateAsync(pair, DateTimeOffset.Now.AddMinutes(1d), default).ConfigureAwait(true)).ConfigureAwait(true); } [Fact] public async Task GetExchangeRate004Async() { var Bank = new BankOfCanada(this._currencyFactory, this._timeProvider); var AO = new RegionInfo("AO"); var BW = new RegionInfo("BW"); var AOA = new CurrencyInfo(AO); var BWP = new CurrencyInfo(BW); var pair = new CurrencyPair(BWP, AOA); _ = await Assert.ThrowsAsync<ArgumentException>( async () => await Bank.GetExchangeRateAsync(pair, DateTimeOffset.Now, default).ConfigureAwait(true)).ConfigureAwait(true); } } }
#region License // Pomona is open source software released under the terms of the LICENSE specified in the // project's repository, or alternatively at http://pomona.io/ #endregion using System; using System.Linq; using System.Reflection; using NUnit.Framework; using Pomona.Common.TypeSystem; using Pomona.Example; using Pomona.FluentMapping; namespace Pomona.UnitTests.FluentMapping { [TestFixture] public class FluentTypeConfiguratorTests : FluentMappingTestsBase { [Test] public void AsAbstract_GivenTypeThatWouldBeConcreteByConvention_MakesTypeAbstract() { CheckHowChangeInTypeRuleAffectsFilter<Top, bool>( x => x.AsAbstract(), (f, t) => f.GetTypeIsAbstract(t), (origValue, changedValue) => { Assert.That(changedValue, Is.Not.EqualTo(origValue), "Test no use if change in filter has no effect"); Assert.That(changedValue, Is.EqualTo(true)); }); } [Test] public void AsConcrete_GivenTypeThatWouldBeAbstractByConvention_MakesTypeNonAbstract() { CheckHowChangeInTypeRuleAffectsFilter<TestEntityBase, bool>( x => x.AsConcrete(), (f, t) => f.GetTypeIsAbstract(t), (origValue, changedValue) => { Assert.That(changedValue, Is.Not.EqualTo(origValue), "Test no use if change in filter has no effect"); Assert.That(changedValue, Is.EqualTo(false)); }); } [Test] public void AsSingleton_SetsIsSingletonToTrue() { CheckHowChangeInTypeRuleAffectsFilter<Top, bool>(x => x.AsSingleton(), (f, t) => f.TypeIsSingletonResource(t), false, true); } [Test] public void DefaultPropertyInclusionMode_SetToExcludedByDefault_IncludesOverriddenPropertyInInheritedClass() { var filter = GetMappingFilter(DefaultPropertyInclusionMode.AllPropertiesAreExcludedByDefault); Assert.That( filter.PropertyIsIncluded(typeof(TestEntityBase), GetPropInfo<TestEntityBase>(x => x.ToBeOverridden)), Is.True); var propInfo = typeof(Top).GetProperty("ToBeOverridden"); Assert.That(filter.PropertyIsIncluded(typeof(Top), propInfo), Is.True); } [Test] public void DefaultPropertyInclusionMode_SetToExcludedByDefault_IncludesPropertyInInheritedClass() { var filter = GetMappingFilter(DefaultPropertyInclusionMode.AllPropertiesAreExcludedByDefault); Assert.That(filter.PropertyIsIncluded(typeof(TestEntityBase), GetPropInfo<TestEntityBase>(x => x.Id)), Is.True); Assert.That(filter.PropertyIsIncluded(typeof(Specialized), GetPropInfo<Specialized>(x => x.Id)), Is.True); } [Test] public void DefaultPropertyInclusionMode_SetToExcludedByDefault_MakesPropertyExcludedByDefault() { var filter = GetMappingFilter(DefaultPropertyInclusionMode.AllPropertiesAreExcludedByDefault); Assert.That( filter.PropertyIsIncluded(typeof(Specialized), GetPropInfo<Specialized>(x => x.WillMapToDefault)), Is.False); } [Test] public void DefaultPropertyInclusionMode_SetToIncludedByDefault_MakesPropertyIncludedByDefault() { var filter = GetMappingFilter(DefaultPropertyInclusionMode.AllPropertiesAreIncludedByDefault); Assert.That( filter.PropertyIsIncluded(typeof(Specialized), GetPropInfo<Specialized>(x => x.WillMapToDefault)), Is.True); } [Test] public void ExposedAt_Root_ResultsInEmptyString() { CheckHowChangeInTypeRuleAffectsFilter<Top, string>( x => x.ExposedAt("/"), (f, t) => ((ResourceType)new TypeMapper(f, new[] { typeof(Top) }, null).FromType<Top>()) .UrlRelativePath, "tops", ""); } [Test] public void ExposedAt_WillModifyUrlRelativePath() { CheckHowChangeInTypeRuleAffectsFilter<Top, string>( x => x.ExposedAt("newpath"), (f, t) => f.GetUrlRelativePath(t), (origValue, changedValue) => { Assert.That(changedValue, Is.Not.EqualTo(origValue), "Test no use if change in filter has no effect"); Assert.That(changedValue, Is.EqualTo("newpath")); }); } [Test] public void ExposedAt_WithLeadingPathSeparator_LeadingPathSeparatorIsStrippedFromMappedType() { CheckHowChangeInTypeRuleAffectsFilter<Top, ResourceType>( x => x.ExposedAt("/newpath"), (f, t) => (ResourceType)new TypeMapper(f, new[] { typeof(Top) }, null).FromType<Top>(), (origValue, changedValue) => { Assert.That(changedValue.UrlRelativePath, Is.Not.EqualTo(origValue), "Test no use if change in filter has no effect"); Assert.That(changedValue.UrlRelativePath, Is.EqualTo("newpath")); }); } [Test] public void HasChildren_TypeMappingOptionsAreApplied() { CheckHowChangeInTypeRuleAffectsFilter<TestEntityBase, string>( x => x.HasChildren(y => y.Children, y => y.Parent, y => { Console.WriteLine(y.GetType()); return y.Named("SuperChild"); }), (y, t) => y.GetTypeMappedName(typeof(ChildEntity)), "ChildEntity", "SuperChild"); } [Test] public void Include_non_existant_property_makes_GetAllPropertiesOfType_return_a_new_virtual_property() { CheckHowChangeInTypeRuleAffectsFilter<Top, bool>(x => x.Include<int>("Virtual", o => o.OnGet(y => 1234)), (x, t) => x.GetAllPropertiesOfType(t, default(BindingFlags)).Any( y => y.Name == "Virtual"), false, true); } [Test] public void Named_OverridesDefaultNameOfType() { CheckHowChangeInTypeRuleAffectsFilter<Top, string>(x => x.Named("HolaHola"), (x, t) => x.GetTypeMappedName(t), "Top", "HolaHola"); } [Test] public void OnDeserializedRule_IsAppliedToMappingFilter() { var fluentMappingFilter = GetMappingFilter(); var onDeserializedHook = fluentMappingFilter.GetOnDeserializedHook(typeof(Top)); Assert.That(onDeserializedHook, Is.Not.Null); var top = new Top(); onDeserializedHook(top); Assert.That(top.DeserializeHookWasRun, Is.True); } [Test] public void RuleForBaseClass_IsAlsoAppliedToInheritedClass() { var fluentMappingFilter = GetMappingFilter(); var propertyInfo = GetPropInfo<Specialized>(x => x.ToBeRenamed); Assert.That( fluentMappingFilter.GetPropertyMappedName(propertyInfo.ReflectedType, propertyInfo), Is.EqualTo("NewName")); } [Category("TODO")] [Test] public void Stuff_Not_Yet_Covered_By_Tests() { Assert.Fail("TODO: Test that default inclusion mode works."); Assert.Fail( "TODO: Test that explicit inclusion mode throws exception if not all properties are accounted for."); } [Test] public void WithPluralName_OverridesDefaultNameOfType() { CheckHowChangeInTypeRuleAffectsFilter<Top, string>(x => x.WithPluralName("HolaHolas"), (x, t) => x.GetPluralNameForType(t), "Tops", "HolaHolas"); } } }
using System; using System.Diagnostics; using System.Xml; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; using System.IO; using System.Collections; namespace Netron.Lithium { /// <summary> /// Netron's 'Lithium' tree control /// </summary> public class LithiumControl : ScrollableControl { #region Events /// <summary> /// notifies the host to show the properties usually in the property grid /// </summary> public event ShowProps OnShowProps; /// <summary> /// occurs when a new node is added to the diagram /// </summary> public event ShapeData OnNewNode; /// <summary> /// occurs when certain objects send info out /// </summary> public event Messager OnInfo; /// <summary> /// occurs when a shape is deleted /// </summary> public event ShapeData OnDeleteNode; #endregion #region Fields /// <summary> /// the current layout direction /// </summary> protected TreeDirection layoutDirection = TreeDirection.Vertical; /// <summary> /// the space between the nodes /// </summary> protected int wordSpacing = 20; /// <summary> /// the height between branches /// </summary> protected int branchHeight = 60; /// <summary> /// whether the tree layout algorithm will do its work by default /// </summary> protected bool layoutEnabled = true; /// <summary> /// the default name when the root is added /// </summary> protected readonly string defaultRootName = "Root"; /// <summary> /// the abstract representation of the graph /// </summary> protected internal GraphAbstract graphAbstract; /// <summary> /// the entity hovered by the mouse /// </summary> protected Entity hoveredEntity; /// <summary> /// the unique entity currently selected /// </summary> protected Entity selectedEntity; /// <summary> /// whether we are tracking, i.e. moving something around /// </summary> protected bool tracking = false; /// <summary> /// just a reference point for the OnMouseDown event /// </summary> protected Point refp; /// <summary> /// the context menu of the control /// </summary> protected ContextMenu menu; /// <summary> /// A simple, general purpose random generator /// </summary> protected Random rnd; /// <summary> /// simple proxy for the propsgrid of the control /// </summary> protected Proxy proxy; /// <summary> /// whether the diagram is moved globally /// </summary> protected bool globalMove = false; /// <summary> /// just the default gridsize used in the paint-background method /// </summary> protected Size gridSize = new Size(10,10); /// <summary> /// the new but volatile connection /// </summary> protected internal Connection neoCon = null; /// <summary> /// memory of a connection if the volatile does not end up to a solid connection /// </summary> protected ShapeBase memChild = null, memParent = null; /// <summary> /// the type of connection /// </summary> protected ConnectionType connectionType = ConnectionType.Default; #endregion #region Properties /// <summary> /// Gets or sets the type of connection drawn /// </summary> public ConnectionType ConnectionType { get{return connectionType;} set{connectionType = value; Invalidate(); } } /// <summary> /// Gets or sets the direction the tree-layout expands the tree /// </summary> public TreeDirection LayoutDirection { get{return layoutDirection;} set{layoutDirection = value; //update in case it has changed switch(value) { case TreeDirection.Horizontal: branchHeight = 120; wordSpacing = 20; break; case TreeDirection.Vertical: branchHeight = 70; wordSpacing = 20; break; } DrawTree(); } } /// <summary> /// Gets or sets whether the tree layout algorithm will do its work by default /// </summary> public bool LayoutEnabled { get{return layoutEnabled ;} set{ layoutEnabled = value; if(value) //if set to true, let's rectify what eventually has been distorted by the user DrawTree(); } } /// <summary> /// Gets or sets the shape collection /// </summary> [Browsable(false)] public ShapeCollection Shapes { get{return graphAbstract.Shapes;} set{graphAbstract.Shapes = value;} } /// <summary> /// Gets or sets the connection collection /// </summary> [Browsable(false)] public ConnectionCollection Connections { get{return graphAbstract.Connections;} set{graphAbstract.Connections = value;} } /// <summary> /// Gets the root of the diagram /// </summary> [Browsable(false)] public ShapeBase Root { get{return graphAbstract.Root;} } /// <summary> /// Gets or sets the height between the tree branches /// </summary> [Browsable(true)] public int BranchHeight { get{return branchHeight;} set{ branchHeight = value; DrawTree(); } } /// <summary> /// Gets or sets the spacing between the nodes /// </summary> [Browsable(true)] public int WordSpacing { get{return wordSpacing;} set { wordSpacing = value; DrawTree(); } } #endregion #region Constructor /// <summary> /// Default ctor /// </summary> public LithiumControl() { //double-buffering SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.ResizeRedraw, true); //init the abstract graphAbstract = new GraphAbstract(); graphAbstract.Shapes.OnShapeAdded+=new ShapeData(OnShapeAdded); AddRoot(defaultRootName); //default menu, can be overwritten in the design of the application menu = new ContextMenu(); BuildMenu(); this.ContextMenu = menu; //init the randomizer rnd = new Random(); //init the proxy proxy = new Proxy(this); //allow scrolling this.AutoScroll=true; this.HScroll=true; this.VScroll=true; } #endregion #region Methods private void visitor_OnDelete(ShapeBase shape) { if(OnDeleteNode!=null) OnDeleteNode(shape); } /// <summary> /// Passes the event from the abstracts shape collection to the outside. /// Having the event in the GraphAbstract being raised centralizes it, /// otherwise the event should be raise in various places /// </summary> /// <param name="shape"></param> private void OnShapeAdded(ShapeBase shape) { if(this.OnNewNode!=null) OnNewNode(shape); } /// <summary> /// Builds the context menu /// </summary> private void BuildMenu() { MenuItem mnuDelete = new MenuItem("Delete",new EventHandler(OnDelete)); menu.MenuItems.Add(mnuDelete); MenuItem mnuProps = new MenuItem("Properties", new EventHandler(OnProps)); menu.MenuItems.Add(mnuProps); MenuItem mnuDash = new MenuItem("-"); menu.MenuItems.Add(mnuDash); MenuItem mnuShapes = new MenuItem("Change to"); menu.MenuItems.Add(mnuShapes); MenuItem mnuRecShape = new MenuItem("Rectangular shape", new EventHandler(OnRecShape)); mnuShapes.MenuItems.Add(mnuRecShape); MenuItem mnuOvalShape = new MenuItem("Oval shape", new EventHandler(OnOvalShape)); mnuShapes.MenuItems.Add(mnuOvalShape); MenuItem mnuDash2 = new MenuItem("-"); menu.MenuItems.Add(mnuDash2); MenuItem mnuTLShape = new MenuItem("Add Text label", new EventHandler(OnTextLabelShape)); menu.MenuItems.Add(mnuTLShape); } #region Menu handlers /// <summary> /// Deletes the currently selected object from the canvas /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnDelete(object sender, EventArgs e) { if(selectedEntity!=null) { if(typeof(ShapeBase).IsInstanceOfType(selectedEntity)) { this.Shapes.Remove(selectedEntity as ShapeBase); this.Invalidate(); } else if(typeof(Connection).IsInstanceOfType(selectedEntity)) { this.Connections.Remove(selectedEntity as Connection); this.Invalidate(); } } } /// <summary> /// Asks the host to show the props /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnProps(object sender, EventArgs e) { object thing; if(this.selectedEntity==null) thing = this.proxy; else thing =selectedEntity; if(this.OnShowProps!=null) OnShowProps(thing); } private void OnRecShape(object sender, EventArgs e) { throw new NotImplementedException("Sorry, not implemented yet"); } private void OnOvalShape(object sender, EventArgs e) { throw new NotImplementedException("Sorry, not implemented yet"); } private void OnTextLabelShape(object sender, EventArgs e) { AddShape(ShapeTypes.TextLabel,refp); } #endregion /// <summary> /// Paints the control /// </summary> /// <remarks> /// If you switch the painting order of Connections and shapes the connection line /// will be underneath/above the shape /// </remarks> /// <param name="e"></param> protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; //use the best quality, with a performance penalty g.SmoothingMode= System.Drawing.Drawing2D.SmoothingMode.AntiAlias; int scrollPositionX = this.AutoScrollPosition.X; int scrollPositionY = this.AutoScrollPosition.Y; g.TranslateTransform(scrollPositionX, scrollPositionY); //zoom //g.ScaleTransform(0.1f,0.1f); //draw the Connections for(int k=0; k<Connections.Count; k++) { Connections[k].Paint(g); } if(neoCon!=null) neoCon.Paint(g); //loop over the shapes and draw for(int k=0; k<Shapes.Count; k++) { if(Shapes[k].visible) Shapes[k].Paint(g); } } /// <summary> /// Paints the background /// </summary> /// <param name="e"></param> protected override void OnPaintBackground(PaintEventArgs e) { base.OnPaintBackground (e); // Graphics g = e.Graphics; // // g.DrawString("Lithium Tree Layout Control [version " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + "]",Font,Brushes.SlateGray,new Point(20,10)); // g.DrawString("<Shift>: move the diagram",Font,Brushes.SlateGray,new Point(20,30)); // g.DrawString("<Ctrl>: move a node to a new parent",Font,Brushes.SlateGray,new Point(20,40)); // g.DrawString("<Alt>: add a new child node",Font,Brushes.SlateGray,new Point(20,50)); } #region Add random node /// <summary> /// Adds a random node /// </summary> public void AddRandomNode() { AddRandomNode("Random"); } /// <summary> /// Adds a random node to the diagram /// </summary> /// <param name="newName">the text of the newly added shape</param> public void AddRandomNode(string newName) { //Random rnd = new Random(); int max = Shapes.Count-1; if(max<0) return; ShapeBase shape = Shapes[rnd.Next(0,max)]; shape.AddChild(newName); DrawTree(); } #endregion #region New diagram /// <summary> /// Starts a new diagram and forgets about everything /// You need to call the Save method before this if you wish to keep the current diagram. /// </summary> /// <param name="rootName">the text of the root in the new diagram</param> public void NewDiagram(string rootName) { this.graphAbstract=new GraphAbstract(); this.AddRoot(rootName); CenterRoot(); Invalidate(); } /// <summary> /// Starts a new diagram and forgets about everything /// You need to call the Save method before this if you wish to keep the current diagram. /// </summary> public void NewDiagram() { this.graphAbstract = new GraphAbstract(); this.AddRoot(defaultRootName); CenterRoot(); Invalidate(); } #endregion /// <summary> /// Adds the root of the diagram to the canvas /// </summary> /// <param name="rootText"></param> private ShapeBase AddRoot(string rootText) { if(Shapes.Count>0) throw new Exception("You cannot set the root unless the diagram is empty"); SimpleRectangle root = new SimpleRectangle(this); root.Location = new Point(Width/2+50,Height/2+50); root.Width = 50; root.Height = 25; root.Text = rootText; root.ShapeColor = Color.SteelBlue; root.IsRoot = true; root.Font = Font; root.visible = false; root.level = 0; Fit(root); //set the root of the diagram this.graphAbstract.Root = root; Shapes.Add(root); return root; } /// <summary> /// Centers the root on the control's canvas /// </summary> public void CenterRoot() { graphAbstract.Root.rectangle.Location = new Point(Width/2,Height/2); //Invalidate(); DrawTree(); } /// <summary> /// Adds a shape to the canvas or diagram /// </summary> /// <param name="shape"></param> public ShapeBase AddShape(ShapeBase shape) { Shapes.Add(shape); shape.Site = this; this.Invalidate(); return shape; } /// <summary> /// Adds a predefined shape /// </summary> /// <param name="type"></param> /// <param name="location"></param> public ShapeBase AddShape(ShapeTypes type, Point location) { ShapeBase shape = null; switch(type) { case ShapeTypes.Rectangular: shape = new SimpleRectangle(this); break; case ShapeTypes.Oval: shape = new OvalShape(this); break; case ShapeTypes.TextLabel: shape = new TextLabel(this); shape.Location = location; shape.ShapeColor = Color.Transparent; shape.Text = "A text label (change the text in the property grid)"; shape.Width = 350; shape.Height = 30; Shapes.Add(shape); return shape; } if(shape==null) return null; shape.ShapeColor = Color.FromArgb(rnd.Next(0,255),rnd.Next(0,255),rnd.Next(0,255)); shape.Location = location; Shapes.Add(shape); return shape; } /// <summary> /// Move with the given vector /// </summary> /// <param name="p"></param> public void MoveDiagram(Point p) { //move the whole diagram foreach(ShapeBase shape in Shapes) { shape.Move(p); Invalidate(); } return; } #region Mouse event handlers /// <summary> /// Handles the mouse-down event /// </summary> /// <param name="e"></param> protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown (e); Point p = new Point(e.X - this.AutoScrollPosition.X, e.Y - this.AutoScrollPosition.Y); Rectangle r; #region SHIFT // if(Control.ModifierKeys==Keys.Shift) // { // globalMove = true; // refp = p; //useful for all kind of things // return; // } #endregion ShapeBase sh ; #region LMB & RMB //test for shapes for(int k=0; k<Shapes.Count; k++) { sh = Shapes[k]; if(sh.childNodes.Count>0)//has a [+/-] { if(layoutDirection==TreeDirection.Vertical) r = new Rectangle(sh.Left + sh.Width/2 - 5, sh.Bottom, 10, 10); else r = new Rectangle(sh.Right, sh.Y + sh.Height/2-5, 10, 10); if(r.Contains(p)) { if(sh.expanded) sh.Collapse(true); else sh.Expand(); DrawTree(); } } if(Shapes[k].Hit(p)) { //shapes[k].ShapeColor = Color.WhiteSmoke; if(selectedEntity!=null) selectedEntity.IsSelected=false; selectedEntity = Shapes[k]; selectedEntity.IsSelected = true; sh = selectedEntity as ShapeBase; #region CONTROL // if(Control.ModifierKeys==Keys.Control && !sh.IsRoot) // { // tracking = true; // //remove from parent // sh.parentNode.childNodes.Remove(sh); // Connections.Remove(sh, sh.parentNode); // //...but keep the reference in case the user didn't find a new location // memChild = sh; // memParent = sh.parentNode; // //now remove the reference // sh.parentNode = null; // } #endregion //set the point for the next round refp=p; #region Double-click if(e.Button==MouseButtons.Left && e.Clicks==2) { if(sh.expanded) sh.Collapse(true); else sh.Expand(); DrawTree(); } #endregion #region ALT // if(Control.ModifierKeys==Keys.Alt) // { // sh.AddChild("New"); // DrawTree(); // } #endregion if(OnShowProps!=null) OnShowProps(Shapes[k]); return; } } if(selectedEntity!=null) selectedEntity.IsSelected=false; selectedEntity = null; Invalidate(); refp = p; //useful for all kind of things //nothing was selected but we'll show the props of the control in this case if(OnShowProps!=null) OnShowProps(this.proxy); #endregion } /// <summary> /// Handles the mouse-move event /// </summary> /// <param name="e"></param> protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove (e); Point p = new Point(e.X - this.AutoScrollPosition.X, e.Y - this.AutoScrollPosition.Y); //move the whole diagram if(globalMove) { foreach(ShapeBase shape in Shapes) { shape.Move(new Point(p.X-refp.X,p.Y-refp.Y)); Invalidate(); } refp=p; return; } //move just one and its kids if(tracking) { ShapeBase sh = selectedEntity as ShapeBase; ResetPickup(); //forget about what happened before Pickup(sh); //pickup the shape hanging underneath the shape to move next foreach(ShapeBase shape in Shapes) { if(!shape.pickup) continue; shape.Move(new Point(p.X-refp.X,p.Y-refp.Y)); Invalidate(); } refp=p; //try to find the new parent SeekNewParent(sh); Invalidate(); return; } //hovering stuff for(int k=0; k<Shapes.Count; k++) { if(Shapes[k].Hit(p)) { if(hoveredEntity!=null) hoveredEntity.hovered = false; Shapes[k].hovered = true; hoveredEntity = Shapes[k]; //hoveredEntity.Invalidate(); Invalidate(); return; } } for(int k=0; k<Connections.Count; k++) { if(Connections[k].Hit(p)) { if(hoveredEntity!=null) hoveredEntity.hovered = false; Connections[k].hovered = true; hoveredEntity = Connections[k]; hoveredEntity.Invalidate(); Invalidate(); return; } } //reset the whole process if nothing happened above HoverNone(); Invalidate(); } /// <summary> /// Handles the mouse-up event /// </summary> /// <param name="e"></param> protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp (e); globalMove = false; Connection con = null; //test if we connected a connection if(tracking) { tracking = false; //make the volatile solid if(neoCon!=null) { con = new Connection(neoCon.To, neoCon.From); con.site = this; Connections.Add(con); //the From is the shape seeking a parent neoCon.To.childNodes.Add(neoCon.From); neoCon.From.parentNode = neoCon.To; con.visible = true; neoCon.To.Expand(); neoCon.From.connection = con; } else //the user hasn't released near anything, so reset to the original situation { con = new Connection(memChild, memParent); con.site = this; Connections.Add(con); memParent.childNodes.Add(memChild); memChild.parentNode = memParent; con.visible = true; memChild.connection = con; } //either case, restart the process next neoCon = null; memChild = null; memParent = null; DrawTree(); } } /// <summary> /// Find a new parent for the given shape. This creates a new volatile connection which will be solidified /// in the MouseUp handler. /// </summary> /// <param name="shape">the shape being moved around by the user</param> private void SeekNewParent(ShapeBase shape) { /* this is the fast way but gives problems when the shape is surrounded by other shapes * which makes it difficult to attach it to one you want for(int k=0;k<Shapes.Count; k++) { if(Shapes[k]!=shape && Environment(Shapes[k],shape) && Shapes[k].parentNode!=shape && !Shapes[k].pickup) { neoCon = new Connection(shape, Shapes[k], Color.Red,2f); neoCon.visible = true; Invalidate(); return; } } */ double best = 10000d; int chosen = -1; double dist; ShapeBase other; for(int k=0;k<Shapes.Count; k++) { other = Shapes[k]; if(other!=shape && other.visible && other.parentNode!=shape && !other.pickup) { dist = Math.Sqrt((other.X-shape.X)*(other.X-shape.X)+(other.Y-shape.Y)*(other.Y-shape.Y)); if(dist<best && dist< 120) chosen = k; } } if(chosen>-1) { neoCon = new Connection(shape, Shapes[chosen], Color.Red,2f); neoCon.visible = true; neoCon.site = this; return; } neoCon = null; } private bool Environment(ShapeBase shape1, ShapeBase shape2) { return Math.Sqrt((shape1.X-shape2.X)*(shape1.X-shape2.X)+(shape1.Y-shape2.Y)*(shape1.Y-shape2.Y))<100; } private void ResetPickup() { for(int k=0; k<Shapes.Count; k++) Shapes[k].pickup = false; } private void Pickup(ShapeBase shape) { shape.pickup=true; for(int k =0; k< shape.childNodes.Count; k++) { shape.childNodes[k].pickup = true; if(shape.childNodes[k].childNodes.Count>0) Pickup(shape.childNodes[k]); } } #endregion /// <summary> /// Resets the hovering status of the control, i.e. the hoverEntity is set to null. /// </summary> private void HoverNone() { if(hoveredEntity!=null) { hoveredEntity.hovered = false; hoveredEntity.Invalidate(); } hoveredEntity = null; } /// <summary> /// Collapses the whole diagram /// </summary> public void CollapseAll() { this.Root.Collapse(true); } /// <summary> /// Deletes the currently selected shape /// </summary> public void Delete() { if(selectedEntity==null) return; ShapeBase sh = selectedEntity as ShapeBase; if(sh!=null) { if(sh.IsRoot) return; //cannot delete the root //delete the node from the parent's children sh.parentNode.childNodes.Remove(sh); //delete everything underneath the node DeleteVisitor visitor = new DeleteVisitor(this.graphAbstract); visitor.OnDelete+=new ShapeData(visitor_OnDelete); graphAbstract.DepthFirstTraversal(visitor,sh); DrawTree(); } //Invalidate(); } /// <summary> /// Expands the whole diagram /// </summary> public void ExpandAll() { IVisitor expander = new ExpanderVisitor(); this.graphAbstract.DepthFirstTraversal(expander); DrawTree(); } /// <summary> /// Saves the diagram to file in XML format (XML serialization) /// </summary> /// <param name="filePath"></param> public void SaveGraphAs(string filePath) { XmlTextWriter tw = new XmlTextWriter(filePath,System.Text.Encoding.Unicode); GraphSerializer g = new GraphSerializer(this); g.Serialize(tw); tw.Close(); } /// <summary> /// Opens a diagram which was saved to XML previously (XML deserialization) /// </summary> /// <param name="filePath"></param> public void OpenGraph(string filePath) { XmlTextReader reader = new XmlTextReader(filePath); GraphSerializer ser = new GraphSerializer(this); graphAbstract = ser.Deserialize(reader) as GraphAbstract; reader.Close(); DrawTree(); Invalidate(); } #region Layout algorithm int marginLeft = 10; /// <summary> /// Generic entry point to layout the diagram on the canvas. /// The default LayoutDirection is vertical. If you wish to layout the tree in a certain /// direction you need to specify this property first. Also, the direction is global, you cannot have /// different parts being drawn in different ways though it can be implemented. /// /// </summary> public void DrawTree() { if(!layoutEnabled || graphAbstract.Root == null) return; Point p = Point.Empty; //the shift vector difference between the original and the moved root try { //start the recursion //the layout will move the root but it's reset to its original position switch(layoutDirection) { case TreeDirection.Vertical: p = new Point(graphAbstract.Root.X, graphAbstract.Root.Y); VerticalDrawTree(graphAbstract.Root,false,marginLeft,this.graphAbstract.Root.Y); p = new Point(-graphAbstract.Root.X+p.X, -graphAbstract.Root.Y+ p.Y); MoveDiagram(p); break; case TreeDirection.Horizontal: p = new Point(graphAbstract.Root.X, graphAbstract.Root.Y); HorizontalDrawTree(graphAbstract.Root,false,marginLeft,10); p = new Point(-graphAbstract.Root.X+p.X, -graphAbstract.Root.Y+ p.Y); MoveDiagram(p); break; } int maxY = 0; foreach (ShapeBase shape in Shapes) { if (shape.ShapeColor == Color.Ivory) { if (shape.Visible) { if (shape.Y > maxY) { maxY = shape.Y; } } } } foreach (ShapeBase shape in Shapes) { if (shape.ShapeColor == Color.Ivory) { if (shape.Visible) { shape.Move(new Point(0, maxY - shape.Y)); } } } CalculateScrollBars(); Invalidate(); } catch(Exception exc) { Trace.WriteLine(exc.Message); } } private void CalculateScrollBars() { Point minPoint = new Point(int.MaxValue,int.MaxValue); Size maxSize = new Size(0,0); foreach(ShapeBase shape in Shapes) { if (shape.Visible) { if (shape.X + shape.Width > maxSize.Width) { maxSize.Width = shape.X + shape.Width; } if (shape.Y + shape.Height > maxSize.Height) { maxSize.Height = shape.Y + shape.Height; } if (shape.X < minPoint.X) { minPoint.X = shape.X; } if (shape.Y < minPoint.Y) { minPoint.Y = shape.Y; } } } MoveDiagram(new Point(50 - minPoint.X, 50 - minPoint.Y)); maxSize.Width = maxSize.Width - minPoint.X + 100; maxSize.Height = maxSize.Height - minPoint.Y + 100; this.AutoScrollMinSize = maxSize; } /// <summary> /// Positions everything underneath the node and returns the total width of the kids /// </summary> /// <param name="containerNode"></param> /// <param name="first"></param> /// <param name="shiftLeft"></param> /// <param name="shiftTop"></param> /// <returns></returns> private int VerticalDrawTree(ShapeBase containerNode, bool first, int shiftLeft, int shiftTop) { bool isFirst = false; bool isParent = containerNode.childNodes.Count>0? true: false; int childrenWidth = 0; int thisX, thisY; int returned = 0; int verticalDelta = branchHeight ; //the applied vertical shift of the child depends on the Height of the containerNode #region Children width for(int i =0; i<containerNode.childNodes.Count; i++) { //determine the width of the label if(i==0) isFirst = true; else isFirst = false; if(containerNode.childNodes[i].visible) { if((branchHeight - containerNode.Height) < 30) //if too close to the child, shift it with 40 units verticalDelta = containerNode.Height + 40; returned = VerticalDrawTree(containerNode.childNodes[i], isFirst, shiftLeft + childrenWidth, shiftTop + verticalDelta ); childrenWidth += returned; } } if(childrenWidth>0 && containerNode.expanded) childrenWidth=Math.Max(Convert.ToInt32(childrenWidth + (containerNode.Width-childrenWidth)/2), childrenWidth); //in case the length of the containerNode is bigger than the total length of the children #endregion if(childrenWidth==0) //there are no children; this is the branch end childrenWidth = containerNode.Width+wordSpacing; #region Positioning thisY = shiftTop; if(containerNode.childNodes.Count>0 && containerNode.expanded) { if(containerNode.childNodes.Count==1) { thisX = Convert.ToInt32(containerNode.childNodes[0].X+containerNode.childNodes[0].Width/2 - containerNode.Width/2); } else { float firstChild = containerNode.childNodes[0].Left+ containerNode.childNodes[0].Width/2; float lastChild = containerNode.childNodes[containerNode.childNodes.Count-1].Left + containerNode.childNodes[containerNode.childNodes.Count-1].Width/2; //the following max in case the containerNode is larger than the childrenWidth thisX = Convert.ToInt32(Math.Max(firstChild + (lastChild -firstChild - containerNode.Width)/2, firstChild)); } } else { thisX = shiftLeft; } containerNode.rectangle.X = thisX; containerNode.rectangle.Y = thisY; #endregion return childrenWidth; } /// <summary> /// Horizontal layout algorithm /// </summary> /// <param name="containerNode"></param> /// <param name="first"></param> /// <param name="shiftLeft"></param> /// <param name="shiftTop"></param> /// <returns></returns> private int HorizontalDrawTree(ShapeBase containerNode, bool first, int shiftLeft, int shiftTop) { bool isFirst = false; bool isParent = containerNode.childNodes.Count>0? true: false; int childrenHeight = 0; int thisX, thisY; int returned = 0; int horizontalDelta = branchHeight; #region Children width for(int i =0; i<containerNode.childNodes.Count; i++) { //determine the width of the label if(i==0) isFirst = true; else isFirst = false; if(containerNode.childNodes[i].visible) { if((branchHeight - containerNode.Width) < 30) //if too close to the child, shift it with 40 units horizontalDelta = containerNode.Width + 40; returned = HorizontalDrawTree(containerNode.childNodes[i], isFirst, shiftLeft + horizontalDelta , shiftTop + childrenHeight ); childrenHeight += returned; } } #endregion if(childrenHeight==0) //there are no children; this is the branch end childrenHeight = containerNode.Height+wordSpacing; #region Positioning thisX = shiftLeft; if(containerNode.childNodes.Count>0 && containerNode.expanded) { int firstChild = containerNode.childNodes[0].Y; int lastChild = containerNode.childNodes[containerNode.childNodes.Count-1].Y; thisY = Convert.ToInt32(firstChild + (lastChild - firstChild)/2); } else { thisY = Convert.ToInt32(shiftTop); } containerNode.rectangle.X = thisX; containerNode.rectangle.Y = thisY; #endregion return childrenHeight; } private int Measure(string text) { Graphics g = Graphics.FromHwnd(this.Handle); return Size.Round(g.MeasureString(text,Font)).Width +37; } /// <summary> /// Resizes the shape to fit the text /// </summary> /// <param name="shape"></param> public void Fit(ShapeBase shape) { Graphics g = Graphics.FromHwnd(this.Handle); Size s = Size.Round(g.MeasureString(shape.Text,Font)); shape.Width =s.Width +20; shape.Height = s.Height+8; } private void FitAll() { foreach(ShapeBase shape in graphAbstract.Shapes) Fit(shape); Invalidate(); } /// <summary> /// When the font of the control is changed all shapes get /// the new font assigned /// </summary> /// <param name="e"></param> protected override void OnFontChanged(EventArgs e) { base.OnFontChanged (e); foreach(ShapeBase shape in graphAbstract.Shapes) shape.Font = Font; } /// <summary> /// Adds a child node to the currently selected one /// </summary> public void AddChild() { if(selectedEntity==null) return; ShapeBase sh = selectedEntity as ShapeBase; if(sh!=null) { sh.AddChild("New node"); DrawTree(); } } /// <summary> /// DFT of the diagram with the given visitor, starting from the given shape /// </summary> /// <param name="visitor"></param> /// <param name="shape"></param> public void DepthFirstTraversal(IVisitor visitor, ShapeBase shape) { graphAbstract.DepthFirstTraversal(visitor, shape); } /// <summary> /// DFT of the diagram with the given visitor, starting from the root /// </summary> /// <param name="visitor"></param> public void DepthFirstTraversal(IVisitor visitor) { graphAbstract.DepthFirstTraversal(visitor); } /// <summary> /// BFT of the diagram with the given visitor, starting from the root /// </summary> /// <param name="visitor"></param> public void BreadthFirstTraversal(IVisitor visitor) { graphAbstract.BreadthFirstTraversal(visitor); } /// <summary> /// BFT of the diagram with the given visitor, starting from the given shape /// </summary> /// <param name="visitor"></param> /// <param name="shape"></param> public void BreadthFirstTraversal(IVisitor visitor, ShapeBase shape) { graphAbstract.BreadthFirstTraversal(visitor, shape); } #endregion #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace FWWebService.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MGTK.EventArguments; using MGTK.Services; namespace MGTK.Controls { public class TextBox : Control { protected Scrollbar horizontalScrollbar; protected Scrollbar verticalScrollbar; protected InnerTextBox innerTextBox; private bool useVerticalScrollBar = true, useHorizontalScrollBar = true; public int CursorX { get { return innerTextBox.CursorX; } set { innerTextBox.CursorX = value; } } public int CursorY { get { return innerTextBox.CursorY; } set { innerTextBox.CursorY = value; } } public bool UseVerticalScrollBar { get { if (!MultiLine) return false; return useVerticalScrollBar; } set { useVerticalScrollBar = value; ConfigureCoordinatesAndSizes(); } } public bool UseHorizontalScrollBar { get { if (!MultiLine) return false; return useHorizontalScrollBar; } set { useHorizontalScrollBar = value; ConfigureCoordinatesAndSizes(); } } public bool MultiLine { get { return innerTextBox.MultiLine; } set { innerTextBox.MultiLine = value; } } public new string Text { get { return innerTextBox.Text; } set { innerTextBox.Text = value; } } public new event EventHandler TextChanged; public event TextChangingEventHandler TextChanging; public TextBox(Form formowner) : base(formowner) { horizontalScrollbar = new Scrollbar(formowner) { Type = ScrollBarType.Horizontal }; verticalScrollbar = new Scrollbar(formowner) { Type = ScrollBarType.Vertical }; innerTextBox = new InnerTextBox(formowner); horizontalScrollbar.Parent = verticalScrollbar.Parent = innerTextBox.Parent = this; horizontalScrollbar.IndexChanged += new EventHandler(horizontalScrollbar_IndexChanged); verticalScrollbar.IndexChanged += new EventHandler(verticalScrollbar_IndexChanged); innerTextBox.TextChanged += new EventHandler(innerTextBox_TextChanged); innerTextBox.ScrollChanged += new EventHandler(innerTextBox_ScrollChanged); innerTextBox.TextChanging += new TextChangingEventHandler(innerTextBox_TextChanging); this.Controls.Add(innerTextBox); this.Controls.Add(horizontalScrollbar); this.Controls.Add(verticalScrollbar); this.Init += new EventHandler(TextBox_Init); this.TextChanged += new EventHandler(TextBox_TextChanged); this.WidthChanged += new EventHandler(TextBox_SizeChanged); this.HeightChanged += new EventHandler(TextBox_SizeChanged); } void innerTextBox_TextChanging(object sender, TextChangingEventArgs e) { if (TextChanging != null) TextChanging(this, e); } void TextBox_SizeChanged(object sender, EventArgs e) { ConfigureInternalTextCounters(); } void innerTextBox_ScrollChanged(object sender, EventArgs e) { horizontalScrollbar.Index = innerTextBox.ScrollX; verticalScrollbar.Index = innerTextBox.ScrollY; } void innerTextBox_TextChanged(object sender, EventArgs e) { if (Initialized) ConfigureInternalTextCounters(); } void TextBox_TextChanged(object sender, EventArgs e) { if (TextChanged != null) TextChanged(this, new EventArgs()); } void TextBox_Init(object sender, EventArgs e) { ConfigureCoordinatesAndSizes(); } public override void Draw() { DrawingService.DrawFrame(spriteBatch, Theme.TextBoxFrame, OwnerX + X, OwnerY + Y, Width, Height, Z - 0.001f); horizontalScrollbar.Z = verticalScrollbar.Z = Z - 0.0015f; innerTextBox.Z = Z - 0.001f; base.Draw(); } private void ConfigureInternalTextCounters() { verticalScrollbar.NrItemsPerPage = innerTextBox.NrItemsVisible; verticalScrollbar.TotalNrItems = innerTextBox.NrLines; if (innerTextBox.internalText != null && innerTextBox.internalText.Count > 0) { horizontalScrollbar.TotalNrItems = 0; horizontalScrollbar.NrItemsPerPage = 0; for (int i = 0; i < innerTextBox.internalText.Count; i++) { if (innerTextBox.internalText[i].Text.Length > horizontalScrollbar.TotalNrItems) horizontalScrollbar.TotalNrItems = innerTextBox.internalText[i].Text.Length; if (innerTextBox.internalText[i].NrCharsVisible > horizontalScrollbar.NrItemsPerPage) horizontalScrollbar.NrItemsPerPage = innerTextBox.internalText[i].NrCharsVisible; } } } private void ConfigureCoordinatesAndSizes() { innerTextBox.X = 2; innerTextBox.Y = 2; innerTextBox.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom; verticalScrollbar.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right; verticalScrollbar.X = Width - 16 - 2; verticalScrollbar.Y = 2; verticalScrollbar.Width = 16; verticalScrollbar.Height = Height - 4; horizontalScrollbar.X = 2; horizontalScrollbar.Y = Height - 16 - 2; horizontalScrollbar.Width = Width - 4; horizontalScrollbar.Height = 16; horizontalScrollbar.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom; if (UseVerticalScrollBar) innerTextBox.Width = Width - verticalScrollbar.Width - 4 - 1; else innerTextBox.Width = Width - 4; if (UseHorizontalScrollBar) innerTextBox.Height = Height - horizontalScrollbar.Height - 4 - 1; else innerTextBox.Height = Height - 4; if (UseVerticalScrollBar && UseHorizontalScrollBar) { horizontalScrollbar.Width -= 16; verticalScrollbar.Height -= 16; } horizontalScrollbar.Visible = UseHorizontalScrollBar; verticalScrollbar.Visible = UseVerticalScrollBar; ConfigureInternalTextCounters(); } void verticalScrollbar_IndexChanged(object sender, EventArgs e) { innerTextBox.ScrollY = verticalScrollbar.Index; } void horizontalScrollbar_IndexChanged(object sender, EventArgs e) { innerTextBox.ScrollX = horizontalScrollbar.Index; } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Transactions { public sealed partial class CommittableTransaction : System.Transactions.Transaction, System.IAsyncResult { public CommittableTransaction() { } public CommittableTransaction(System.TimeSpan timeout) { } public CommittableTransaction(System.Transactions.TransactionOptions options) { } object System.IAsyncResult.AsyncState { get { throw null; } } System.Threading.WaitHandle System.IAsyncResult.AsyncWaitHandle { get { throw null; } } bool System.IAsyncResult.CompletedSynchronously { get { throw null; } } bool System.IAsyncResult.IsCompleted { get { throw null; } } public System.IAsyncResult BeginCommit(System.AsyncCallback asyncCallback, object asyncState) { throw null; } public void Commit() { } public void EndCommit(System.IAsyncResult asyncResult) { } } public enum DependentCloneOption { BlockCommitUntilComplete = 0, RollbackIfNotComplete = 1, } public sealed partial class DependentTransaction : System.Transactions.Transaction { internal DependentTransaction() { } public void Complete() { } } public partial class Enlistment { internal Enlistment() { } public void Done() { } } [System.FlagsAttribute] public enum EnlistmentOptions { EnlistDuringPrepareRequired = 1, None = 0, } public enum EnterpriseServicesInteropOption { Automatic = 1, Full = 2, None = 0, } public delegate System.Transactions.Transaction HostCurrentTransactionCallback(); public partial interface IDtcTransaction { void Abort(System.IntPtr reason, int retaining, int async); void Commit(int retaining, int commitType, int reserved); void GetTransactionInfo(System.IntPtr transactionInformation); } public partial interface IEnlistmentNotification { void Commit(System.Transactions.Enlistment enlistment); void InDoubt(System.Transactions.Enlistment enlistment); void Prepare(System.Transactions.PreparingEnlistment preparingEnlistment); void Rollback(System.Transactions.Enlistment enlistment); } public partial interface IPromotableSinglePhaseNotification : System.Transactions.ITransactionPromoter { void Initialize(); void Rollback(System.Transactions.SinglePhaseEnlistment singlePhaseEnlistment); void SinglePhaseCommit(System.Transactions.SinglePhaseEnlistment singlePhaseEnlistment); } public partial interface ISimpleTransactionSuperior : System.Transactions.ITransactionPromoter { void Rollback(); } public partial interface ISinglePhaseNotification : System.Transactions.IEnlistmentNotification { void SinglePhaseCommit(System.Transactions.SinglePhaseEnlistment singlePhaseEnlistment); } public enum IsolationLevel { Chaos = 5, ReadCommitted = 2, ReadUncommitted = 3, RepeatableRead = 1, Serializable = 0, Snapshot = 4, Unspecified = 6, } public partial interface ITransactionPromoter { byte[] Promote(); } public partial class PreparingEnlistment : System.Transactions.Enlistment { internal PreparingEnlistment() { } public void ForceRollback() { } public void ForceRollback(System.Exception e) { } public void Prepared() { } public byte[] RecoveryInformation() { throw null; } } public partial class SinglePhaseEnlistment : System.Transactions.Enlistment { internal SinglePhaseEnlistment() { } public void Aborted() { } public void Aborted(System.Exception e) { } public void Committed() { } public void InDoubt() { } public void InDoubt(System.Exception e) { } } public sealed partial class SubordinateTransaction : System.Transactions.Transaction { public SubordinateTransaction(System.Transactions.IsolationLevel isoLevel, System.Transactions.ISimpleTransactionSuperior superior) { } } public partial class Transaction : System.IDisposable, System.Runtime.Serialization.ISerializable { internal Transaction() { } public static System.Transactions.Transaction Current { get { throw null; } set { } } public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } } public System.Guid PromoterType { get { throw null; } } public System.Transactions.TransactionInformation TransactionInformation { get { throw null; } } public event System.Transactions.TransactionCompletedEventHandler TransactionCompleted { add { } remove { } } public System.Transactions.Transaction Clone() { throw null; } public System.Transactions.DependentTransaction DependentClone(System.Transactions.DependentCloneOption cloneOption) { throw null; } public void Dispose() { } public System.Transactions.Enlistment EnlistDurable(System.Guid resourceManagerIdentifier, System.Transactions.IEnlistmentNotification enlistmentNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { throw null; } public System.Transactions.Enlistment EnlistDurable(System.Guid resourceManagerIdentifier, System.Transactions.ISinglePhaseNotification singlePhaseNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { throw null; } public bool EnlistPromotableSinglePhase(System.Transactions.IPromotableSinglePhaseNotification promotableSinglePhaseNotification) { throw null; } public bool EnlistPromotableSinglePhase(System.Transactions.IPromotableSinglePhaseNotification promotableSinglePhaseNotification, System.Guid promoterType) { throw null; } public System.Transactions.Enlistment EnlistVolatile(System.Transactions.IEnlistmentNotification enlistmentNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { throw null; } public System.Transactions.Enlistment EnlistVolatile(System.Transactions.ISinglePhaseNotification singlePhaseNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public byte[] GetPromotedToken() { throw null; } public static bool operator ==(System.Transactions.Transaction x, System.Transactions.Transaction y) { throw null; } public static bool operator !=(System.Transactions.Transaction x, System.Transactions.Transaction y) { throw null; } public System.Transactions.Enlistment PromoteAndEnlistDurable(System.Guid resourceManagerIdentifier, System.Transactions.IPromotableSinglePhaseNotification promotableNotification, System.Transactions.ISinglePhaseNotification enlistmentNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { throw null; } public void Rollback() { } public void Rollback(System.Exception e) { } public void SetDistributedTransactionIdentifier(System.Transactions.IPromotableSinglePhaseNotification promotableNotification, System.Guid distributedTransactionIdentifier) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext context) { } } public partial class TransactionAbortedException : System.Transactions.TransactionException { public TransactionAbortedException() { } protected TransactionAbortedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TransactionAbortedException(string message) { } public TransactionAbortedException(string message, System.Exception innerException) { } } public delegate void TransactionCompletedEventHandler(object sender, System.Transactions.TransactionEventArgs e); public partial class TransactionEventArgs : System.EventArgs { public TransactionEventArgs() { } public System.Transactions.Transaction Transaction { get { throw null; } } } public partial class TransactionException : System.SystemException { public TransactionException() { } protected TransactionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TransactionException(string message) { } public TransactionException(string message, System.Exception innerException) { } } public partial class TransactionInDoubtException : System.Transactions.TransactionException { public TransactionInDoubtException() { } protected TransactionInDoubtException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TransactionInDoubtException(string message) { } public TransactionInDoubtException(string message, System.Exception innerException) { } } public partial class TransactionInformation { internal TransactionInformation() { } public System.DateTime CreationTime { get { throw null; } } public System.Guid DistributedIdentifier { get { throw null; } } public string LocalIdentifier { get { throw null; } } public System.Transactions.TransactionStatus Status { get { throw null; } } } public static partial class TransactionInterop { public static readonly System.Guid PromoterTypeDtc; public static System.Transactions.IDtcTransaction GetDtcTransaction(System.Transactions.Transaction transaction) { throw null; } public static byte[] GetExportCookie(System.Transactions.Transaction transaction, byte[] whereabouts) { throw null; } public static System.Transactions.Transaction GetTransactionFromDtcTransaction(System.Transactions.IDtcTransaction transactionNative) { throw null; } public static System.Transactions.Transaction GetTransactionFromExportCookie(byte[] cookie) { throw null; } public static System.Transactions.Transaction GetTransactionFromTransmitterPropagationToken(byte[] propagationToken) { throw null; } public static byte[] GetTransmitterPropagationToken(System.Transactions.Transaction transaction) { throw null; } public static byte[] GetWhereabouts() { throw null; } } public static partial class TransactionManager { public static System.TimeSpan DefaultTimeout { get { throw null; } } public static System.Transactions.HostCurrentTransactionCallback HostCurrentCallback { get { throw null; } set { } } public static System.TimeSpan MaximumTimeout { get { throw null; } } public static event System.Transactions.TransactionStartedEventHandler DistributedTransactionStarted { add { } remove { } } public static void RecoveryComplete(System.Guid resourceManagerIdentifier) { } public static System.Transactions.Enlistment Reenlist(System.Guid resourceManagerIdentifier, byte[] recoveryInformation, System.Transactions.IEnlistmentNotification enlistmentNotification) { throw null; } } public partial class TransactionManagerCommunicationException : System.Transactions.TransactionException { public TransactionManagerCommunicationException() { } protected TransactionManagerCommunicationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TransactionManagerCommunicationException(string message) { } public TransactionManagerCommunicationException(string message, System.Exception innerException) { } } public partial struct TransactionOptions { private int _dummyPrimitive; public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Transactions.TransactionOptions x, System.Transactions.TransactionOptions y) { throw null; } public static bool operator !=(System.Transactions.TransactionOptions x, System.Transactions.TransactionOptions y) { throw null; } } public partial class TransactionPromotionException : System.Transactions.TransactionException { public TransactionPromotionException() { } protected TransactionPromotionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TransactionPromotionException(string message) { } public TransactionPromotionException(string message, System.Exception innerException) { } } public sealed partial class TransactionScope : System.IDisposable { public TransactionScope() { } public TransactionScope(System.Transactions.Transaction transactionToUse) { } public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout) { } public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout, System.Transactions.EnterpriseServicesInteropOption interopOption) { } public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { } public TransactionScope(System.Transactions.Transaction transactionToUse, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { } public TransactionScope(System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.TimeSpan scopeTimeout) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.TimeSpan scopeTimeout, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionOptions transactionOptions) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionOptions transactionOptions, System.Transactions.EnterpriseServicesInteropOption interopOption) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionOptions transactionOptions, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { } public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { } public void Complete() { } public void Dispose() { } } public enum TransactionScopeAsyncFlowOption { Enabled = 1, Suppress = 0, } public enum TransactionScopeOption { Required = 0, RequiresNew = 1, Suppress = 2, } public delegate void TransactionStartedEventHandler(object sender, System.Transactions.TransactionEventArgs e); public enum TransactionStatus { Aborted = 2, Active = 0, Committed = 1, InDoubt = 3, } }
using System; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans; using Orleans.Runtime; using Orleans.Streams; using UnitTests.GrainInterfaces; namespace UnitTests.Grains { internal class SampleConsumerObserver<T> : IAsyncObserver<T> { private readonly SampleStreaming_ConsumerGrain hostingGrain; internal SampleConsumerObserver(SampleStreaming_ConsumerGrain hostingGrain) { this.hostingGrain = hostingGrain; } public Task OnNextAsync(T item, StreamSequenceToken token = null) { hostingGrain.logger.Info("OnNextAsync(item={0}, token={1})", item, token != null ? token.ToString() : "null"); hostingGrain.numConsumedItems++; return Task.CompletedTask; } public Task OnCompletedAsync() { hostingGrain.logger.Info("OnCompletedAsync()"); return Task.CompletedTask; } public Task OnErrorAsync(Exception ex) { hostingGrain.logger.Info("OnErrorAsync({0})", ex); return Task.CompletedTask; } } public class SampleStreaming_ProducerGrain : Grain, ISampleStreaming_ProducerGrain { private IAsyncStream<int> producer; private int numProducedItems; private IDisposable producerTimer; internal ILogger logger; internal readonly static string RequestContextKey = "RequestContextField"; internal readonly static string RequestContextValue = "JustAString"; public SampleStreaming_ProducerGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync(CancellationToken cancellationToken) { logger.Info("OnActivateAsync"); numProducedItems = 0; return Task.CompletedTask; } public Task BecomeProducer(Guid streamId, string streamNamespace, string providerToUse) { logger.Info("BecomeProducer"); IStreamProvider streamProvider = this.GetStreamProvider(providerToUse); producer = streamProvider.GetStream<int>(streamId, streamNamespace); return Task.CompletedTask; } public Task StartPeriodicProducing() { logger.Info("StartPeriodicProducing"); producerTimer = base.RegisterTimer(TimerCallback, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(10)); return Task.CompletedTask; } public Task StopPeriodicProducing() { logger.Info("StopPeriodicProducing"); producerTimer.Dispose(); producerTimer = null; return Task.CompletedTask; } public Task<int> GetNumberProduced() { logger.Info("GetNumberProduced {0}", numProducedItems); return Task.FromResult(numProducedItems); } public Task ClearNumberProduced() { numProducedItems = 0; return Task.CompletedTask; } public Task Produce() { return Fire(); } private Task TimerCallback(object state) { return producerTimer != null? Fire(): Task.CompletedTask; } private async Task Fire([CallerMemberName] string caller = null) { RequestContext.Set(RequestContextKey, RequestContextValue); await producer.OnNextAsync(numProducedItems); numProducedItems++; logger.Info("{0} (item={1})", caller, numProducedItems); } public override Task OnDeactivateAsync(DeactivationReason reason, CancellationToken cancellationToken) { logger.Info("OnDeactivateAsync"); return Task.CompletedTask; } } public class SampleStreaming_ConsumerGrain : Grain, ISampleStreaming_ConsumerGrain { private IAsyncObservable<int> consumer; internal int numConsumedItems; internal ILogger logger; private IAsyncObserver<int> consumerObserver; private StreamSubscriptionHandle<int> consumerHandle; public SampleStreaming_ConsumerGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync(CancellationToken cancellationToken) { logger.Info("OnActivateAsync"); numConsumedItems = 0; consumerHandle = null; return Task.CompletedTask; } public async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse) { logger.Info("BecomeConsumer"); consumerObserver = new SampleConsumerObserver<int>(this); IStreamProvider streamProvider = this.GetStreamProvider(providerToUse); consumer = streamProvider.GetStream<int>(streamId, streamNamespace); consumerHandle = await consumer.SubscribeAsync(consumerObserver); } public async Task StopConsuming() { logger.Info("StopConsuming"); if (consumerHandle != null) { await consumerHandle.UnsubscribeAsync(); consumerHandle = null; } } public Task<int> GetNumberConsumed() { return Task.FromResult(numConsumedItems); } public override Task OnDeactivateAsync(DeactivationReason reason, CancellationToken cancellationToken) { logger.Info("OnDeactivateAsync"); return Task.CompletedTask; } } public class SampleStreaming_InlineConsumerGrain : Grain, ISampleStreaming_InlineConsumerGrain { private IAsyncObservable<int> consumer; internal int numConsumedItems; internal ILogger logger; private StreamSubscriptionHandle<int> consumerHandle; public SampleStreaming_InlineConsumerGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync(CancellationToken cancellationToken) { logger.Info( "OnActivateAsync" ); numConsumedItems = 0; consumerHandle = null; return Task.CompletedTask; } public async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse) { logger.Info( "BecomeConsumer" ); IStreamProvider streamProvider = this.GetStreamProvider( providerToUse ); consumer = streamProvider.GetStream<int>(streamId, streamNamespace); consumerHandle = await consumer.SubscribeAsync( OnNextAsync, OnErrorAsync, OnCompletedAsync ); } public async Task StopConsuming() { logger.Info( "StopConsuming" ); if ( consumerHandle != null ) { await consumerHandle.UnsubscribeAsync(); //consumerHandle.Dispose(); consumerHandle = null; } } public Task<int> GetNumberConsumed() { return Task.FromResult( numConsumedItems ); } public Task OnNextAsync( int item, StreamSequenceToken token = null ) { logger.Info( "OnNextAsync({0}{1})", item, token != null ? token.ToString() : "null" ); numConsumedItems++; return Task.CompletedTask; } public Task OnCompletedAsync() { logger.Info( "OnCompletedAsync()" ); return Task.CompletedTask; } public Task OnErrorAsync( Exception ex ) { logger.Info( "OnErrorAsync({0})", ex ); return Task.CompletedTask; } public override Task OnDeactivateAsync(DeactivationReason reason, CancellationToken cancellationToken) { logger.Info("OnDeactivateAsync"); return Task.CompletedTask; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Common { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; #if !WINDOWS_UWP using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Transactions; using Microsoft.Win32; #endif static class Fx { // This is only used for EventLog Source therefore matching EventLog source rather than ETL source const string DefaultEventSource = "Microsoft.IotHub"; #if DEBUG const string SBRegistryKey = @"SOFTWARE\Microsoft\IotHub\v2.0"; const string AssertsFailFastName = "AssertsFailFast"; const string BreakOnExceptionTypesName = "BreakOnExceptionTypes"; const string FastDebugName = "FastDebug"; static bool breakOnExceptionTypesRetrieved; static Type[] breakOnExceptionTypesCache; static bool fastDebugRetrieved; static bool fastDebugCache; #endif #if UNUSED [Fx.Tag.SecurityNote(Critical = "This delegate is called from within a ConstrainedExecutionRegion, must not be settable from PT code")] [SecurityCritical] static ExceptionHandler asynchronousThreadExceptionHandler; #endif // UNUSED static ExceptionTrace exceptionTrace; ////static DiagnosticTrace diagnosticTrace; ////[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical field EtwProvider", //// Safe = "Doesn't leak info\\resources")] ////[SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule, //// Justification = "This is a method that creates ETW provider passing Guid Provider ID.")] ////static DiagnosticTrace InitializeTracing() ////{ //// DiagnosticTrace trace = new DiagnosticTrace(DefaultEventSource, DiagnosticTrace.DefaultEtwProviderId); //// return trace; ////} #if UNUSED public static ExceptionHandler AsynchronousThreadExceptionHandler { [Fx.Tag.SecurityNote(Critical = "access critical field", Safe = "ok for get-only access")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return Fx.asynchronousThreadExceptionHandler; } [Fx.Tag.SecurityNote(Critical = "sets a critical field")] [SecurityCritical] set { Fx.asynchronousThreadExceptionHandler = value; } } #endif // UNUSED public static ExceptionTrace Exception { get { if (exceptionTrace == null) { //need not be a true singleton. No locking needed here. exceptionTrace = new ExceptionTrace(DefaultEventSource); } return exceptionTrace; } } ////public static DiagnosticTrace Trace ////{ //// get //// { //// if (diagnosticTrace == null) //// { //// diagnosticTrace = InitializeTracing(); //// } //// return diagnosticTrace; //// } ////} #if !WINDOWS_UWP public static byte[] AllocateByteArray(int size) { try { // Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls). return new byte[size]; } catch (OutOfMemoryException exception) { // Convert OOM into an exception that can be safely handled by higher layers. throw Fx.Exception.AsError(new InsufficientMemoryException(CommonResources.GetString(CommonResources.BufferAllocationFailed, size), exception)); } } #endif // Do not call the parameter "message" or else FxCop thinks it should be localized. [Conditional("DEBUG")] public static void Assert(bool condition, string description) { if (!condition) { Assert(description); } } [Conditional("DEBUG")] public static void Assert(string description) { Debug.Assert(false, description); } public static void AssertAndThrow(bool condition, string description) { if (!condition) { AssertAndThrow(description); } } public static void AssertIsNotNull(object objectMayBeNull, string description) { if (objectMayBeNull == null) { Fx.AssertAndThrow(description); } } [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndThrow(string description) { Fx.Assert(description); throw Fx.Exception.AsError(new AssertionFailedException(description)); } public static void AssertAndThrowFatal(bool condition, string description) { if (!condition) { AssertAndThrowFatal(description); } } [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndThrowFatal(string description) { Fx.Assert(description); throw Fx.Exception.AsError(new FatalException(description)); } public static void AssertAndFailFastService(bool condition, string description) { if (!condition) { AssertAndFailFastService(description); } } // This never returns. The Exception return type lets you write 'throw AssertAndFailFast()' which tells the compiler/tools that // execution stops. [Fx.Tag.SecurityNote(Critical = "Calls into critical method Environment.FailFast", Safe = "The side affect of the app crashing is actually intended here")] [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndFailFastService(string description) { Fx.Assert(description); string failFastMessage = CommonResources.GetString(CommonResources.FailFastMessage, description); // The catch is here to force the finally to run, as finallys don't run until the stack walk gets to a catch. // The catch makes sure that the finally will run before the stack-walk leaves the frame, but the code inside is impossible to reach. try { try { ////MessagingClientEtwProvider.Provider.EventWriteFailFastOccurred(description); Fx.Exception.TraceFailFast(failFastMessage); // Mark that a FailFast is in progress, so that we can take ourselves out of the NLB if for // any reason we can't kill ourselves quickly. Wait 15 seconds so this state gets picked up for sure. Fx.FailFastInProgress = true; #if !WINDOWS_UWP Thread.Sleep(TimeSpan.FromSeconds(15)); #endif } finally { #if !WINDOWS_UWP // ########################## NOTE ########################### // Environment.FailFast does not collect crash dumps when used in Azure services. // Environment.FailFast(failFastMessage); // ################## WORKAROUND ############################# // Workaround for the issue above. Throwing an unhandled exception on a separate thread to trigger process crash and crash dump collection // Throwing FatalException since our service does not morph/eat up fatal exceptions // We should find the tracking bug in Azure for this issue, and remove the workaround when fixed by Azure Thread failFastWorkaroundThread = new Thread(delegate() { throw new FatalException(failFastMessage); }); failFastWorkaroundThread.Start(); failFastWorkaroundThread.Join(); #endif } } catch { throw; } return null; // we'll never get here since we've just fail-fasted } internal static bool FailFastInProgress { get; private set; } public static bool IsFatal(Exception exception) { while (exception != null) { // FYI, CallbackException is-a FatalException if (exception is FatalException || exception is OutOfMemoryException) { #if WINDOWS_UWP return true; #else if (!(exception is InsufficientMemoryException)) { return true; } #endif } #if !WINDOWS_UWP if( exception is ThreadAbortException || exception is AccessViolationException || exception is SEHException) { return true; } #endif // These exceptions aren't themselves fatal, but since the CLR uses them to wrap other exceptions, // we want to check to see whether they've been used to wrap a fatal exception. If so, then they // count as fatal. if (exception is TypeInitializationException || exception is TargetInvocationException) { exception = exception.InnerException; } else if (exception is AggregateException) { // AggregateExceptions have a collection of inner exceptions, which may themselves be other // wrapping exceptions (including nested AggregateExceptions). Recursively walk this // hierarchy. The (singular) InnerException is included in the collection. ReadOnlyCollection<Exception> innerExceptions = ((AggregateException)exception).InnerExceptions; foreach (Exception innerException in innerExceptions) { if (IsFatal(innerException)) { return true; } } break; } else if (exception is NullReferenceException) { ////MessagingClientEtwProvider.Provider.EventWriteNullReferenceErrorOccurred(exception.ToString()); break; } else { break; } } return false; } #if !WINDOWS_UWP // If the transaction has aborted then we switch over to a new transaction // which we will immediately abort after setting Transaction.Current public static TransactionScope CreateTransactionScope(Transaction transaction) { try { return transaction == null ? null : new TransactionScope(transaction); } catch (TransactionAbortedException) { CommittableTransaction tempTransaction = new CommittableTransaction(); try { return new TransactionScope(tempTransaction.Clone()); } finally { tempTransaction.Rollback(); } } } public static void CompleteTransactionScope(ref TransactionScope scope) { TransactionScope localScope = scope; if (localScope != null) { scope = null; try { localScope.Complete(); } finally { localScope.Dispose(); } } } #endif #if UNUSED public static AsyncCallback ThunkCallback(AsyncCallback callback) { return (new AsyncThunk(callback)).ThunkFrame; } public static WaitCallback ThunkCallback(WaitCallback callback) { return (new WaitThunk(callback)).ThunkFrame; } public static TimerCallback ThunkCallback(TimerCallback callback) { return (new TimerThunk(callback)).ThunkFrame; } public static WaitOrTimerCallback ThunkCallback(WaitOrTimerCallback callback) { return (new WaitOrTimerThunk(callback)).ThunkFrame; } public static SendOrPostCallback ThunkCallback(SendOrPostCallback callback) { return (new SendOrPostThunk(callback)).ThunkFrame; } #endif #if !WINDOWS_UWP [Fx.Tag.SecurityNote(Critical = "Construct the unsafe object IOCompletionThunk")] [SecurityCritical] public static IOCompletionCallback ThunkCallback(IOCompletionCallback callback) { return (new IOCompletionThunk(callback)).ThunkFrame; } public static TransactionCompletedEventHandler ThunkTransactionEventHandler(TransactionCompletedEventHandler handler) { return (new TransactionEventHandlerThunk(handler)).ThunkFrame; } #endif #if DEBUG internal static bool AssertsFailFast { get { object value; return TryGetDebugSwitch(Fx.AssertsFailFastName, out value) && typeof(int).IsAssignableFrom(value.GetType()) && ((int)value) != 0; } } internal static Type[] BreakOnExceptionTypes { get { if (!Fx.breakOnExceptionTypesRetrieved) { object value; if (TryGetDebugSwitch(Fx.BreakOnExceptionTypesName, out value)) { string[] typeNames = value as string[]; if (typeNames != null && typeNames.Length > 0) { List<Type> types = new List<Type>(typeNames.Length); for (int i = 0; i < typeNames.Length; i++) { types.Add(Type.GetType(typeNames[i], false)); } if (types.Count != 0) { Fx.breakOnExceptionTypesCache = types.ToArray(); } } } Fx.breakOnExceptionTypesRetrieved = true; } return Fx.breakOnExceptionTypesCache; } } internal static bool FastDebug { get { if (!Fx.fastDebugRetrieved) { object value; if (TryGetDebugSwitch(Fx.FastDebugName, out value)) { Fx.fastDebugCache = typeof(int).IsAssignableFrom(value.GetType()) && ((int)value) != 0; } Fx.fastDebugRetrieved = true; ////MessagingClientEtwProvider.Provider.EventWriteLogAsWarning(string.Format(CultureInfo.InvariantCulture, "AppDomain({0}).Fx.FastDebug={1}", AppDomain.CurrentDomain.FriendlyName, Fx.fastDebugCache.ToString())); } return Fx.fastDebugCache; } } static bool TryGetDebugSwitch(string name, out object value) { value = null; #if !WINDOWS_UWP try { RegistryKey key = Registry.LocalMachine.OpenSubKey(Fx.SBRegistryKey); if (key != null) { using (key) { value = key.GetValue(name); } } } catch (SecurityException) { // This debug-only code shouldn't trace. } #endif return value != null; } #endif [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes, Justification = "Don't want to hide the exception which is about to crash the process.")] #if !WINDOWS_UWP [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif static void TraceExceptionNoThrow(Exception exception) { try { // This call exits the CER. However, when still inside a catch, normal ThreadAbort is prevented. // Rude ThreadAbort will still be allowed to terminate processing. Fx.Exception.TraceUnhandled(exception); } catch { // This empty catch is only acceptable because we are a) in a CER and b) processing an exception // which is about to crash the process anyway. } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes, Justification = "Don't want to hide the exception which is about to crash the process.")] [SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.IsFatalRule, Justification = "Don't want to hide the exception which is about to crash the process.")] [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] #if !WINDOWS_UWP [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif static bool HandleAtThreadBase(Exception exception) { // This area is too sensitive to do anything but return. if (exception == null) { Fx.Assert("Null exception in HandleAtThreadBase."); return false; } TraceExceptionNoThrow(exception); #if UNUSED try { ExceptionHandler handler = Fx.AsynchronousThreadExceptionHandler; return handler == null ? false : handler.HandleException(exception); } catch (Exception secondException) { // Don't let a new exception hide the original exception. TraceExceptionNoThrow(secondException); } #endif // UNUSED return false; } #if UNUSED abstract class Thunk<T> where T : class { [Fx.Tag.SecurityNote(Critical = "Make these safe to use in SecurityCritical contexts.")] [SecurityCritical] T callback; [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data provided by caller.")] protected Thunk(T callback) { this.callback = callback; } internal T Callback { [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data is not privileged.")] get { return this.callback; } } } sealed class TimerThunk : Thunk<TimerCallback> { public TimerThunk(TimerCallback callback) : base(callback) { } public TimerCallback ThunkFrame { get { return new TimerCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } sealed class WaitOrTimerThunk : Thunk<WaitOrTimerCallback> { public WaitOrTimerThunk(WaitOrTimerCallback callback) : base(callback) { } public WaitOrTimerCallback ThunkFrame { get { return new WaitOrTimerCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(object state, bool timedOut) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state, timedOut); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } sealed class WaitThunk : Thunk<WaitCallback> { public WaitThunk(WaitCallback callback) : base(callback) { } public WaitCallback ThunkFrame { get { return new WaitCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } sealed class AsyncThunk : Thunk<AsyncCallback> { public AsyncThunk(AsyncCallback callback) : base(callback) { } public AsyncCallback ThunkFrame { get { return new AsyncCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(IAsyncResult result) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(result); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } public abstract class ExceptionHandler { [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] public abstract bool HandleException(Exception exception); } #endif // UNUSED #if !WINDOWS_UWP // This can't derive from Thunk since T would be unsafe. [Fx.Tag.SecurityNote(Critical = "unsafe object")] [SecurityCritical] unsafe sealed class IOCompletionThunk { [Fx.Tag.SecurityNote(Critical = "Make these safe to use in SecurityCritical contexts.")] IOCompletionCallback callback; [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data provided by caller.")] public IOCompletionThunk(IOCompletionCallback callback) { this.callback = callback; } public IOCompletionCallback ThunkFrame { [Fx.Tag.SecurityNote(Safe = "returns a delegate around the safe method UnhandledExceptionFrame")] get { return new IOCompletionCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Accesses critical field, calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Delegates can be invoked, guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(uint error, uint bytesRead, NativeOverlapped* nativeOverlapped) { RuntimeHelpers.PrepareConstrainedRegions(); try { this.callback(error, bytesRead, nativeOverlapped); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } #endif #if UNUSED sealed class SendOrPostThunk : Thunk<SendOrPostCallback> { public SendOrPostThunk(SendOrPostCallback callback) : base(callback) { } public SendOrPostCallback ThunkFrame { get { return new SendOrPostCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } #endif // UNUSED #if !WINDOWS_UWP sealed class TransactionEventHandlerThunk { readonly TransactionCompletedEventHandler callback; public TransactionEventHandlerThunk(TransactionCompletedEventHandler callback) { this.callback = callback; } public TransactionCompletedEventHandler ThunkFrame { get { return new TransactionCompletedEventHandler(UnhandledExceptionFrame); } } void UnhandledExceptionFrame(object sender, TransactionEventArgs args) { RuntimeHelpers.PrepareConstrainedRegions(); try { this.callback(sender, args); } catch (Exception exception) { throw AssertAndFailFastService(exception.ToString()); } } } #endif public static class Tag { public enum CacheAttrition { None, ElementOnTimer, // A finalizer/WeakReference based cache, where the elements are held by WeakReferences (or hold an // inner object by a WeakReference), and the weakly-referenced object has a finalizer which cleans the // item from the cache. ElementOnGC, // A cache that provides a per-element token, delegate, interface, or other piece of context that can // be used to remove the element (such as IDisposable). ElementOnCallback, FullPurgeOnTimer, FullPurgeOnEachAccess, PartialPurgeOnTimer, PartialPurgeOnEachAccess, } public enum Location { InProcess, OutOfProcess, LocalSystem, LocalOrRemoteSystem, // as in a file that might live on a share RemoteSystem, } public enum SynchronizationKind { LockStatement, MonitorWait, MonitorExplicit, InterlockedNoSpin, InterlockedWithSpin, // Same as LockStatement if the field type is object. FromFieldType, } [Flags] public enum BlocksUsing { MonitorEnter, MonitorWait, ManualResetEvent, AutoResetEvent, AsyncResult, IAsyncResult, PInvoke, InputQueue, ThreadNeutralSemaphore, PrivatePrimitive, OtherInternalPrimitive, OtherFrameworkPrimitive, OtherInterop, Other, NonBlocking, // For use by non-blocking SynchronizationPrimitives such as IOThreadScheduler } public static class Strings { internal const string ExternallyManaged = "externally managed"; internal const string AppDomain = "AppDomain"; internal const string DeclaringInstance = "instance of declaring class"; internal const string Unbounded = "unbounded"; internal const string Infinite = "infinite"; } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class ExternalResourceAttribute : Attribute { readonly Location location; readonly string description; public ExternalResourceAttribute(Location location, string description) { this.location = location; this.description = description; } public Location Location { get { return this.location; } } public string Description { get { return this.description; } } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS")] public sealed class CacheAttribute : Attribute { readonly Type elementType; readonly CacheAttrition cacheAttrition; public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) { Scope = Strings.DeclaringInstance; SizeLimit = Strings.Unbounded; Timeout = Strings.Infinite; if (elementType == null) { throw Fx.Exception.ArgumentNull("elementType"); } this.elementType = elementType; this.cacheAttrition = cacheAttrition; } public Type ElementType { get { return this.elementType; } } public CacheAttrition CacheAttrition { get { return this.cacheAttrition; } } public string Scope { get; set; } public string SizeLimit { get; set; } public string Timeout { get; set; } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS")] public sealed class QueueAttribute : Attribute { readonly Type elementType; public QueueAttribute(Type elementType) { Scope = Strings.DeclaringInstance; SizeLimit = Strings.Unbounded; if (elementType == null) { throw Fx.Exception.ArgumentNull("elementType"); } this.elementType = elementType; } public Type ElementType { get { return this.elementType; } } public string Scope { get; set; } public string SizeLimit { get; set; } public bool StaleElementsRemovedImmediately { get; set; } public bool EnqueueThrowsIfFull { get; set; } } // Set on a class when that class uses lock (this) - acts as though it were on a field // private object this; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Class, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class SynchronizationObjectAttribute : Attribute { public SynchronizationObjectAttribute() { Blocking = true; Scope = Strings.DeclaringInstance; Kind = SynchronizationKind.FromFieldType; } public bool Blocking { get; set; } public string Scope { get; set; } public SynchronizationKind Kind { get; set; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)] [Conditional("CODE_ANALYSIS")] public sealed class SynchronizationPrimitiveAttribute : Attribute { readonly BlocksUsing blocksUsing; public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing) { this.blocksUsing = blocksUsing; } public BlocksUsing BlocksUsing { get { return this.blocksUsing; } } public bool SupportsAsync { get; set; } public bool Spins { get; set; } public string ReleaseMethod { get; set; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class BlockingAttribute : Attribute { public BlockingAttribute() { } public string CancelMethod { get; set; } public Type CancelDeclaringType { get; set; } public string Conditional { get; set; } } // Sometime a method will call a conditionally-blocking method in such a way that it is guaranteed // not to block (i.e. the condition can be Asserted false). Such a method can be marked as // GuaranteeNonBlocking as an assertion that the method doesn't block despite calling a blocking method. // // Methods that don't call blocking methods and aren't marked as Blocking are assumed not to block, so // they do not require this attribute. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class GuaranteeNonBlockingAttribute : Attribute { public GuaranteeNonBlockingAttribute() { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class NonThrowingAttribute : Attribute { public NonThrowingAttribute() { } } [SuppressMessage(FxCop.Category.Performance, "CA1813:AvoidUnsealedAttributes", Justification = "This is intended to be an attribute heirarchy. It does not affect product perf.")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS")] public class ThrowsAttribute : Attribute { readonly Type exceptionType; readonly string diagnosis; public ThrowsAttribute(Type exceptionType, string diagnosis) { if (exceptionType == null) { throw Fx.Exception.ArgumentNull("exceptionType"); } if (string.IsNullOrEmpty(diagnosis)) { throw Fx.Exception.ArgumentNullOrEmpty("diagnosis"); } this.exceptionType = exceptionType; this.diagnosis = diagnosis; } public Type ExceptionType { get { return this.exceptionType; } } public string Diagnosis { get { return this.diagnosis; } } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class InheritThrowsAttribute : Attribute { public InheritThrowsAttribute() { } public Type FromDeclaringType { get; set; } public string From { get; set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class SecurityNoteAttribute : Attribute { public SecurityNoteAttribute() { } public string Critical { get; set; } public string Safe { get; set; } public string Miscellaneous { get; set; } } } } }
// This is an open source non-commercial project. Dear PVS-Studio, please check it. PVS-Studio Static // Code Analyzer for C, C++ and C#: http://www.viva64.com namespace EOpt.Math.Optimization.OOOpt { using System; using System.Collections.Generic; using System.Threading; using Help; using Math; using Math.Random; using Optimization; /// <summary> /// Optimization method Fireworks. /// </summary> public class FWOptimizer : BaseFW<double, IOOOptProblem>, IOOOptimizer<FWParams> { private double _fmax, _fmin; private int _indexSolutionInCharges, _indexSolutionInDebrisFromCharge, _indexSolutionInDebris; private Agent _solution; private void EvalFunction(Func<IReadOnlyList<double>, double> Function) { for (int i = 0; i < _parameters.NP; i++) { _chargePoints[i].Eval(Function); } } private void EvalFunctionForDebris(Func<IReadOnlyList<double>, double> Function) { for (int i = 0; i < _debris.Length; i++) { foreach (Agent agent in _debris[i]) { agent.Eval(Function); } } } /// <summary> /// Find amount debris for each point of charge. /// </summary> private void FindAmountDebris() { double s = 0; double denumerator = 0; for (int i = 0; i < _parameters.NP; i++) { denumerator += _fmax - _chargePoints[i].Objs[0]; } if (denumerator < Constants.VALUE_AVOID_DIV_BY_ZERO) { denumerator += Constants.VALUE_AVOID_DIV_BY_ZERO; } for (int i = 0; i < _parameters.NP; i++) { s = _parameters.M * (_fmax - _chargePoints[i].Objs[0] + Constants.VALUE_AVOID_DIV_BY_ZERO) / denumerator; base.FindAmountDebrisForCharge(s, i); } } /// <summary> /// Find best solution among debris and charges. /// </summary> private void FindBestSolution() { _solution.SetAt(_chargePoints[0]); _indexSolutionInCharges = 0; _indexSolutionInDebrisFromCharge = -1; _indexSolutionInDebris = -1; // Searching best solution among charges. for (int i = 1; i < _parameters.NP; i++) { if (_chargePoints[i].Objs[0] < _solution.Objs[0]) { _solution.SetAt(_chargePoints[i]); _indexSolutionInCharges = i; } } // Searching best solution among debris. for (int j = 0; j < _parameters.NP; j++) { int k = 0; foreach (Agent splinter in _debris[j]) { if (splinter.Objs[0] < _solution.Objs[0]) { _solution.SetAt(splinter); _indexSolutionInCharges = -1; _indexSolutionInDebrisFromCharge = j; _indexSolutionInDebris = k; } k++; } } } private void FindFMaxMin() { _fmin = _chargePoints[0].Objs[0]; _fmax = _chargePoints[0].Objs[0]; for (int i = 0; i < _parameters.NP; i++) { if (_chargePoints[i].Objs[0] < _fmin) { _fmin = _chargePoints[i].Objs[0]; } else if (_chargePoints[i].Objs[0] > _fmax) { _fmax = _chargePoints[i].Objs[0]; } } } /// <summary> /// Determine debris position. /// </summary> /// <param name="LowerBounds"></param> /// <param name="UpperBounds"></param> private void GenerateDebris(IReadOnlyList<double> LowerBounds, IReadOnlyList<double> UpperBounds) { double denumerator = 0; for (int j = 0; j < _parameters.NP; j++) { denumerator += _chargePoints[j].Objs[0] - _fmin; } if (denumerator < Constants.VALUE_AVOID_DIV_BY_ZERO) { denumerator += Constants.VALUE_AVOID_DIV_BY_ZERO; } for (int i = 0; i < _parameters.NP; i++) { double amplitude = 0; // Amplitude of explosion. amplitude = _parameters.Amax * (_chargePoints[i].Objs[0] - _fmin + Constants.VALUE_AVOID_DIV_BY_ZERO) / denumerator; base.GenerateDebrisForCharge(LowerBounds, UpperBounds, amplitude, i); } } /// <summary> /// Generate current population. /// </summary> private void GenerateNextAgents() { // The total count minus solution. int actualSizeMatrix = _chargePoints.Count - 1; for (int k = 0; k < _parameters.NP; k++) { actualSizeMatrix += _debris[k].Count; } base.ResetMatrixAndTrimWeights(actualSizeMatrix); { int index = 0; for (int i = 0; i < _chargePoints.Count; i++) { // Skip solution. if (i != _indexSolutionInCharges) { _weightedAgents[index].Agent.SetAt(_chargePoints[i]); index++; } } for (int i = 0; i < _parameters.NP; i++) { int k = 0; foreach (Agent splinter in _debris[i]) { // Skip solution, if it in the debris. if (_indexSolutionInDebrisFromCharge != i || _indexSolutionInDebris != k) { _weightedAgents[index].Agent.SetAt(splinter); index++; } k++; } } } base.CalculateDistances((a, b) => PointND.Distance(a.Point, b.Point)); int totalToTake = _parameters.NP - 1; base.TakeAgents(totalToTake); _chargePoints[0].SetAt(_solution); int startIndex = 1; for (int i = 0; i < actualSizeMatrix && totalToTake > 0; i++) { if (_weightedAgents[i].IsTake) { _chargePoints[startIndex].SetAt(_weightedAgents[i].Agent); startIndex++; totalToTake--; } } } protected override void FirstStep(IOOOptProblem Problem) { if (Problem == null) { throw new ArgumentNullException(nameof(Problem)); } base.InitAgents(Problem.LowerBounds, Problem.UpperBounds, 1); EvalFunction(Problem.TargetFunction); FindFMaxMin(); FindAmountDebris(); GenerateDebris(Problem.LowerBounds, Problem.UpperBounds); EvalFunctionForDebris(Problem.TargetFunction); FindBestSolution(); } protected override void Init(FWParams Parameters, int Dimension, int DimObjs) { base.Init(Parameters, Dimension, DimObjs); if (_solution == null) { _solution = new Agent(Dimension, DimObjs); } else if (_solution.Point.Count != Dimension) { _solution = new Agent(Dimension, DimObjs); } } protected override void NextStep(IOOOptProblem Problem) { GenerateNextAgents(); EvalFunction(Problem.TargetFunction); FindFMaxMin(); FindAmountDebris(); GenerateDebris(Problem.LowerBounds, Problem.UpperBounds); EvalFunctionForDebris(Problem.TargetFunction); FindBestSolution(); } /// <summary> /// The solution of the constrained optimization problem. /// </summary> public Agent Solution => _solution; /// <summary> /// Create object which uses default implementation for random generators. /// </summary> public FWOptimizer() : this(new ContUniformDist(), new NormalDist()) { } /// <summary> /// Create object which uses custom implementation for random generators. /// </summary> /// <param name="UniformGen"> Object, which implements <see cref="IContUniformGen"/> interface. </param> /// <param name="NormalGen"> Object, which implements <see cref="INormalGen"/> interface. </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="NormalGen"/> or <paramref name="UniformGen"/> is null. /// </exception> public FWOptimizer(IContUniformGen UniformGen, INormalGen NormalGen) : base(UniformGen, NormalGen) { } /// <summary> /// <see cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem)"/> /// </summary> /// <param name="Parameters"> Parameters for method. </param> /// <param name="Problem"> An optimization problem. </param> /// <exception cref="InvalidOperationException"> If parameters do not set. </exception> /// <exception cref="ArgumentNullException"> If <paramref name="Problem"/> is null. </exception> /// <exception cref="ArithmeticException"> /// If the function has value is NaN, PositiveInfinity or NegativeInfinity. /// </exception> public override void Minimize(FWParams Parameters, IOOOptProblem Problem) { Init(Parameters, Problem.LowerBounds.Count, 1); FirstStep(Problem); for (int i = 1; i < _parameters.Imax; i++) { NextStep(Problem); } Clear(); } /// <summary> /// <see cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem, CancellationToken)"/> /// </summary> /// <param name="Parameters"> Parameters for method. </param> /// <param name="Problem"> An optimization problem. </param> /// <param name="CancelToken"> <see cref="CancellationToken"/> </param> /// <exception cref="InvalidOperationException"> If parameters do not set. </exception> /// <exception cref="ArgumentNullException"> If <paramref name="Problem"/> is null. </exception> /// <exception cref="ArithmeticException"> /// If the function has value is NaN, PositiveInfinity or NegativeInfinity. /// </exception> /// <exception cref="OperationCanceledException"></exception> public override void Minimize(FWParams Parameters, IOOOptProblem Problem, CancellationToken CancelToken) { Init(Parameters, Problem.LowerBounds.Count, 1); FirstStep(Problem); for (int i = 1; i < _parameters.Imax; i++) { CancelToken.ThrowIfCancellationRequested(); NextStep(Problem); } Clear(); } /// <summary> /// <see cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem, CancellationToken)"/> /// </summary> /// <param name="Parameters"> Parameters for method. </param> /// <param name="Problem"> An optimization problem. </param> /// <param name="Reporter"> /// Object which implement interface <see cref="IProgress{T}"/>, where T is /// <see cref="Progress"/>. <seealso cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem, IProgress{Progress})"/> /// </param> /// <exception cref="InvalidOperationException"> If parameters do not set. </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="Problem"/> or <paramref name="Reporter"/> is null. /// </exception> /// <exception cref="ArithmeticException"> /// If the function has value is NaN, PositiveInfinity or NegativeInfinity. /// </exception> public override void Minimize(FWParams Parameters, IOOOptProblem Problem, IProgress<Progress> Reporter) { if (Reporter == null) { throw new ArgumentNullException(nameof(Reporter)); } Init(Parameters, Problem.LowerBounds.Count, 1); FirstStep(Problem); Progress progress = new Progress(this, 0, _parameters.Imax - 1, 0); Reporter.Report(progress); for (int i = 1; i < this._parameters.Imax; i++) { NextStep(Problem); progress.Current = i; Reporter.Report(progress); } Clear(); } /// <summary> /// <see cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem, CancellationToken)"/> /// </summary> /// <param name="Parameters"> Parameters for method. </param> /// <param name="Problem"> An optimization problem. </param> /// <param name="Reporter"> /// Object which implement interface <see cref="IProgress{T}"/>, where T is /// <see cref="Progress"/>. <seealso cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem, IProgress{Progress})"/> /// </param> /// <param name="CancelToken"> <see cref="CancellationToken"/> </param> /// <exception cref="InvalidOperationException"> If parameters do not set. </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="Problem"/> or <paramref name="Reporter"/> is null. /// </exception> /// <exception cref="ArithmeticException"> /// If the function has value is NaN, PositiveInfinity or NegativeInfinity. /// </exception> /// <exception cref="OperationCanceledException"></exception> public override void Minimize(FWParams Parameters, IOOOptProblem Problem, IProgress<Progress> Reporter, CancellationToken CancelToken) { if (Reporter == null) { throw new ArgumentNullException(nameof(Reporter)); } Init(Parameters, Problem.LowerBounds.Count, 1); FirstStep(Problem); Progress progress = new Progress(this, 0, _parameters.Imax - 1, 0); Reporter.Report(progress); for (int i = 1; i < _parameters.Imax; i++) { CancelToken.ThrowIfCancellationRequested(); NextStep(Problem); progress.Current = i; Reporter.Report(progress); } Clear(); } } }
// 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.IO; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.IO.Tests { public partial class WriteTests { protected virtual Stream CreateStream() { return new MemoryStream(); } [Fact] public void WriteChars() { char[] chArr = setupArray(); // [] Write a wide variety of characters and read them back Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); StreamReader sr; for (int i = 0; i < chArr.Length; i++) sw.Write(chArr[i]); sw.Flush(); ms.Position = 0; sr = new StreamReader(ms); for (int i = 0; i < chArr.Length; i++) { Assert.Equal((int)chArr[i], sr.Read()); } } private static char[] setupArray() { return new char[]{ char.MinValue ,char.MaxValue ,'\t' ,' ' ,'$' ,'@' ,'#' ,'\0' ,'\v' ,'\'' ,'\u3190' ,'\uC3A0' ,'A' ,'5' ,'\uFE70' ,'-' ,';' ,'\u00E6' }; } [Fact] public void NullArray() { // [] Exception for null array Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); Assert.Throws<ArgumentNullException>(() => sw.Write(null, 0, 0)); sw.Dispose(); } [Fact] public void NegativeOffset() { char[] chArr = setupArray(); // [] Exception if offset is negative Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(chArr, -1, 0)); sw.Dispose(); } [Fact] public void NegativeCount() { char[] chArr = setupArray(); // [] Exception if count is negative Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(chArr, 0, -1)); sw.Dispose(); } [Fact] public void WriteCustomLenghtStrings() { char[] chArr = setupArray(); // [] Write some custom length strings Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); StreamReader sr; sw.Write(chArr, 2, 5); sw.Flush(); ms.Position = 0; sr = new StreamReader(ms); int tmp = 0; for (int i = 2; i < 7; i++) { tmp = sr.Read(); Assert.Equal((int)chArr[i], tmp); } ms.Dispose(); } [Fact] public void WriteToStreamWriter() { char[] chArr = setupArray(); // [] Just construct a streamwriter and write to it //------------------------------------------------- Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); StreamReader sr; sw.Write(chArr, 0, chArr.Length); sw.Flush(); ms.Position = 0; sr = new StreamReader(ms); for (int i = 0; i < chArr.Length; i++) { Assert.Equal((int)chArr[i], sr.Read()); } ms.Dispose(); } [Fact] public void TestWritingPastEndOfArray() { char[] chArr = setupArray(); Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); AssertExtensions.Throws<ArgumentException>(null, () => sw.Write(chArr, 1, chArr.Length)); sw.Dispose(); } [Fact] public void VerifyWrittenString() { char[] chArr = setupArray(); // [] Write string with wide selection of characters and read it back StringBuilder sb = new StringBuilder(40); Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); StreamReader sr; for (int i = 0; i < chArr.Length; i++) sb.Append(chArr[i]); sw.Write(sb.ToString()); sw.Flush(); ms.Position = 0; sr = new StreamReader(ms); for (int i = 0; i < chArr.Length; i++) { Assert.Equal((int)chArr[i], sr.Read()); } } [Fact] public void NullStreamThrows() { // [] Null string should write nothing Stream ms = CreateStream(); StreamWriter sw = new StreamWriter(ms); sw.Write((string)null); sw.Flush(); Assert.Equal(0, ms.Length); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework throws NullReferenceException")] public async Task NullNewLineAsync() { using (MemoryStream ms = new MemoryStream()) { string newLine; using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8, 16, true)) { newLine = sw.NewLine; await sw.WriteLineAsync(default(string)); await sw.WriteLineAsync(default(string)); } ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(ms)) { Assert.Equal(newLine + newLine, await sr.ReadToEndAsync()); } } } } }
// // ExtensionNodeDescription.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Xml; using System.Collections.Specialized; using Mono.Addins.Serialization; namespace Mono.Addins.Description { /// <summary> /// An extension node definition. /// </summary> public class ExtensionNodeDescription: ObjectDescription, NodeElement { ExtensionNodeDescriptionCollection childNodes; string[] attributes; string nodeName; /// <summary> /// Initializes a new instance of the <see cref="Mono.Addins.Description.ExtensionNodeDescription"/> class. /// </summary> /// <param name='nodeName'> /// Node name. /// </param> public ExtensionNodeDescription (string nodeName) { this.nodeName = nodeName; } internal ExtensionNodeDescription (XmlElement elem) { Element = elem; nodeName = elem.LocalName; } internal ExtensionNodeDescription () { } /// <summary> /// Gets the type of the node. /// </summary> /// <returns> /// The node type. /// </returns> /// <remarks> /// This method only works when the add-in description to which the node belongs has been /// loaded from an add-in registry. /// </remarks> public ExtensionNodeType GetNodeType () { if (Parent is Extension) { Extension ext = (Extension) Parent; object ob = ext.GetExtendedObject (); if (ob is ExtensionPoint) { ExtensionPoint ep = (ExtensionPoint) ob; return ep.NodeSet.GetAllowedNodeTypes () [NodeName]; } else if (ob is ExtensionNodeDescription) { ExtensionNodeDescription pn = (ExtensionNodeDescription) ob; ExtensionNodeType pt = ((ExtensionNodeDescription) pn).GetNodeType (); if (pt != null) return pt.GetAllowedNodeTypes () [NodeName]; } } else if (Parent is ExtensionNodeDescription) { ExtensionNodeType pt = ((ExtensionNodeDescription) Parent).GetNodeType (); if (pt != null) return pt.GetAllowedNodeTypes () [NodeName]; } return null; } /// <summary> /// Gets the extension path under which this node is registered /// </summary> /// <returns> /// The parent path. /// </returns> /// <remarks> /// For example, if the id of the node is 'ThisNode', and the node is a child of another node with id 'ParentNode', and /// that parent node is defined in an extension with the path '/Core/MainExtension', then the parent path is 'Core/MainExtension/ParentNode'. /// </remarks> public string GetParentPath () { if (Parent is Extension) return ((Extension)Parent).Path; else if (Parent is ExtensionNodeDescription) { ExtensionNodeDescription pn = (ExtensionNodeDescription) Parent; return pn.GetParentPath () + "/" + pn.Id; } else return string.Empty; } internal override void Verify (string location, StringCollection errors) { if (nodeName == null || nodeName.Length == 0) errors.Add (location + "Node: NodeName can't be empty."); ChildNodes.Verify (location + NodeName + "/", errors); } /// <summary> /// Gets or sets the name of the node. /// </summary> /// <value> /// The name of the node. /// </value> public string NodeName { get { return nodeName; } internal set { if (Element != null) throw new InvalidOperationException ("Can't change node name of xml element"); nodeName = value; } } /// <summary> /// Gets or sets the identifier of the node. /// </summary> /// <value> /// The identifier. /// </value> public string Id { get { return GetAttribute ("id"); } set { SetAttribute ("id", value); } } /// <summary> /// Gets or sets the identifier of the node after which this node has to be inserted /// </summary> /// <value> /// The identifier of the reference node /// </value> public string InsertAfter { get { return GetAttribute ("insertafter"); } set { if (value == null || value.Length == 0) RemoveAttribute ("insertafter"); else SetAttribute ("insertafter", value); } } /// <summary> /// Gets or sets the identifier of the node before which this node has to be inserted /// </summary> /// <value> /// The identifier of the reference node /// </value> public string InsertBefore { get { return GetAttribute ("insertbefore"); } set { if (value == null || value.Length == 0) RemoveAttribute ("insertbefore"); else SetAttribute ("insertbefore", value); } } /// <summary> /// Gets a value indicating whether this node is a condition. /// </summary> /// <value> /// <c>true</c> if this node is a condition; otherwise, <c>false</c>. /// </value> public bool IsCondition { get { return nodeName == "Condition" || nodeName == "ComplexCondition"; } } internal override void SaveXml (XmlElement parent) { if (Element == null) { Element = parent.OwnerDocument.CreateElement (nodeName); parent.AppendChild (Element); if (attributes != null) { for (int n=0; n<attributes.Length; n+=2) Element.SetAttribute (attributes[n], attributes[n+1]); } ChildNodes.SaveXml (Element); } } /// <summary> /// Gets the value of an attribute. /// </summary> /// <returns> /// The value of the attribute, or an empty string if the attribute is not defined. /// </returns> /// <param name='key'> /// Name of the attribute. /// </param> public string GetAttribute (string key) { if (Element != null) return Element.GetAttribute (key); if (attributes == null) return string.Empty; for (int n=0; n<attributes.Length; n+=2) { if (attributes [n] == key) return attributes [n+1]; } return string.Empty; } /// <summary> /// Sets the value of an attribute. /// </summary> /// <param name='key'> /// Name of the attribute /// </param> /// <param name='value'> /// The value. /// </param> public void SetAttribute (string key, string value) { if (Element != null) { Element.SetAttribute (key, value); return; } if (value == null) value = string.Empty; if (attributes == null) { attributes = new string [2]; attributes [0] = key; attributes [1] = value; return; } for (int n=0; n<attributes.Length; n+=2) { if (attributes [n] == key) { attributes [n+1] = value; return; } } string[] newList = new string [attributes.Length + 2]; attributes.CopyTo (newList, 0); attributes = newList; attributes [attributes.Length - 2] = key; attributes [attributes.Length - 1] = value; } /// <summary> /// Removes an attribute. /// </summary> /// <param name='name'> /// Name of the attribute to remove. /// </param> public void RemoveAttribute (string name) { if (Element != null) { Element.RemoveAttribute (name); return; } if (attributes == null) return; for (int n=0; n<attributes.Length; n+=2) { if (attributes [n] == name) { string[] newar = new string [attributes.Length - 2]; Array.Copy (attributes, 0, newar, 0, n); Array.Copy (attributes, n+2, newar, n, attributes.Length - n - 2); attributes = newar; break; } } } /// <summary> /// Gets the attributes of the node. /// </summary> /// <value> /// The attributes. /// </value> public NodeAttribute[] Attributes { get { if (Element != null) SaveXmlAttributes (); if (attributes == null) return new NodeAttribute [0]; NodeAttribute[] ats = new NodeAttribute [attributes.Length / 2]; for (int n=0; n<ats.Length; n++) { NodeAttribute at = new NodeAttribute (); at.name = attributes [n*2]; at.value = attributes [n*2 + 1]; ats [n] = at; } return ats; } } /// <summary> /// Gets the child nodes. /// </summary> /// <value> /// The child nodes. /// </value> public ExtensionNodeDescriptionCollection ChildNodes { get { if (childNodes == null) { childNodes = new ExtensionNodeDescriptionCollection (this); if (Element != null) { foreach (XmlNode nod in Element.ChildNodes) { if (nod is XmlElement) childNodes.Add (new ExtensionNodeDescription ((XmlElement)nod)); } } } return childNodes; } } NodeElementCollection NodeElement.ChildNodes { get { return ChildNodes; } } void SaveXmlAttributes () { attributes = new string [Element.Attributes.Count * 2]; for (int n=0; n<attributes.Length; n+=2) { XmlAttribute at = Element.Attributes [n/2]; attributes [n] = at.LocalName; attributes [n+1] = at.Value; } } internal override void Write (BinaryXmlWriter writer) { if (Element != null) SaveXmlAttributes (); writer.WriteValue ("nodeName", nodeName); writer.WriteValue ("attributes", attributes); writer.WriteValue ("ChildNodes", ChildNodes); } internal override void Read (BinaryXmlReader reader) { nodeName = reader.ReadStringValue ("nodeName"); attributes = (string[]) reader.ReadValue ("attributes"); childNodes = (ExtensionNodeDescriptionCollection) reader.ReadValue ("ChildNodes", new ExtensionNodeDescriptionCollection (this)); } } }
// Copyright (c) Microsoft Open Technologies, Inc. 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.Globalization; using System.Linq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonCommandLineParserTests : TestBase { private const int EN_US = 1033; private void VerifyCommandLineSplitter(string commandLine, string[] expected) { string[] actual = CommandLineSplitter.SplitCommandLine(commandLine); Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < actual.Length; ++i) { Assert.Equal(expected[i], actual[i]); } } private RuleSet ParseRuleSet(string source, params string[] otherSources) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); for (int i = 1; i <= otherSources.Length; i++) { var newFile = dir.CreateFile("file" + i + ".ruleset"); newFile.WriteAllText(otherSources[i - 1]); } if (otherSources.Length != 0) { return RuleSet.LoadEffectiveRuleSetFromFile(file.Path); } return RuleSetProcessor.LoadFromFile(file.Path); } private void VerifyRuleSetError(string source, string message, bool locSpecific = true, string locMessage = "", params string[] otherSources) { try { ParseRuleSet(source, otherSources); } catch (Exception e) { if (CultureInfo.CurrentCulture.LCID == EN_US || CultureInfo.CurrentUICulture.LCID == EN_US || CultureInfo.CurrentCulture == CultureInfo.InvariantCulture || CultureInfo.CurrentUICulture == CultureInfo.InvariantCulture) { Assert.Equal(message, e.Message); } else if (locSpecific) { if (locMessage != "") Assert.Contains(locMessage, e.Message); else Assert.Equal(message, e.Message); } return; } Assert.True(false, "Didn't return an error"); } [Fact] public void TestCommandLineSplitter() { VerifyCommandLineSplitter("", new string[0]); VerifyCommandLineSplitter(" \t ", new string[0]); VerifyCommandLineSplitter(" abc\tdef baz quuz ", new string[] {"abc", "def", "baz", "quuz"}); VerifyCommandLineSplitter(@" ""abc def"" fi""ddle dee de""e ""hi there ""dude he""llo there"" ", new string[] { @"abc def", @"fi""ddle dee de""e", @"""hi there ""dude", @"he""llo there""" }); VerifyCommandLineSplitter(@" ""abc def \"" baz quuz"" ""\""straw berry"" fi\""zz \""buzz fizzbuzz", new string[] { @"abc def "" baz quuz", @"""straw berry", @"fi""zz", @"""buzz", @"fizzbuzz"}); VerifyCommandLineSplitter(@" \\""abc def"" \\\""abc def"" ", new string[] { @"\""abc def""", @"\""abc", @"def""" }); VerifyCommandLineSplitter(@" \\\\""abc def"" \\\\\""abc def"" ", new string[] { @"\\""abc def""", @"\\""abc", @"def""" }); } [Fact] public void TestRuleSetParsingDuplicateRule() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1012"" Action=""Warning"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet>"; string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, ""); VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "There is a duplicate key sequence 'CA1012' for the 'UniqueRuleName' key or unique identity constraint."), locMessage: locMessage); string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, ""); VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "There is a duplicate key sequence 'CA1012' for the 'UniqueRuleName' key or unique identity constraint."), locMessage: locMessage); } [Fact] public void TestRuleSetParsingDuplicateRule2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> <Rule Id=""CA1013"" Action=""None"" /> </Rules> </RuleSet>"; VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetHasDuplicateRules, "CA1012", "Error", "Warn"), locSpecific: false); } [Fact] public void TestRuleSetParsingDuplicateRule3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""None"" /> </Rules> </RuleSet>"; var ruleSet = ParseRuleSet(source); Assert.Equal(expected: ReportDiagnostic.Error, actual: ruleSet.SpecificDiagnosticOptions["CA1012"]); } [Fact] public void TestRuleSetParsingDuplicateRuleSet() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> <RuleSet Name=""Ruleset2"" Description=""Test""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, "There are multiple root elements. Line 8, position 2.", false); } [Fact] public void TestRuleSetParsingIncludeAll1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.Equal(ReportDiagnostic.Warn, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetParsingIncludeAll2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetParsingWithIncludeOfSameFile() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""a.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, new string[] { "" }); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Equal(1, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count()); } [Fact] public void TestRuleSetParsingWithMutualIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""a.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Equal(2, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count()); } [Fact] public void TestRuleSetParsingWithSiblingIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Warning"" /> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Equal(3, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count()); } [Fact] public void TestRuleSetParsingIncludeAll3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, ""); VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The 'Action' attribute is invalid - The value 'Default' is invalid according to its datatype 'TIncludeAllAction' - The Enumeration constraint failed."), locMessage: locMessage); } [Fact] public void TestRuleSetParsingRulesMissingAttribute1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Action=""Error"" /> </Rules> </RuleSet> "; string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, ""); VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'Id' is missing."), locMessage: locMessage); } [Fact] public void TestRuleSetParsingRulesMissingAttribute2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" /> </Rules> </RuleSet> "; string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, ""); VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'Action' is missing."), locMessage: locMessage); } [Fact] public void TestRuleSetParsingRulesMissingAttribute3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, ""); VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'AnalyzerId' is missing."), locMessage: locMessage); } [Fact] public void TestRuleSetParsingRulesMissingAttribute4() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, ""); VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'RuleNamespace' is missing."), locMessage: locMessage); } [Fact] public void TestRuleSetParsingRulesMissingAttribute5() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, ""); VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'ToolsVersion' is missing."), locMessage: locMessage); } [Fact] public void TestRuleSetParsingRulesMissingAttribute6() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, ""); VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'Name' is missing."), locMessage: locMessage); } [Fact] public void TestRuleSetParsingRules() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> <Rule Id=""CA1015"" Action=""Info"" /> <Rule Id=""CA1016"" Action=""Hidden"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1012"], ReportDiagnostic.Error); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1013"], ReportDiagnostic.Warn); Assert.Contains("CA1014", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1014"], ReportDiagnostic.Suppress); Assert.Contains("CA1015", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1015"], ReportDiagnostic.Info); Assert.Contains("CA1016", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1016"], ReportDiagnostic.Hidden); } [Fact] public void TestRuleSetParsingRules2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Default"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, ""); VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The 'Action' attribute is invalid - The value 'Default' is invalid according to its datatype 'TRuleAction' - The Enumeration constraint failed."), locMessage: locMessage); } [Fact] public void TestRuleSetInclude() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""foo.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.True(ruleSet.Includes.Count() == 1); Assert.Equal(ruleSet.Includes.First().Action, ReportDiagnostic.Default); Assert.Equal(ruleSet.Includes.First().IncludePath, "foo.ruleset"); } [WorkItem(156)] [Fact(Skip = "156")] public void TestRuleSetInclude1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""foo.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, string.Format(CodeAnalysisResources.InvalidRuleSetInclude, "foo.ruleset", string.Format(CodeAnalysisResources.FailedToResolveRuleSetName, "foo.ruleset")), otherSources: new string[] {""}); } [Fact] public void TestRuleSetInclude2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Hidden"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Hidden, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Info"" /> <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Info, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Include Path=""file1.ruleset"" Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeRecursiveIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1014"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); Assert.Contains("CA1014", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1014"]); } [Fact] public void TestRuleSetIncludeSpecificStrict1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); // CA1012's value in source wins. Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); } [Fact] public void TestRuleSetIncludeSpecificStrict2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); // CA1012's value in source still wins. Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); } [Fact] public void TestRuleSetIncludeSpecificStrict3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); // CA1013's value in source2 wins. Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeEffectiveAction() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""None"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.DoesNotContain("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); } [Fact] public void TestRuleSetIncludeEffectiveAction1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetIncludeEffectiveActionGlobal1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetIncludeEffectiveActionGlobal2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Warn, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetIncludeEffectiveActionSpecific1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""None"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeEffectiveActionSpecific2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestAllCombinations() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>"; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1000"]); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1001"]); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA2100"]); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA2104"]); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA2105"]); Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA2111"]); Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA2119"]); } [Fact] public void TestRuleSetIncludeError() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Default"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); var newFile = dir.CreateFile("file1.ruleset"); newFile.WriteAllText(source1); try { RuleSet.LoadEffectiveRuleSetFromFile(file.Path); Assert.True(false, "Didn't throw an exception"); } catch (InvalidRuleSetException e) { Assert.Contains(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, newFile.Path, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "")), e.Message); } } [Fact] public void GetEffectiveIncludes_NoIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path); Assert.Equal(expected: 1, actual: includePaths.Length); Assert.Equal(expected: file.Path, actual: includePaths[0]); } [Fact] public void GetEffectiveIncludes_OneLevel() { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet> "; string includeSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(ruleSetSource); var include = dir.CreateFile("file1.ruleset"); include.WriteAllText(includeSource); var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path); Assert.Equal(expected: 2, actual: includePaths.Length); Assert.Equal(expected: file.Path, actual: includePaths[0]); Assert.Equal(expected: include.Path, actual: includePaths[1]); } [Fact] public void GetEffectiveIncludes_TwoLevels() { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet> "; string includeSource1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet> "; string includeSource2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(ruleSetSource); var include1 = dir.CreateFile("file1.ruleset"); include1.WriteAllText(includeSource1); var include2 = dir.CreateFile("file2.ruleset"); include2.WriteAllText(includeSource2); var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path); Assert.Equal(expected: 3, actual: includePaths.Length); Assert.Equal(expected: file.Path, actual: includePaths[0]); Assert.Equal(expected: include1.Path, actual: includePaths[1]); Assert.Equal(expected: include2.Path, actual: includePaths[2]); } } }
using System; namespace SharpTibiaProxy.Util { /// <summary> /// Helper methods for reading memory. /// </summary> public static class Memory { /// <summary> /// Read a specified number of bytes from a process. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="bytesToRead"></param> /// <returns></returns> public static byte[] ReadBytes(IntPtr handle, long address, uint bytesToRead) { IntPtr ptrBytesRead; byte[] buffer = new byte[bytesToRead]; WinApi.ReadProcessMemory(handle, new IntPtr(address), buffer, bytesToRead, out ptrBytesRead); return buffer; } /// <summary> /// Read a byte from memory. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <returns></returns> public static byte ReadByte(IntPtr handle, long address) { return ReadBytes(handle, address, 1)[0]; } /// <summary> /// Read a short from memory (16-bits). /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <returns></returns> public static short ReadInt16(IntPtr handle, long address) { return BitConverter.ToInt16(ReadBytes(handle, address, 2), 0); } /// <summary> /// Read a ushort from memory (16-bits). /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <returns></returns> public static ushort ReadUInt16(IntPtr handle, long address) { return BitConverter.ToUInt16(ReadBytes(handle, address, 2), 0); } [Obsolete("Please use ReadInt16")] public static short ReadShort(IntPtr handle, long address) { return BitConverter.ToInt16(ReadBytes(handle, address, 2), 0); } /// <summary> /// Read an integer from the process (32-bits) /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <returns></returns> public static int ReadInt32(IntPtr handle, long address) { return BitConverter.ToInt32(ReadBytes(handle, address, 4), 0); } /// <summary> /// Read an uinteger from the process (32-bits) /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <returns></returns> public static uint ReadUInt32(IntPtr handle, long address) { return BitConverter.ToUInt32(ReadBytes(handle, address, 4), 0); } /// <summary> /// Read an unsigned long from the process (64-bits) /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <returns></returns> public static ulong ReadUInt64(IntPtr handle, long address) { return BitConverter.ToUInt64(ReadBytes(handle, address, 8), 0); } [Obsolete("Please use ReadInt32.")] public static int ReadInt(IntPtr handle, long address) { return BitConverter.ToInt32(ReadBytes(handle, address, 4), 0); } /// <summary> /// Read a 32-bit double from the process /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <returns></returns> public static double ReadDouble(IntPtr handle, long address) { return BitConverter.ToDouble(ReadBytes(handle, address, 8), 0); } /// <summary> /// Read a string from memmory. Splits at 00 and returns first section to avoid junk. Uses default length of 255. Use ReadString(IntPtr handle, long address, int length) to read longer strings, such as the RSA key. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <returns></returns> public static string ReadString(IntPtr handle, long address) { return ReadString(handle, address, 0); } /// <summary> /// Read a string from memmory. Splits at 00 and returns first section to avoid junk. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="length">the length of the bytes to read</param> /// <returns></returns> public static string ReadString(IntPtr handle, long address, uint length) { if (length > 0) { byte[] buffer; buffer = ReadBytes(handle, address, length); return System.Text.ASCIIEncoding.Default.GetString(buffer).Split(new Char())[0]; } else { string s = ""; byte temp = ReadByte(handle, address++); while (temp != 0) { s += (char)temp; temp = ReadByte(handle, address++); } return s; } } /// <summary> /// Write a specified number of bytes to a process. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="bytes"></param> /// <param name="length"></param> /// <returns></returns> public static bool WriteBytes(IntPtr handle, long address, byte[] bytes, uint length) { IntPtr bytesWritten; // Write to memory int result = WinApi.WriteProcessMemory(handle, new IntPtr(address), bytes, length, out bytesWritten); return result != 0; } /// <summary> /// Write an integer (32-bits) to memory. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="value"></param> /// <returns></returns> public static bool WriteInt32(IntPtr handle, long address, int value) { return WriteBytes(handle, address, BitConverter.GetBytes(value), 4); } /// <summary> /// Write an uinteger (32-bits) to memory. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="value"></param> /// <returns></returns> public static bool WriteUInt32(IntPtr handle, long address, uint value) { return WriteBytes(handle, address, BitConverter.GetBytes(value), 4); } /// <summary> /// Write an unsigned long (64-bits) to memory. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="value"></param> /// <returns></returns> public static bool WriteUInt64(IntPtr handle, long address, ulong value) { return WriteBytes(handle, address, BitConverter.GetBytes(value), 8); } /// <summary> /// Write an integer (16-bits) to memory. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="value"></param> /// <returns></returns> public static bool WriteInt16(IntPtr handle, long address, short value) { return WriteBytes(handle, address, BitConverter.GetBytes(value), 2); } /// <summary> /// Write an uinteger (16-bits) to memory. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="value"></param> /// <returns></returns> public static bool WriteUInt16(IntPtr handle, long address, ushort value) { return WriteBytes(handle, address, BitConverter.GetBytes(value), 2); } [Obsolete("Please use WriteInt32.")] public static bool WriteInt(IntPtr handle, long address, int value) { byte[] bytes = BitConverter.GetBytes(value); return WriteBytes(handle, address, bytes, 4); } /// <summary> /// Write a double value to memory. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="value"></param> /// <returns></returns> public static bool WriteDouble(IntPtr handle, long address, double value) { byte[] bytes = BitConverter.GetBytes(value); return WriteBytes(handle, address, bytes, 8); } /// <summary> /// Write a byte to memory. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="value"></param> /// <returns></returns> public static bool WriteByte(IntPtr handle, long address, byte value) { return WriteBytes(handle, address, new byte[] { value }, 1); } /// <summary> /// Write a string to memory without using econding. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="str"></param> /// <returns></returns> public static bool WriteStringNoEncoding(IntPtr handle, long address, string str) { str += '\0'; byte[] bytes = str.ToByteArray(); return WriteBytes(handle, address, bytes, (uint)bytes.Length); } /// <summary> /// Write a string to memory. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="str"></param> /// <returns></returns> public static bool WriteString(IntPtr handle, long address, string str) { str += '\0'; byte[] bytes = System.Text.ASCIIEncoding.Default.GetBytes(str); return WriteBytes(handle, address, bytes, (uint)bytes.Length); } /// <summary> /// Set the RSA key. Different from WriteString because must overcome protection. /// </summary> /// <param name="handle"></param> /// <param name="address"></param> /// <param name="newKey"></param> /// <returns></returns> public static bool WriteRSA(IntPtr handle, long address, string newKey) { IntPtr bytesWritten; int result; WinApi.MemoryProtection oldProtection = 0; System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); byte[] bytes = enc.GetBytes(newKey); // Make it so we can write to the memory block WinApi.VirtualProtectEx( handle, new IntPtr(address), new IntPtr(bytes.Length), WinApi.MemoryProtection.ExecuteReadWrite, ref oldProtection); // Write to memory result = WinApi.WriteProcessMemory(handle, new IntPtr(address), bytes, (uint)bytes.Length, out bytesWritten); // Put the protection back on the memory block WinApi.VirtualProtectEx(handle, new IntPtr(address), new IntPtr(bytes.Length), oldProtection, ref oldProtection); return (result != 0); } } }
// 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.Dynamic.Utils; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using static System.Linq.Expressions.CachedReflectionInfo; namespace System.Linq.Expressions.Compiler { internal partial class LambdaCompiler { private void EmitBlockExpression(Expression expr, CompilationFlags flags) { // emit body Emit((BlockExpression)expr, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsDefaultType)); } private void Emit(BlockExpression node, CompilationFlags flags) { int count = node.ExpressionCount; if (count == 0) { return; } EnterScope(node); CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask; CompilationFlags tailCall = flags & CompilationFlags.EmitAsTailCallMask; for (int index = 0; index < count - 1; index++) { Expression e = node.GetExpression(index); Expression next = node.GetExpression(index + 1); CompilationFlags tailCallFlag; if (tailCall != CompilationFlags.EmitAsNoTail) { var g = next as GotoExpression; if (g != null && (g.Value == null || !Significant(g.Value)) && ReferenceLabel(g.Target).CanReturn) { // Since tail call flags are not passed into EmitTryExpression, CanReturn means the goto will be emitted // as Ret. Therefore we can emit the current expression with tail call. tailCallFlag = CompilationFlags.EmitAsTail; } else { // In the middle of the block. // We may do better here by marking it as Tail if the following expressions are not going to emit any IL. tailCallFlag = CompilationFlags.EmitAsMiddle; } } else { tailCallFlag = CompilationFlags.EmitAsNoTail; } flags = UpdateEmitAsTailCallFlag(flags, tailCallFlag); EmitExpressionAsVoid(e, flags); } // if the type of Block it means this is not a Comma // so we will force the last expression to emit as void. // We don't need EmitAsType flag anymore, should only pass // the EmitTailCall field in flags to emitting the last expression. if (emitAs == CompilationFlags.EmitAsVoidType || node.Type == typeof(void)) { EmitExpressionAsVoid(node.GetExpression(count - 1), tailCall); } else { EmitExpressionAsType(node.GetExpression(count - 1), node.Type, tailCall); } ExitScope(node); } private void EnterScope(object node) { if (HasVariables(node) && (_scope.MergedScopes == null || !_scope.MergedScopes.Contains(node))) { CompilerScope scope; if (!_tree.Scopes.TryGetValue(node, out scope)) { // // Very often, we want to compile nodes as reductions // rather than as IL, but usually they need to allocate // some IL locals. To support this, we allow emitting a // BlockExpression that was not bound by VariableBinder. // This works as long as the variables are only used // locally -- i.e. not closed over. // // User-created blocks will never hit this case; only our // internally reduced nodes will. // scope = new CompilerScope(node, false) { NeedsClosure = _scope.NeedsClosure }; } _scope = scope.Enter(this, _scope); Debug.Assert(_scope.Node == node); } } private static bool HasVariables(object node) { var block = node as BlockExpression; if (block != null) { return block.Variables.Count > 0; } return ((CatchBlock)node).Variable != null; } private void ExitScope(object node) { if (_scope.Node == node) { _scope = _scope.Exit(); } } private void EmitDefaultExpression(Expression expr) { var node = (DefaultExpression)expr; if (node.Type != typeof(void)) { // emit default(T) _ilg.EmitDefault(node.Type, this); } } private void EmitLoopExpression(Expression expr) { LoopExpression node = (LoopExpression)expr; PushLabelBlock(LabelScopeKind.Statement); LabelInfo breakTarget = DefineLabel(node.BreakLabel); LabelInfo continueTarget = DefineLabel(node.ContinueLabel); continueTarget.MarkWithEmptyStack(); EmitExpressionAsVoid(node.Body); _ilg.Emit(OpCodes.Br, continueTarget.Label); PopLabelBlock(LabelScopeKind.Statement); breakTarget.MarkWithEmptyStack(); } #region SwitchExpression private void EmitSwitchExpression(Expression expr, CompilationFlags flags) { SwitchExpression node = (SwitchExpression)expr; if (node.Cases.Count == 0) { // Emit the switch value in case it has side-effects, but as void // since the value is ignored. EmitExpressionAsVoid(node.SwitchValue); // Now if there is a default body, it happens unconditionally. if (node.DefaultBody != null) { EmitExpressionAsType(node.DefaultBody, node.Type, flags); } else { // If there are no cases and no default then the type must be void. // Assert that earlier validation caught any exceptions to that. Debug.Assert(node.Type == typeof(void)); } return; } // Try to emit it as an IL switch. Works for integer types. if (TryEmitSwitchInstruction(node, flags)) { return; } // Try to emit as a hashtable lookup. Works for strings. if (TryEmitHashtableSwitch(node, flags)) { return; } // // Fall back to a series of tests. We need to IL gen instead of // transform the tree to avoid stack overflow on a big switch. // ParameterExpression switchValue = Expression.Parameter(node.SwitchValue.Type, "switchValue"); ParameterExpression testValue = Expression.Parameter(GetTestValueType(node), "testValue"); _scope.AddLocal(this, switchValue); _scope.AddLocal(this, testValue); EmitExpression(node.SwitchValue); _scope.EmitSet(switchValue); // Emit tests var labels = new Label[node.Cases.Count]; var isGoto = new bool[node.Cases.Count]; for (int i = 0, n = node.Cases.Count; i < n; i++) { DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]); foreach (Expression test in node.Cases[i].TestValues) { // Pull the test out into a temp so it runs on the same // stack as the switch. This simplifies spilling. EmitExpression(test); _scope.EmitSet(testValue); Debug.Assert(TypeUtils.AreReferenceAssignable(testValue.Type, test.Type)); EmitExpressionAndBranch(true, Expression.Equal(switchValue, testValue, false, node.Comparison), labels[i]); } } // Define labels Label end = _ilg.DefineLabel(); Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel(); // Emit the case and default bodies EmitSwitchCases(node, labels, isGoto, @default, end, flags); } /// <summary> /// Gets the common test value type of the SwitchExpression. /// </summary> private static Type GetTestValueType(SwitchExpression node) { if (node.Comparison == null) { // If we have no comparison, all right side types must be the // same. return node.Cases[0].TestValues[0].Type; } // Otherwise, get the type from the method. Type result = node.Comparison.GetParametersCached()[1].ParameterType.GetNonRefType(); if (node.IsLifted) { result = result.GetNullableType(); } return result; } private sealed class SwitchLabel { internal readonly decimal Key; internal readonly Label Label; // Boxed version of Key, preserving the original type. internal readonly object Constant; internal SwitchLabel(decimal key, object @constant, Label label) { Key = key; Constant = @constant; Label = label; } } private sealed class SwitchInfo { internal readonly SwitchExpression Node; internal readonly LocalBuilder Value; internal readonly Label Default; internal readonly Type Type; internal readonly bool IsUnsigned; internal readonly bool Is64BitSwitch; internal SwitchInfo(SwitchExpression node, LocalBuilder value, Label @default) { Node = node; Value = value; Default = @default; Type = Node.SwitchValue.Type; IsUnsigned = Type.IsUnsigned(); TypeCode code = Type.GetTypeCode(); Is64BitSwitch = code == TypeCode.UInt64 || code == TypeCode.Int64; } } private static bool FitsInBucket(List<SwitchLabel> buckets, decimal key, int count) { Debug.Assert(key > buckets[buckets.Count - 1].Key); decimal jumpTableSlots = key - buckets[0].Key + 1; if (jumpTableSlots > int.MaxValue) { return false; } // density must be > 50% return (buckets.Count + count) * 2 > jumpTableSlots; } private static void MergeBuckets(List<List<SwitchLabel>> buckets) { while (buckets.Count > 1) { List<SwitchLabel> first = buckets[buckets.Count - 2]; List<SwitchLabel> second = buckets[buckets.Count - 1]; if (!FitsInBucket(first, second[second.Count - 1].Key, second.Count)) { return; } // Merge them first.AddRange(second); buckets.RemoveAt(buckets.Count - 1); } } // Add key to a new or existing bucket private static void AddToBuckets(List<List<SwitchLabel>> buckets, SwitchLabel key) { if (buckets.Count > 0) { List<SwitchLabel> last = buckets[buckets.Count - 1]; if (FitsInBucket(last, key.Key, 1)) { last.Add(key); // we might be able to merge now MergeBuckets(buckets); return; } } // else create a new bucket buckets.Add(new List<SwitchLabel> { key }); } // Determines if the type is an integer we can switch on. private static bool CanOptimizeSwitchType(Type valueType) { // enums & char are allowed switch (valueType.GetTypeCode()) { case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Char: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return true; default: return false; } } // Tries to emit switch as a jmp table private bool TryEmitSwitchInstruction(SwitchExpression node, CompilationFlags flags) { // If we have a comparison, bail if (node.Comparison != null) { return false; } // Make sure the switch value type and the right side type // are types we can optimize Type type = node.SwitchValue.Type; if (!CanOptimizeSwitchType(type) || !TypeUtils.AreEquivalent(type, node.Cases[0].TestValues[0].Type)) { return false; } // Make sure all test values are constant, or we can't emit the // jump table. if (!node.Cases.All(c => c.TestValues.All(t => t is ConstantExpression))) { return false; } // // We can emit the optimized switch, let's do it. // // Build target labels, collect keys. var labels = new Label[node.Cases.Count]; var isGoto = new bool[node.Cases.Count]; var uniqueKeys = new HashSet<decimal>(); var keys = new List<SwitchLabel>(); for (int i = 0; i < node.Cases.Count; i++) { DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]); foreach (ConstantExpression test in node.Cases[i].TestValues) { // Guaranteed to work thanks to CanOptimizeSwitchType. // // Use decimal because it can hold Int64 or UInt64 without // precision loss or signed/unsigned conversions. decimal key = ConvertSwitchValue(test.Value); // Only add each key once. If it appears twice, it's // allowed, but can't be reached. if (uniqueKeys.Add(key)) { keys.Add(new SwitchLabel(key, test.Value, labels[i])); } } } // Sort the keys, and group them into buckets. keys.Sort((x, y) => Math.Sign(x.Key - y.Key)); var buckets = new List<List<SwitchLabel>>(); foreach (SwitchLabel key in keys) { AddToBuckets(buckets, key); } // Emit the switchValue LocalBuilder value = GetLocal(node.SwitchValue.Type); EmitExpression(node.SwitchValue); _ilg.Emit(OpCodes.Stloc, value); // Create end label, and default label if needed Label end = _ilg.DefineLabel(); Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel(); // Emit the switch var info = new SwitchInfo(node, value, @default); EmitSwitchBuckets(info, buckets, 0, buckets.Count - 1); // Emit the case bodies and default EmitSwitchCases(node, labels, isGoto, @default, end, flags); FreeLocal(value); return true; } private static decimal ConvertSwitchValue(object value) { if (value is char) { return (int)(char)value; } return Convert.ToDecimal(value, CultureInfo.InvariantCulture); } /// <summary> /// Creates the label for this case. /// Optimization: if the body is just a goto, and we can branch /// to it, put the goto target directly in the jump table. /// </summary> private void DefineSwitchCaseLabel(SwitchCase @case, out Label label, out bool isGoto) { var jump = @case.Body as GotoExpression; // if it's a goto with no value if (jump != null && jump.Value == null) { // Reference the label from the switch. This will cause us to // analyze the jump target and determine if it is safe. LabelInfo jumpInfo = ReferenceLabel(jump.Target); // If we have are allowed to emit the "branch" opcode, then we // can jump directly there from the switch's jump table. // (Otherwise, we need to emit the goto later as a "leave".) if (jumpInfo.CanBranch) { label = jumpInfo.Label; isGoto = true; return; } } // otherwise, just define a new label label = _ilg.DefineLabel(); isGoto = false; } private void EmitSwitchCases(SwitchExpression node, Label[] labels, bool[] isGoto, Label @default, Label end, CompilationFlags flags) { // Jump to default (to handle the fallthrough case) _ilg.Emit(OpCodes.Br, @default); // Emit the cases for (int i = 0, n = node.Cases.Count; i < n; i++) { // If the body is a goto, we already emitted an optimized // branch directly to it. No need to emit anything else. if (isGoto[i]) { continue; } _ilg.MarkLabel(labels[i]); EmitExpressionAsType(node.Cases[i].Body, node.Type, flags); // Last case doesn't need branch if (node.DefaultBody != null || i < n - 1) { if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) { //The switch case is at the tail of the lambda so //it is safe to emit a Ret. _ilg.Emit(OpCodes.Ret); } else { _ilg.Emit(OpCodes.Br, end); } } } // Default value if (node.DefaultBody != null) { _ilg.MarkLabel(@default); EmitExpressionAsType(node.DefaultBody, node.Type, flags); } _ilg.MarkLabel(end); } private void EmitSwitchBuckets(SwitchInfo info, List<List<SwitchLabel>> buckets, int first, int last) { for (;;) { if (first == last) { EmitSwitchBucket(info, buckets[first]); return; } // Split the buckets into two groups, and use an if test to find // the right bucket. This ensures we'll only need O(lg(B)) tests // where B is the number of buckets int mid = (int)(((long)first + last + 1) / 2); if (first == mid - 1) { EmitSwitchBucket(info, buckets[first]); } else { // If the first half contains more than one, we need to emit an // explicit guard Label secondHalf = _ilg.DefineLabel(); _ilg.Emit(OpCodes.Ldloc, info.Value); EmitConstant(buckets[mid - 1].Last().Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, secondHalf); EmitSwitchBuckets(info, buckets, first, mid - 1); _ilg.MarkLabel(secondHalf); } first = mid; } } private void EmitSwitchBucket(SwitchInfo info, List<SwitchLabel> bucket) { // No need for switch if we only have one value if (bucket.Count == 1) { _ilg.Emit(OpCodes.Ldloc, info.Value); EmitConstant(bucket[0].Constant); _ilg.Emit(OpCodes.Beq, bucket[0].Label); return; } // // If we're switching off of Int64/UInt64, we need more guards here // because we'll have to narrow the switch value to an Int32, and // we can't do that unless the value is in the right range. // Label? after = null; if (info.Is64BitSwitch) { after = _ilg.DefineLabel(); _ilg.Emit(OpCodes.Ldloc, info.Value); EmitConstant(bucket.Last().Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, after.Value); _ilg.Emit(OpCodes.Ldloc, info.Value); EmitConstant(bucket[0].Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Blt_Un : OpCodes.Blt, after.Value); } _ilg.Emit(OpCodes.Ldloc, info.Value); // Normalize key decimal key = bucket[0].Key; if (key != 0) { EmitConstant(bucket[0].Constant); _ilg.Emit(OpCodes.Sub); } if (info.Is64BitSwitch) { _ilg.Emit(OpCodes.Conv_I4); } // Collect labels int len = (int)(bucket[bucket.Count - 1].Key - bucket[0].Key + 1); Label[] jmpLabels = new Label[len]; // Initialize all labels to the default int slot = 0; foreach (SwitchLabel label in bucket) { while (key++ != label.Key) { jmpLabels[slot++] = info.Default; } jmpLabels[slot++] = label.Label; } // check we used all keys and filled all slots Debug.Assert(key == bucket[bucket.Count - 1].Key + 1); Debug.Assert(slot == jmpLabels.Length); // Finally, emit the switch instruction _ilg.Emit(OpCodes.Switch, jmpLabels); if (info.Is64BitSwitch) { _ilg.MarkLabel(after.Value); } } private bool TryEmitHashtableSwitch(SwitchExpression node, CompilationFlags flags) { // If we have a comparison other than string equality, bail if (node.Comparison != String_op_Equality_String_String && node.Comparison != String_Equals_String_String) { return false; } // All test values must be constant. int tests = 0; foreach (SwitchCase c in node.Cases) { foreach (Expression t in c.TestValues) { if (!(t is ConstantExpression)) { return false; } tests++; } } // Must have >= 7 labels for it to be worth it. if (tests < 7) { return false; } // If we're in a DynamicMethod, we could just build the dictionary // immediately. But that would cause the two code paths to be more // different than they really need to be. var initializers = new List<ElementInit>(tests); var cases = new ArrayBuilder<SwitchCase>(node.Cases.Count); int nullCase = -1; MethodInfo add = DictionaryOfStringInt32_Add_String_Int32; for (int i = 0, n = node.Cases.Count; i < n; i++) { foreach (ConstantExpression t in node.Cases[i].TestValues) { if (t.Value != null) { initializers.Add(Expression.ElementInit(add, new TrueReadOnlyCollection<Expression>(t, Utils.Constant(i)))); } else { nullCase = i; } } cases.UncheckedAdd(Expression.SwitchCase(node.Cases[i].Body, new TrueReadOnlyCollection<Expression>(Utils.Constant(i)))); } // Create the field to hold the lazily initialized dictionary MemberExpression dictField = CreateLazyInitializedField<Dictionary<string, int>>("dictionarySwitch"); // If we happen to initialize it twice (multithreaded case), it's // not the end of the world. The C# compiler does better here by // emitting a volatile access to the field. Expression dictInit = Expression.Condition( Expression.Equal(dictField, Expression.Constant(null, dictField.Type)), Expression.Assign( dictField, Expression.ListInit( Expression.New( DictionaryOfStringInt32_Ctor_Int32, new TrueReadOnlyCollection<Expression>( Utils.Constant(initializers.Count) ) ), initializers ) ), dictField ); // // Create a tree like: // // switchValue = switchValueExpression; // if (switchValue == null) { // switchIndex = nullCase; // } else { // if (_dictField == null) { // _dictField = new Dictionary<string, int>(count) { { ... }, ... }; // } // if (!_dictField.TryGetValue(switchValue, out switchIndex)) { // switchIndex = -1; // } // } // switch (switchIndex) { // case 0: ... // case 1: ... // ... // default: // } // ParameterExpression switchValue = Expression.Variable(typeof(string), "switchValue"); ParameterExpression switchIndex = Expression.Variable(typeof(int), "switchIndex"); BlockExpression reduced = Expression.Block( new TrueReadOnlyCollection<ParameterExpression>(switchIndex, switchValue), new TrueReadOnlyCollection<Expression>( Expression.Assign(switchValue, node.SwitchValue), Expression.IfThenElse( Expression.Equal(switchValue, Expression.Constant(null, typeof(string))), Expression.Assign(switchIndex, Utils.Constant(nullCase)), Expression.IfThenElse( Expression.Call(dictInit, "TryGetValue", null, switchValue, switchIndex), Utils.Empty, Expression.Assign(switchIndex, Utils.Constant(-1)) ) ), Expression.Switch(node.Type, switchIndex, node.DefaultBody, null, cases.ToReadOnly()) ) ); EmitExpression(reduced, flags); return true; } #endregion private void CheckRethrow() { // Rethrow is only valid inside a catch. for (LabelScopeInfo j = _labelBlock; j != null; j = j.Parent) { if (j.Kind == LabelScopeKind.Catch) { return; } else if (j.Kind == LabelScopeKind.Finally) { // Rethrow from inside finally is not verifiable break; } } throw Error.RethrowRequiresCatch(); } #region TryStatement private void CheckTry() { // Try inside a filter is not verifiable for (LabelScopeInfo j = _labelBlock; j != null; j = j.Parent) { if (j.Kind == LabelScopeKind.Filter) { throw Error.TryNotAllowedInFilter(); } } } private void EmitSaveExceptionOrPop(CatchBlock cb) { if (cb.Variable != null) { // If the variable is present, store the exception // in the variable. _scope.EmitSet(cb.Variable); } else { // Otherwise, pop it off the stack. _ilg.Emit(OpCodes.Pop); } } private void EmitTryExpression(Expression expr) { var node = (TryExpression)expr; CheckTry(); //****************************************************************** // 1. ENTERING TRY //****************************************************************** PushLabelBlock(LabelScopeKind.Try); _ilg.BeginExceptionBlock(); //****************************************************************** // 2. Emit the try statement body //****************************************************************** EmitExpression(node.Body); Type tryType = node.Type; LocalBuilder value = null; if (tryType != typeof(void)) { //store the value of the try body value = GetLocal(tryType); _ilg.Emit(OpCodes.Stloc, value); } //****************************************************************** // 3. Emit the catch blocks //****************************************************************** foreach (CatchBlock cb in node.Handlers) { PushLabelBlock(LabelScopeKind.Catch); // Begin the strongly typed exception block if (cb.Filter == null) { _ilg.BeginCatchBlock(cb.Test); } else { _ilg.BeginExceptFilterBlock(); } EnterScope(cb); EmitCatchStart(cb); // // Emit the catch block body // EmitExpression(cb.Body); if (tryType != typeof(void)) { //store the value of the catch block body _ilg.Emit(OpCodes.Stloc, value); } ExitScope(cb); PopLabelBlock(LabelScopeKind.Catch); } //****************************************************************** // 4. Emit the finally block //****************************************************************** if (node.Finally != null || node.Fault != null) { PushLabelBlock(LabelScopeKind.Finally); if (node.Finally != null) { _ilg.BeginFinallyBlock(); } else { _ilg.BeginFaultBlock(); } // Emit the body EmitExpressionAsVoid(node.Finally ?? node.Fault); _ilg.EndExceptionBlock(); PopLabelBlock(LabelScopeKind.Finally); } else { _ilg.EndExceptionBlock(); } if (tryType != typeof(void)) { _ilg.Emit(OpCodes.Ldloc, value); FreeLocal(value); } PopLabelBlock(LabelScopeKind.Try); } /// <summary> /// Emits the start of a catch block. The exception value that is provided by the /// CLR is stored in the variable specified by the catch block or popped if no /// variable is provided. /// </summary> private void EmitCatchStart(CatchBlock cb) { if (cb.Filter == null) { EmitSaveExceptionOrPop(cb); return; } // emit filter block. Filter blocks are untyped so we need to do // the type check ourselves. Label endFilter = _ilg.DefineLabel(); Label rightType = _ilg.DefineLabel(); // skip if it's not our exception type, but save // the exception if it is so it's available to the // filter _ilg.Emit(OpCodes.Isinst, cb.Test); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Brtrue, rightType); _ilg.Emit(OpCodes.Pop); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br, endFilter); // it's our type, save it and emit the filter. _ilg.MarkLabel(rightType); EmitSaveExceptionOrPop(cb); PushLabelBlock(LabelScopeKind.Filter); EmitExpression(cb.Filter); PopLabelBlock(LabelScopeKind.Filter); // begin the catch, clear the exception, we've // already saved it _ilg.MarkLabel(endFilter); _ilg.BeginCatchBlock(exceptionType: null); _ilg.Emit(OpCodes.Pop); } #endregion } }
using System; using NBitcoin.BouncyCastle.Security; namespace NBitcoin.BouncyCastle.Crypto.Paddings { /** * A wrapper class that allows block ciphers to be used to process data in * a piecemeal fashion with padding. The PaddedBufferedBlockCipher * outputs a block only when the buffer is full and more data is being added, * or on a doFinal (unless the current block in the buffer is a pad block). * The default padding mechanism used is the one outlined in Pkcs5/Pkcs7. */ internal class PaddedBufferedBlockCipher : BufferedBlockCipher { private readonly IBlockCipherPadding padding; /** * Create a buffered block cipher with the desired padding. * * @param cipher the underlying block cipher this buffering object wraps. * @param padding the padding type. */ public PaddedBufferedBlockCipher( IBlockCipher cipher, IBlockCipherPadding padding) { this.cipher = cipher; this.padding = padding; buf = new byte[cipher.GetBlockSize()]; bufOff = 0; } /** * Create a buffered block cipher Pkcs7 padding * * @param cipher the underlying block cipher this buffering object wraps. */ public PaddedBufferedBlockCipher( IBlockCipher cipher) : this(cipher, new Pkcs7Padding()) { } /** * initialise the cipher. * * @param forEncryption if true the cipher is initialised for * encryption, if false for decryption. * @param param the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public override void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; SecureRandom initRandom = null; Reset(); padding.Init(initRandom); cipher.Init(forEncryption, parameters); } /** * return the minimum size of the output buffer required for an update * plus a doFinal with an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update and doFinal * with len bytes of input. */ public override int GetOutputSize( int length) { int total = length + bufOff; int leftOver = total % buf.Length; if(leftOver == 0) { if(forEncryption) { return total + buf.Length; } return total; } return total - leftOver + buf.Length; } /** * return the size of the output buffer required for an update * an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update * with len bytes of input. */ public override int GetUpdateOutputSize( int length) { int total = length + bufOff; int leftOver = total % buf.Length; if(leftOver == 0) { return total - buf.Length; } return total - leftOver; } /** * process a single byte, producing an output block if necessary. * * @param in the input byte. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessByte( byte input, byte[] output, int outOff) { int resultLen = 0; if(bufOff == buf.Length) { resultLen = cipher.ProcessBlock(buf, 0, output, outOff); bufOff = 0; } buf[bufOff++] = input; return resultLen; } /** * process an array of bytes, producing output if necessary. * * @param in the input byte array. * @param inOff the offset at which the input data starts. * @param len the number of bytes to be copied out of the input array. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessBytes( byte[] input, int inOff, int length, byte[] output, int outOff) { if(length < 0) { throw new ArgumentException("Can't have a negative input length!"); } int blockSize = GetBlockSize(); int outLength = GetUpdateOutputSize(length); if(outLength > 0) { Check.OutputLength(output, outOff, outLength, "output buffer too short"); } int resultLen = 0; int gapLen = buf.Length - bufOff; if(length > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); resultLen += cipher.ProcessBlock(buf, 0, output, outOff); bufOff = 0; length -= gapLen; inOff += gapLen; while(length > buf.Length) { resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen); length -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, buf, bufOff, length); bufOff += length; return resultLen; } /** * Process the last block in the buffer. If the buffer is currently * full and padding needs to be added a call to doFinal will produce * 2 * GetBlockSize() bytes. * * @param out the array the block currently being held is copied into. * @param outOff the offset at which the copying starts. * @return the number of output bytes copied to out. * @exception DataLengthException if there is insufficient space in out for * the output or we are decrypting and the input is not block size aligned. * @exception InvalidOperationException if the underlying cipher is not * initialised. * @exception InvalidCipherTextException if padding is expected and not found. */ public override int DoFinal( byte[] output, int outOff) { int blockSize = cipher.GetBlockSize(); int resultLen = 0; if(forEncryption) { if(bufOff == blockSize) { if((outOff + 2 * blockSize) > output.Length) { Reset(); throw new OutputLengthException("output buffer too short"); } resultLen = cipher.ProcessBlock(buf, 0, output, outOff); bufOff = 0; } padding.AddPadding(buf, bufOff); resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen); Reset(); } else { if(bufOff == blockSize) { resultLen = cipher.ProcessBlock(buf, 0, buf, 0); bufOff = 0; } else { Reset(); throw new DataLengthException("last block incomplete in decryption"); } try { resultLen -= padding.PadCount(buf); Array.Copy(buf, 0, output, outOff, resultLen); } finally { Reset(); } } return resultLen; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Domain.Uow; using Abp.MultiTenancy; using Abp.Runtime.Caching.Configuration; using Abp.Runtime.Caching.Memory; using Abp.Runtime.Remoting; using Abp.Runtime.Session; using Abp.TestBase.Runtime.Session; using Abp.Tests.MultiTenancy; using Castle.MicroKernel.Registration; using NSubstitute; using Shouldly; using Xunit; namespace Abp.Tests.Configuration { public class SettingManager_Tests : TestBaseWithLocalIocManager { private enum MyEnumSettingType { Setting1 = 0, Setting2 = 1, } private const string MyAppLevelSetting = "MyAppLevelSetting"; private const string MyAllLevelsSetting = "MyAllLevelsSetting"; private const string MyNotInheritedSetting = "MyNotInheritedSetting"; private const string MyEnumTypeSetting = "MyEnumTypeSetting"; private const string MyEncryptedSetting = "MyEncryptedSetting"; private SettingManager CreateSettingManager(bool multiTenancyIsEnabled = true) { return new SettingManager( CreateMockSettingDefinitionManager(), new AbpMemoryCacheManager( new CachingConfiguration(Substitute.For<IAbpStartupConfiguration>()) ), new MultiTenancyConfig { IsEnabled = multiTenancyIsEnabled }, new TestTenantStore(), new SettingEncryptionService(new SettingsConfiguration()), Substitute.For<IUnitOfWorkManager>()); } [Fact] public async Task Should_Get_Default_Values_With_No_Store_And_No_Session() { var settingManager = CreateSettingManager(); (await settingManager.GetSettingValueAsync<int>(MyAppLevelSetting)).ShouldBe(42); (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)).ShouldBe("application level default value"); } [Fact] public async Task Should_Get_Stored_Application_Value_With_No_Session() { var settingManager = CreateSettingManager(); settingManager.SettingStore = new MemorySettingStore(); (await settingManager.GetSettingValueAsync<int>(MyAppLevelSetting)).ShouldBe(48); (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)).ShouldBe("application level stored value"); } [Fact] public async Task Should_Get_Correct_Values() { var session = CreateTestAbpSession(); var settingManager = CreateSettingManager(); settingManager.SettingStore = new MemorySettingStore(); settingManager.AbpSession = session; session.TenantId = 1; //Inherited setting session.UserId = 1; (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)).ShouldBe("user 1 stored value"); session.UserId = 2; (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)).ShouldBe("user 2 stored value"); session.UserId = 3; (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)) .ShouldBe("tenant 1 stored value"); //Because no user value in the store session.TenantId = 3; session.UserId = 3; (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)) .ShouldBe("application level stored value"); //Because no user and tenant value in the store //Not inherited setting session.TenantId = 1; session.UserId = 1; (await settingManager.GetSettingValueForApplicationAsync(MyNotInheritedSetting)).ShouldBe( "application value"); (await settingManager.GetSettingValueForTenantAsync(MyNotInheritedSetting, session.TenantId.Value)) .ShouldBe("default-value"); (await settingManager.GetSettingValueAsync(MyNotInheritedSetting)).ShouldBe("default-value"); (await settingManager.GetSettingValueAsync<MyEnumSettingType>(MyEnumTypeSetting)).ShouldBe(MyEnumSettingType .Setting1); } [Fact] public async Task Should_Get_All_Values() { var settingManager = CreateSettingManager(); settingManager.SettingStore = new MemorySettingStore(); (await settingManager.GetAllSettingValuesAsync()).Count.ShouldBe(5); (await settingManager.GetAllSettingValuesForApplicationAsync()).Count.ShouldBe(4); (await settingManager.GetAllSettingValuesForTenantAsync(1)).Count.ShouldBe(2); (await settingManager.GetAllSettingValuesForTenantAsync(1)).Count.ShouldBe(2); (await settingManager.GetAllSettingValuesForTenantAsync(2)).Count.ShouldBe(0); (await settingManager.GetAllSettingValuesForTenantAsync(3)).Count.ShouldBe(0); (await settingManager.GetAllSettingValuesForUserAsync(new UserIdentifier(1, 1))).Count.ShouldBe(1); (await settingManager.GetAllSettingValuesForUserAsync(new UserIdentifier(1, 2))).Count.ShouldBe(2); (await settingManager.GetAllSettingValuesForUserAsync(new UserIdentifier(1, 3))).Count.ShouldBe(0); } [Fact] public async Task Should_Change_Setting_Values() { var session = CreateTestAbpSession(); var settingManager = CreateSettingManager(); settingManager.SettingStore = new MemorySettingStore(); settingManager.AbpSession = session; //Application level changes await settingManager.ChangeSettingForApplicationAsync(MyAppLevelSetting, "53"); await settingManager.ChangeSettingForApplicationAsync(MyAppLevelSetting, "54"); await settingManager.ChangeSettingForApplicationAsync(MyAllLevelsSetting, "application level changed value"); (await settingManager.SettingStore.GetSettingOrNullAsync(null, null, MyAppLevelSetting)).Value .ShouldBe("54"); (await settingManager.GetSettingValueAsync<int>(MyAppLevelSetting)).ShouldBe(54); (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)).ShouldBe("application level changed value"); //Tenant level changes session.TenantId = 1; await settingManager.ChangeSettingForTenantAsync(1, MyAllLevelsSetting, "tenant 1 changed value"); (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)).ShouldBe("tenant 1 changed value"); //User level changes session.UserId = 1; await settingManager.ChangeSettingForUserAsync(1, MyAllLevelsSetting, "user 1 changed value"); (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)).ShouldBe("user 1 changed value"); } [Fact] public async Task Should_Delete_Setting_Values_On_Default_Value() { var session = CreateTestAbpSession(); var store = new MemorySettingStore(); var settingManager = CreateSettingManager(); settingManager.SettingStore = store; settingManager.AbpSession = session; session.TenantId = 1; session.UserId = 1; //We can get user's personal stored value (await store.GetSettingOrNullAsync(1, 1, MyAllLevelsSetting)).ShouldNotBe(null); (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)).ShouldBe("user 1 stored value"); //This will delete setting for the user since it's same as tenant's setting value await settingManager.ChangeSettingForUserAsync(1, MyAllLevelsSetting, "tenant 1 stored value"); (await store.GetSettingOrNullAsync(1, 1, MyAllLevelsSetting)).ShouldBe(null); //We can get tenant's setting value (await store.GetSettingOrNullAsync(1, null, MyAllLevelsSetting)).ShouldNotBe(null); (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)).ShouldBe("tenant 1 stored value"); //This will delete setting for tenant since it's same as application's setting value await settingManager.ChangeSettingForTenantAsync(1, MyAllLevelsSetting, "application level stored value"); (await store.GetSettingOrNullAsync(1, 1, MyAllLevelsSetting)).ShouldBe(null); //We can get application's value (await store.GetSettingOrNullAsync(null, null, MyAllLevelsSetting)).ShouldNotBe(null); (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)).ShouldBe("application level stored value"); //This will delete setting for application since it's same as the default value of the setting await settingManager.ChangeSettingForApplicationAsync(MyAllLevelsSetting, "application level default value"); (await store.GetSettingOrNullAsync(null, null, MyAllLevelsSetting)).ShouldBe(null); //Now, there is no setting value, default value should return (await settingManager.GetSettingValueAsync(MyAllLevelsSetting)).ShouldBe("application level default value"); } [Fact] public async Task Should_Save_Application_Level_Setting_As_Tenant_Setting_When_Multi_Tenancy_Is_Disabled() { // Arrange var session = CreateTestAbpSession(multiTenancyIsEnabled: false); var settingManager = CreateSettingManager(multiTenancyIsEnabled: false); settingManager.SettingStore = new MemorySettingStore(); settingManager.AbpSession = session; // Act await settingManager.ChangeSettingForApplicationAsync(MyAllLevelsSetting, "53"); // Assert var value = await settingManager.GetSettingValueAsync(MyAllLevelsSetting); value.ShouldBe("53"); } [Fact] public async Task Should_Get_Tenant_Setting_For_Application_Level_Setting_When_Multi_Tenancy_Is_Disabled() { // Arrange var session = CreateTestAbpSession(multiTenancyIsEnabled: false); var settingManager = CreateSettingManager(multiTenancyIsEnabled: false); settingManager.SettingStore = new MemorySettingStore(); settingManager.AbpSession = session; // Act await settingManager.ChangeSettingForApplicationAsync(MyAllLevelsSetting, "53"); // Assert var value = await settingManager.GetSettingValueForApplicationAsync(MyAllLevelsSetting); value.ShouldBe("53"); } [Fact] public async Task Should_Change_Setting_Value_When_Multi_Tenancy_Is_Disabled() { // Arrange var session = CreateTestAbpSession(multiTenancyIsEnabled: false); var settingManager = CreateSettingManager(multiTenancyIsEnabled: false); settingManager.SettingStore = new MemorySettingStore(); settingManager.AbpSession = session; //change setting value with "B" await settingManager.ChangeSettingForApplicationAsync(MyAppLevelSetting, "B"); // it's ok (await settingManager.GetSettingValueForApplicationAsync(MyAppLevelSetting)).ShouldBe("B"); //change setting with same value "B" again, await settingManager.ChangeSettingForApplicationAsync(MyAppLevelSetting, "B"); //but was "A" ,that's wrong (await settingManager.GetSettingValueForApplicationAsync(MyAppLevelSetting)).ShouldBe("B"); } [Fact] public async Task Should_Get_Encrypted_Setting_Value() { var session = CreateTestAbpSession(); var settingManager = CreateSettingManager(); settingManager.SettingStore = new MemorySettingStore(); settingManager.AbpSession = session; session.TenantId = 1; // User setting session.UserId = 2; (await settingManager.GetSettingValueAsync(MyEncryptedSetting)).ShouldBe("user_setting"); // Tenant setting session.UserId = null; (await settingManager.GetSettingValueAsync(MyEncryptedSetting)).ShouldBe("tenant_setting"); // App setting session.TenantId = null; (await settingManager.GetSettingValueAsync(MyEncryptedSetting)).ShouldBe("app_setting"); } [Fact] public async Task Should_Set_Encrypted_Setting_Value() { var session = CreateTestAbpSession(); var settingManager = CreateSettingManager(); settingManager.SettingStore = new MemorySettingStore(); settingManager.AbpSession = session; session.TenantId = 1; // User setting session.UserId = 2; await settingManager.ChangeSettingForUserAsync(session.ToUserIdentifier(), MyEncryptedSetting, "user_123qwe"); var settingValue = await settingManager.SettingStore.GetSettingOrNullAsync( session.TenantId, session.UserId, MyEncryptedSetting ); settingValue.Value.ShouldBe("oKPqQDCAHhz+AEnl/r0fsw=="); // Tenant setting session.UserId = null; await settingManager.ChangeSettingForTenantAsync(session.GetTenantId(), MyEncryptedSetting, "tenant_123qwe"); settingValue = await settingManager.SettingStore.GetSettingOrNullAsync( session.TenantId, session.UserId, MyEncryptedSetting ); settingValue.Value.ShouldBe("YX+MTwbuOwXgL7tnKw+oxw=="); // App setting session.TenantId = null; await settingManager.ChangeSettingForApplicationAsync(MyEncryptedSetting, "app_123qwe"); settingValue = await settingManager.SettingStore.GetSettingOrNullAsync( session.TenantId, session.UserId, MyEncryptedSetting ); settingValue.Value.ShouldBe("EOi2wcQt1pi1K4qYycBBbg=="); } [Fact] public async Task Should_Get_Changed_Encrypted_Setting_Value() { var session = CreateTestAbpSession(); var settingManager = CreateSettingManager(); settingManager.SettingStore = new MemorySettingStore(); settingManager.AbpSession = session; session.TenantId = 1; // User setting session.UserId = 2; await settingManager.ChangeSettingForUserAsync( session.ToUserIdentifier(), MyEncryptedSetting, "new_user_setting" ); var settingValue = await settingManager.GetSettingValueAsync(MyEncryptedSetting); settingValue.ShouldBe("new_user_setting"); // Tenant Setting session.UserId = null; await settingManager.ChangeSettingForTenantAsync( session.GetTenantId(), MyEncryptedSetting, "new_tenant_setting" ); settingValue = await settingManager.GetSettingValueAsync(MyEncryptedSetting); settingValue.ShouldBe("new_tenant_setting"); // App Setting session.TenantId = null; await settingManager.ChangeSettingForApplicationAsync( MyEncryptedSetting, "new_app_setting" ); settingValue = await settingManager.GetSettingValueAsync(MyEncryptedSetting); settingValue.ShouldBe("new_app_setting"); } private static TestAbpSession CreateTestAbpSession(bool multiTenancyIsEnabled = true) { return new TestAbpSession( new MultiTenancyConfig {IsEnabled = multiTenancyIsEnabled}, new DataContextAmbientScopeProvider<SessionOverride>( new AsyncLocalAmbientDataContext() ), Substitute.For<ITenantResolver>() ); } private static ISettingDefinitionManager CreateMockSettingDefinitionManager() { var settings = new Dictionary<string, SettingDefinition> { {MyAppLevelSetting, new SettingDefinition(MyAppLevelSetting, "42")}, { MyAllLevelsSetting, new SettingDefinition(MyAllLevelsSetting, "application level default value", scopes: SettingScopes.Application | SettingScopes.Tenant | SettingScopes.User) }, { MyNotInheritedSetting, new SettingDefinition(MyNotInheritedSetting, "default-value", scopes: SettingScopes.Application | SettingScopes.Tenant, isInherited: false) }, {MyEnumTypeSetting, new SettingDefinition(MyEnumTypeSetting, MyEnumSettingType.Setting1.ToString())}, { MyEncryptedSetting, new SettingDefinition(MyEncryptedSetting, "", isEncrypted: true, scopes: SettingScopes.Application | SettingScopes.Tenant | SettingScopes.User) } }; var definitionManager = Substitute.For<ISettingDefinitionManager>(); //Implement methods definitionManager.GetSettingDefinition(Arg.Any<string>()).Returns(x => { if (!settings.TryGetValue(x[0].ToString(), out var settingDefinition)) { throw new AbpException("There is no setting defined with name: " + x[0]); } return settingDefinition; }); definitionManager.GetAllSettingDefinitions().Returns(settings.Values.ToList()); return definitionManager; } private class MemorySettingStore : ISettingStore { private readonly List<SettingInfo> _settings; public MemorySettingStore() { _settings = new List<SettingInfo> { new SettingInfo(null, null, MyAppLevelSetting, "48"), new SettingInfo(null, null, MyAllLevelsSetting, "application level stored value"), new SettingInfo(1, null, MyAllLevelsSetting, "tenant 1 stored value"), new SettingInfo(1, 1, MyAllLevelsSetting, "user 1 stored value"), new SettingInfo(1, 2, MyAllLevelsSetting, "user 2 stored value"), new SettingInfo(1, 2, MyEncryptedSetting, "Bs90qo8Argqw3l4ZfWsRqQ=="), // encrypted setting: user_setting new SettingInfo(1, null, MyEncryptedSetting, "f1dilIUWtfL7DhGextUFKw=="), // encrypted setting: tenant_setting new SettingInfo(null, null, MyEncryptedSetting, "OsxLBbqIX7jiqOXo3M1DdA=="), // encrypted setting: app_setting new SettingInfo(null, null, MyNotInheritedSetting, "application value"), }; } public Task<SettingInfo> GetSettingOrNullAsync(int? tenantId, long? userId, string name) { return Task.FromResult(GetSettingOrNull(tenantId, userId, name)); } public SettingInfo GetSettingOrNull(int? tenantId, long? userId, string name) { return _settings.FirstOrDefault(s => s.TenantId == tenantId && s.UserId == userId && s.Name == name); } #pragma warning disable 1998 public Task DeleteAsync(SettingInfo setting) { Delete(setting); return Task.CompletedTask; } public void Delete(SettingInfo setting) { _settings.RemoveAll(s => s.TenantId == setting.TenantId && s.UserId == setting.UserId && s.Name == setting.Name); } #pragma warning restore 1998 #pragma warning disable 1998 public Task CreateAsync(SettingInfo setting) { Create(setting); return Task.CompletedTask; } public void Create(SettingInfo setting) { _settings.Add(setting); } #pragma warning restore 1998 public Task UpdateAsync(SettingInfo setting) { Update(setting); return Task.CompletedTask; } public void Update(SettingInfo setting) { var s = GetSettingOrNull(setting.TenantId, setting.UserId, setting.Name); if (s != null) { s.Value = setting.Value; } } public Task<List<SettingInfo>> GetAllListAsync(int? tenantId, long? userId) { return Task.FromResult(GetAllList(tenantId, userId)); } public List<SettingInfo> GetAllList(int? tenantId, long? userId) { var allSetting = _settings.Where(s => s.TenantId == tenantId && s.UserId == userId) .Select(s => new SettingInfo(s.TenantId, s.UserId, s.Name, s.Value)).ToList(); //Add some undefined settings. allSetting.Add(new SettingInfo(null, null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString())); allSetting.Add(new SettingInfo(1, null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString())); allSetting.Add(new SettingInfo(1, 1, Guid.NewGuid().ToString(), Guid.NewGuid().ToString())); return allSetting; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Linq.Expressions.Tests { public class Break : GotoExpressionTests { [Theory] [PerCompilationType(nameof(ConstantValueData))] public void JustBreakValue(object value, bool useInterpreter) { Type type = value.GetType(); LabelTarget target = Expression.Label(type); Expression block = Expression.Block( Expression.Break(target, Expression.Constant(value)), Expression.Label(target, Expression.Default(type)) ); Expression equals = Expression.Equal(Expression.Constant(value), block); Assert.True(Expression.Lambda<Func<bool>>(equals).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void BreakToMiddle(bool useInterpreter) { // The behaviour is that return jumps to a label, but does not necessarily leave a block. LabelTarget target = Expression.Label(typeof(int)); Expression block = Expression.Block( Expression.Break(target, Expression.Constant(1)), Expression.Label(target, Expression.Constant(2)), Expression.Constant(3) ); Assert.Equal(3, Expression.Lambda<Func<int>>(block).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void BreakJumps(object value, bool useInterpreter) { Type type = value.GetType(); LabelTarget target = Expression.Label(type); Expression block = Expression.Block( Expression.Break(target, Expression.Constant(value)), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value), block)).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(TypesData))] public void NonVoidTargetBreakHasNoValue(Type type) { LabelTarget target = Expression.Label(type); Assert.Throws<ArgumentException>("target", () => Expression.Break(target)); } [Theory] [MemberData(nameof(TypesData))] public void NonVoidTargetBreakHasNoValueTypeExplicit(Type type) { LabelTarget target = Expression.Label(type); Assert.Throws<ArgumentException>("target", () => Expression.Break(target, type)); } [Theory] [ClassData(typeof(CompilationTypes))] public void BreakVoidNoValue(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression block = Expression.Block( Expression.Break(target), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target) ); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [ClassData(typeof(CompilationTypes))] public void BreakExplicitVoidNoValue(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression block = Expression.Block( Expression.Break(target, typeof(void)), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target) ); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [MemberData(nameof(TypesData))] public void NullValueOnNonVoidBreak(Type type) { Assert.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(type))); Assert.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(type), default(Expression))); Assert.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(type), null, type)); } [Theory] [MemberData(nameof(ConstantValueData))] public void ExplicitNullTypeWithValue(object value) { Assert.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(value.GetType()), default(Type))); } [Fact] public void UnreadableLabel() { Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly"); LabelTarget target = Expression.Label(typeof(string)); Assert.Throws<ArgumentException>("value", () => Expression.Break(target, value)); Assert.Throws<ArgumentException>("value", () => Expression.Break(target, value, typeof(string))); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void CanAssignAnythingToVoid(object value, bool useInterpreter) { LabelTarget target = Expression.Label(); BlockExpression block = Expression.Block( Expression.Break(target, Expression.Constant(value)), Expression.Label(target) ); Assert.Equal(typeof(void), block.Type); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [MemberData(nameof(NonObjectAssignableConstantValueData))] public void CannotAssignValueTypesToObject(object value) { Assert.Throws<ArgumentException>(null, () => Expression.Break(Expression.Label(typeof(object)), Expression.Constant(value))); } [Theory] [PerCompilationType(nameof(ObjectAssignableConstantValueData))] public void ExplicitTypeAssigned(object value, bool useInterpreter) { LabelTarget target = Expression.Label(typeof(object)); BlockExpression block = Expression.Block( Expression.Break(target, Expression.Constant(value), typeof(object)), Expression.Label(target, Expression.Default(typeof(object))) ); Assert.Equal(typeof(object), block.Type); Assert.Equal(value, Expression.Lambda<Func<object>>(block).Compile(useInterpreter)()); } [Fact] public void BreakQuotesIfNecessary() { LabelTarget target = Expression.Label(typeof(Expression<Func<int>>)); BlockExpression block = Expression.Block( Expression.Break(target, Expression.Lambda<Func<int>>(Expression.Constant(0))), Expression.Label(target, Expression.Default(typeof(Expression<Func<int>>))) ); Assert.Equal(typeof(Expression<Func<int>>), block.Type); } [Fact] public void UpdateSameIsSame() { LabelTarget target = Expression.Label(typeof(int)); Expression value = Expression.Constant(0); GotoExpression ret = Expression.Break(target, value); Assert.Same(ret, ret.Update(target, value)); Assert.Same(ret, NoOpVisitor.Instance.Visit(ret)); } [Fact] public void UpdateDiferentValueIsDifferent() { LabelTarget target = Expression.Label(typeof(int)); GotoExpression ret = Expression.Break(target, Expression.Constant(0)); Assert.NotSame(ret, ret.Update(target, Expression.Constant(0))); } [Fact] public void UpdateDifferentTargetIsDifferent() { Expression value = Expression.Constant(0); GotoExpression ret = Expression.Break(Expression.Label(typeof(int)), value); Assert.NotSame(ret, ret.Update(Expression.Label(typeof(int)), value)); } [Fact] public void OpenGenericType() { Assert.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(List<>))); } [Fact] public static void TypeContainsGenericParameters() { Assert.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(List<>.Enumerator))); Assert.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(List<>).MakeGenericType(typeof(List<>)))); } [Fact] public void PointerType() { Assert.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(int).MakePointerType())); } [Fact] public void ByRefType() { Assert.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(int).MakeByRefType())); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using Palaso.WritingSystems.Collation; namespace Palaso.Data { public sealed class ResultSet<T>: IEnumerable<RecordToken<T>>, IEnumerable<RepositoryId> where T : class, new() { private readonly List<RecordToken<T>> _results; private readonly IDataMapper<T> _dataMapper; public ResultSet(IDataMapper<T> dataMapper, params IEnumerable<RecordToken<T>>[] results) { if (dataMapper == null) { throw new ArgumentNullException("dataMapper"); } if (results == null) { throw new ArgumentNullException("results"); } _results = new List<RecordToken<T>>(); foreach (IEnumerable<RecordToken<T>> result in results) { _results.AddRange(result); } _dataMapper = dataMapper; } [Obsolete] private static List<RecordToken<T>> CreateResultsWithNoDuplicates(IEnumerable<IEnumerable<RecordToken<T>>> initialResults) { Dictionary<RecordToken<T>, object> alreadyUsedTokens = new Dictionary<RecordToken<T>, object>(); List<RecordToken<T>> results = new List<RecordToken<T>>(); foreach (IEnumerable<RecordToken<T>> resultSet in initialResults) { foreach (RecordToken<T> token in resultSet) { if (alreadyUsedTokens.ContainsKey(token)) { continue; } alreadyUsedTokens.Add(token, null); results.Add(token); } } return results; } public RecordToken<T> this[int index] { get { return _results[index]; } } public void RemoveAll(Predicate<RecordToken<T>> match) { _results.RemoveAll(match); } public int Count { get { return _results.Count; } } private RecordToken<T> GetItemFromIndex(int index) { if (index < 0) { return null; } return this[index]; } #region FindFirst(Index) Of DisplayString public RecordToken<T> FindFirst(Predicate<RecordToken<T>> match) { int index = FindFirstIndex(match); return GetItemFromIndex(index); } public RecordToken<T> FindFirst(int startIndex, Predicate<RecordToken<T>> match) { int index = FindFirstIndex(startIndex, match); return GetItemFromIndex(index); } public RecordToken<T> FindFirst(int startIndex, int count, Predicate<RecordToken<T>> match) { int index = FindFirstIndex(startIndex, count, match); return GetItemFromIndex(index); } public int FindFirstIndex(Predicate<RecordToken<T>> match) { return _results.FindIndex(match); } public int FindFirstIndex(int startIndex, int count, Predicate<RecordToken<T>> match) { return _results.FindIndex(startIndex, count, match); } public int FindFirstIndex(int startIndex, Predicate<RecordToken<T>> match) { return _results.FindIndex(startIndex, match); } #endregion #region FindFirst(Index) of RepositoryId public RecordToken<T> FindFirst(RepositoryId id) { int index = FindFirstIndex(id); return GetItemFromIndex(index); } public RecordToken<T> FindFirst(RepositoryId id, int startIndex) { int index = FindFirstIndex(id, startIndex); return GetItemFromIndex(index); } public RecordToken<T> FindFirst(RepositoryId id, int startIndex, int count) { int index = FindFirstIndex(id, startIndex, count); return GetItemFromIndex(index); } public int FindFirstIndex(RepositoryId id, int startIndex, int count) { return _results.FindIndex(startIndex, count, delegate(RecordToken<T> r) { return (r.Id == id); }); } public int FindFirstIndex(RepositoryId id) { return _results.FindIndex(delegate(RecordToken<T> r) { return (r.Id == id); }); } public int FindFirstIndex(RepositoryId id, int startIndex) { return _results.FindIndex(startIndex, delegate(RecordToken<T> r) { return (r.Id == id); }); } #endregion #region FindFirst(Index) of T public RecordToken<T> FindFirst(T item) { int index = FindFirstIndex(item); return GetItemFromIndex(index); } public RecordToken<T> FindFirst(T item, int startIndex) { int index = FindFirstIndex(item, startIndex); return GetItemFromIndex(index); } public RecordToken<T> FindFirst(T item, int startIndex, int count) { int index = FindFirstIndex(item, startIndex, count); return GetItemFromIndex(index); } public int FindFirstIndex(T item) { RepositoryId id = _dataMapper.GetId(item); return FindFirstIndex(id); } public int FindFirstIndex(T item, int startIndex) { RepositoryId id = _dataMapper.GetId(item); return FindFirstIndex(id, startIndex); } public int FindFirstIndex(T item, int startIndex, int count) { RepositoryId id = _dataMapper.GetId(item); return FindFirstIndex(id, startIndex, count); } #endregion #region FindFirstIndex of RecordToken<T> public int FindFirstIndex(RecordToken<T> token, int startIndex, int count) { return _results.FindIndex(startIndex, count, delegate(RecordToken<T> r) { return (r == token); }); } public int FindFirstIndex(RecordToken<T> token) { return _results.FindIndex(delegate(RecordToken<T> r) { return (r == token); }); } public int FindFirstIndex(RecordToken<T> token, int startIndex) { return _results.FindIndex(startIndex, delegate(RecordToken<T> r) { return (r == token); }); } #endregion public static explicit operator BindingList<RecordToken<T>>(ResultSet<T> results) { return new BindingList<RecordToken<T>>(results._results); } #region IEnumerable<RecordToken<T>> Members IEnumerator<RecordToken<T>> IEnumerable<RecordToken<T>>.GetEnumerator() { return _results.GetEnumerator(); } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return ((IEnumerable<RecordToken<T>>) this).GetEnumerator(); } #endregion #region IEnumerable<RepositoryId> Members IEnumerator<RepositoryId> IEnumerable<RepositoryId>.GetEnumerator() { foreach (RecordToken<T> recordToken in this) { yield return (recordToken.Id); } } #endregion public void Sort(params SortDefinition[] sortDefinitions) { _results.Sort(new RecordTokenComparer<T>(sortDefinitions)); } public void SortByRepositoryId() { SortByRepositoryId(_results); } private static void SortByRepositoryId(List<RecordToken<T>> list) { list.Sort(new RecordTokenComparer<T>(new SortDefinition("RepositoryId", Comparer<RepositoryId>.Default))); } /// <summary> /// Removes any entries for which the predicate canBeRemoved is true /// and another record token with the same repository Id exists /// </summary> /// <param name="fieldName"></param> /// <param name="canBeRemoved"></param> public void Coalesce(string fieldName, Predicate<object> canBeRemoved) { List<RecordToken<T>> results = new List<RecordToken<T>>(_results); SortByRepositoryId(results); bool hasValidEntry = false; List<RecordToken<T>> removeable = new List<RecordToken<T>>(); RecordToken<T> previousToken = null; foreach (RecordToken<T> token in results) { if ((previousToken != null) && (token.Id != previousToken.Id)) { if(hasValidEntry) { RemoveTokens(removeable); } removeable.Clear(); hasValidEntry = false; } if (canBeRemoved(token[fieldName])) { removeable.Add(token); } else { hasValidEntry = true; } previousToken = token; } if (hasValidEntry) { RemoveTokens(removeable); } } private void RemoveTokens(IEnumerable<RecordToken<T>> removeable) { foreach (RecordToken<T> recordToken in removeable) { _results.Remove(recordToken); } } } public class SortDefinition { private readonly string _field; private readonly IComparer _comparer; public SortDefinition(string field, IComparer comparer) { _field = field; _comparer = comparer; } public string Field { get { return _field; } } public IComparer Comparer { get { return _comparer; } } } }
//css_dir ..\WixSharpToolset\; //css_ref System.Core.dll; //css_ref System.Windows.Forms.dll; //css_ref Wix_bin\SDK\Microsoft.Deployment.WindowsInstaller.dll; //css_ref WixSharp.UI.dll; //css_imp WelcomeDialog.cs; //css_imp WelcomeDialog.designer.cs; //css_imp CloseDialog.cs; //css_imp CloseDialog.designer.cs; //css_imp ProgressDialog.cs //css_imp ProgressDialog.Designer.cs //css_imp ExitDialog.cs; //css_imp ExitDialog.designer.cs; //css_imp MaintenanceDialog.cs; //css_imp MaintenanceDialog.designer.cs; using WixSharp; using WixSharp.Forms; using Microsoft.Deployment.WindowsInstaller; using Microsoft.Win32; class Script { static public void Main(string[] args) { // The name "Symphony" is used in a lot of places, for paths, shortut names and installer filename, so define it once var productName = "Symphony"; // Create a wixsharp project instance and assign the project name to it, and a hierarchy of all files to include // Files are taken from multiple locations, and not all files in each location should be included, which is why // the file list is rather long and explicit. At some point we might make the `dist` folder match exactly the // desired contents of installation, and then we can simplify this bit. var project = new ManagedProject(productName, new Dir(@"%ProgramFiles%\" + productName, new File(new Id("symphony_exe"), @"..\..\..\dist\win-unpacked\Symphony.exe", // Create two shortcuts to the main Symphony.exe file, one on the desktop and one in the program menu new FileShortcut(productName, @"%Desktop%") { IconFile = @"..\..\..\images\icon.ico" }, new FileShortcut(productName, @"%ProgramMenu%") { IconFile = @"..\..\..\images\icon.ico" } ), new File(@"..\..\..\dist\win-unpacked\chrome_100_percent.pak"), new File(@"..\..\..\dist\win-unpacked\chrome_200_percent.pak"), new File(@"..\..\..\dist\win-unpacked\d3dcompiler_47.dll"), new File(@"..\..\..\dist\win-unpacked\ffmpeg.dll"), new File(@"..\..\..\dist\win-unpacked\icudtl.dat"), new File(@"..\..\..\dist\win-unpacked\libEGL.dll"), new File(@"..\..\..\dist\win-unpacked\libGLESv2.dll"), new File(@"..\..\..\dist\win-unpacked\LICENSE.electron.txt"), new File(@"..\..\..\dist\win-unpacked\LICENSES.chromium.html"), new File(@"..\..\..\dist\win-unpacked\resources.pak"), new File(@"..\..\..\dist\win-unpacked\snapshot_blob.bin"), new File(@"..\..\..\dist\win-unpacked\v8_context_snapshot.bin"), new File(@"..\..\..\dist\win-unpacked\vk_swiftshader.dll"), new File(@"..\..\..\dist\win-unpacked\vk_swiftshader_icd.json"), new File(@"..\..\..\dist\win-unpacked\vulkan-1.dll"), new File(@"..\..\..\dist\win-unpacked\resources\app.asar.unpacked\node_modules\screen-share-indicator-frame\ScreenShareIndicatorFrame.exe"), new File(@"..\..\..\dist\win-unpacked\resources\app.asar.unpacked\node_modules\screen-snippet\ScreenSnippet.exe"), new Dir(@"config", new Files(@"..\..\..\dist\win-unpacked\config\*.*") ), new Dir(@"dictionaries", new Files(@"..\..\..\dist\win-unpacked\dictionaries\*.*") ), new Dir(@"library", new File(@"..\..\..\library\dictionary"), new File(@"..\..\..\library\indexvalidator-x64.exe"), new File(@"..\..\..\library\libsymphonysearch-x64.dll"), new File(@"..\..\..\library\lz4-win-x64.exe"), new File(@"..\..\..\library\tar-win.exe") ), new Dir(@"locales", new Files(@"..\..\..\node_modules\electron\dist\locales\*.*") ), new Dir(@"resources", new DirFiles(@"..\..\..\dist\win-unpacked\resources\*.*"), new Dir(@"app.asar.unpacked", new Dir(@"node_modules", new Dir(@"@felixrieseberg\spellchecker\build\Release", new File(@"..\..\..\dist\win-unpacked\resources\app.asar.unpacked\node_modules\@felixrieseberg\spellchecker\build\Release\spellchecker.node") ), new Dir(@"cld\build\Release", new File(@"..\..\..\dist\win-unpacked\resources\app.asar.unpacked\node_modules\cld\build\Release\cld.node") ), new Dir(@"diskusage\build\Release", new File(@"..\..\..\dist\win-unpacked\resources\app.asar.unpacked\node_modules\diskusage\build\Release\diskusage.node") ), new Dir(@"ffi-napi\build\Release", new File(@"..\..\..\dist\win-unpacked\resources\app.asar.unpacked\node_modules\ffi-napi\build\Release\ffi_bindings.node") ), new Dir(@"keyboard-layout\build\Release", new File(@"..\..\..\dist\win-unpacked\resources\app.asar.unpacked\node_modules\keyboard-layout\build\Release\keyboard-layout-manager.node") ), new Dir(@"ref-napi\build\Release", new File(@"..\..\..\dist\win-unpacked\resources\app.asar.unpacked\node_modules\ref-napi\build\Release\binding.node") ), new Dir(@"spawn-rx", new Files(@"..\..\..\dist\win-unpacked\resources\app.asar.unpacked\node_modules\spawn-rx\*.*") ), new Dir(@"swift-search\node_modules", new Dir(@"ffi-napi\build\Release", new File(@"..\..\..\dist\win-unpacked\resources\app.asar.unpacked\node_modules\swift-search\node_modules\ffi-napi\build\Release\ffi_bindings.node") ), new Dir(@"ref-napi\build\Release", new File(@"..\..\..\dist\win-unpacked\resources\app.asar.unpacked\node_modules\swift-search\node_modules\ref-napi\build\Release\binding.node") ) ) ) ) ), new Dir(@"swiftshader", new Files(@"..\..\..\dist\win-unpacked\swiftshader\*.*") ) ), // Add a launch condition to require Windows Server 2008 or later // The property values to compare against can be found here: // https://docs.microsoft.com/en-us/windows/win32/msi/operating-system-property-values new LaunchCondition("VersionNT>=600 AND WindowsBuild>=6001", "OS not supported"), // Add registry entry used by protocol handler to launch symphony when opening symphony:// URIs new RegValue(WixSharp.RegistryHive.ClassesRoot, productName + @"\shell\open\command", "", "\"[INSTALLDIR]Symphony.exe\" \"%1\""), // When installing or uninstalling, we want Symphony to be closed down, but the standard way of sending a WM_CLOSE message // will not work for us, as we have a "minimize on close" option, which stops the app from terminating on WM_CLOSE. So we // instruct the installer to not send a Close message, but instead send the EndSession message, and we have a custom event // handler in the SDA code which listens for this message, and ensures app termination when it is received. new CloseApplication("Symphony.exe", false) { EndSessionMessage = true } ); // The build script which calls the wix# builder, will be run from a command environment which has %SYMVER% set. // So we just extract that version string, create a Version object from it, and pass it to out project definition. var version = System.Environment.GetEnvironmentVariable("SYMVER"); project.Version = new System.Version(version); // To get the correct behaviour with upgrading the product, the product GUID needs to be different for every build, // but the UpgradeCode needs to stay the same. If we wanted to make a new major version and allow it to be installed // side-by-side with the previous version, we would generate a new UpgradeCode for the new version onwards. // More details can be found in this stackoverflow post: // https://stackoverflow.com/a/26344742 project.GUID = new System.Guid("{4042AD1C-90E1-4032-B6B9-2BF6A4214096}"); project.ProductId = System.Guid.NewGuid(); project.UpgradeCode = new System.Guid("{36402281-8141-4797-8A90-07CFA75EFA55}"); // Allow any versions to be upgraded/downgraded freely project.MajorUpgradeStrategy = MajorUpgradeStrategy.Default; project.MajorUpgradeStrategy.RemoveExistingProductAfter = Step.InstallInitialize; project.MajorUpgradeStrategy.UpgradeVersions.Minimum = "0.0.0"; project.MajorUpgradeStrategy.UpgradeVersions.Maximum = null; // No max version limit project.MajorUpgradeStrategy.UpgradeVersions.IncludeMaximum = true; project.MajorUpgradeStrategy.UpgradeVersions.IncludeMinimum = true; project.MajorUpgradeStrategy.PreventDowngradingVersions.Minimum = "0.0.0"; project.MajorUpgradeStrategy.PreventDowngradingVersions.Maximum = "0.0.0"; project.MajorUpgradeStrategy.PreventDowngradingVersions.IncludeMaximum = true; project.MajorUpgradeStrategy.PreventDowngradingVersions.IncludeMinimum = true; // Declare all the custom properties we want to use, and assign them default values. It is possible to override // these when running the installer, but if not specified, the defaults will be used. project.Properties = new[] { new PublicProperty("APPDIR", ""), new PublicProperty("ALLUSERS", "1"), new PublicProperty("ALWAYS_ON_TOP", "DISABLED" ), new PublicProperty("AUTO_LAUNCH_PATH", ""), new PublicProperty("AUTO_START", "ENABLED"), new PublicProperty("BRING_TO_FRONT", "DISABLED"), new PublicProperty("CUSTOM_TITLE_BAR", "ENABLED"), new PublicProperty("DEV_TOOLS_ENABLED", "true"), new PublicProperty("FULL_SCREEN", "true"), new PublicProperty("LOCATION", "true"), new PublicProperty("MEDIA", "true"), new PublicProperty("MIDI_SYSEX", "true"), new PublicProperty("MINIMIZE_ON_CLOSE", "ENABLED"), new PublicProperty("NOTIFICATIONS", "true"), new PublicProperty("OPEN_EXTERNAL", "true"), new PublicProperty("POD_URL", "https://my.symphony.com"), new PublicProperty("CONTEXT_ORIGIN_URL", ""), new PublicProperty("POINTER_LOCK", "true"), new Property("MSIINSTALLPERUSER", "1"), new Property("PROGRAMSFOLDER", System.Environment.ExpandEnvironmentVariables(@"%PROGRAMFILES%")) }; // Define the custom actions we want to run, and at what point of the installation we want to execute them. project.Actions = new WixSharp.Action[] { // InstallVariant // // We want to be able to display the POD URL dialog every time SDA starts after a reinstall, regardless of // whether it is a new version or the same version, but we don't want to display it if no reinstallation // have been done. To detect this, we always write a new GUID to the fill InstallVariant.info on every // installation. new ElevatedManagedAction(CustomActions.InstallVariant, Return.check, When.After, Step.InstallFiles, Condition.NOT_BeingRemoved ) { // INSTALLDIR is a built-in property, and we need it to know which path to write the InstallVariant to UsesProperties = "INSTALLDIR" }, // UpdateConfig // // After installation, the Symphony.config file needs to be updated with values from the install properties, // either their default values as specified above, or with the overridden value if an override was specified // on the command line when the installer was started. new ElevatedManagedAction(CustomActions.UpdateConfig, Return.check, When.After, Step.InstallFiles, Condition.NOT_BeingRemoved ) { // The UpdateConfig action needs the built-in property INSTALLDIR as well as most of the custom properties UsesProperties = "INSTALLDIR,POD_URL,CONTEXT_ORIGIN_URL,MINIMIZE_ON_CLOSE,ALWAYS_ON_TOP,AUTO_START,BRING_TO_FRONT,MEDIA,LOCATION,NOTIFICATIONS,MIDI_SYSEX,POINTER_LOCK,FULL_SCREEN,OPEN_EXTERNAL,CUSTOM_TITLE_BAR,DEV_TOOLS_ENABLED,AUTO_LAUNCH_PATH" }, // CleanRegistry // // We have some registry keys which are added by the SDA application when it is first launched. This custom // action will clean up those keys on uninstall. The name/location of keys have changed between different // versions of SDA, so we clean up all known variations, and ignore any missing ones. new ElevatedManagedAction(CustomActions.CleanRegistry, Return.ignore, When.After, Step.RemoveFiles, Condition.BeingUninstalled ), // CleanRegistryCurrentUser // // The registry keys stored under HKEY_CURRENT_USER can not be accessed through an ElevatedManagedAction, as // elevated actions run as a different user (local system account rather than current user) so those keys // are removed in this action. new ManagedAction(CustomActions.CleanRegistryCurrentUser, Return.ignore, When.After, Step.RemoveFiles, Condition.BeingUninstalled ), // Start Symphony after installation is complete new InstalledFileAction(new Id("symphony_exe"), "", Return.asyncNoWait, When.After, Step.InstallFinalize, Condition.NOT_BeingRemoved) }; // Use our own Symphony branded bitmap for installation dialogs project.BannerImage = "Banner.jpg"; project.BackgroundImage = "Tabloid.jpg"; // Define our own installation flow, using a mix of custom dialogs (defined in their own files) and built-in dialogs project.ManagedUI = new ManagedUI(); project.ManagedUI.InstallDialogs.Add<Symphony.WelcomeDialog>() .Add<Symphony.CloseDialog>() .Add<Symphony.ProgressDialog>() .Add<Symphony.ExitDialog>(); project.ManagedUI.ModifyDialogs.Add<Symphony.MaintenanceDialog>() .Add<Symphony.CloseDialog>() .Add<Symphony.ProgressDialog>() .Add<Symphony.ExitDialog>(); project.Load += project_Load; project.ControlPanelInfo.NoRepair = true; project.ControlPanelInfo.NoModify = true; project.ControlPanelInfo.ProductIcon = @"..\..\..\images\icon.ico"; project.ControlPanelInfo.Manufacturer = "Symphony"; project.Platform = Platform.x64; // Generate an MSI from all settings done above Compiler.BuildMsi(project); } static void project_Load(SetupEventArgs e) { try { if (e.IsInstalling || e.IsUpgrading) { // "ALLUSERS" will be set to "2" if installing through UI, so the "MSIINSTALLPERUSER" property can be used so the user can choose install scope if (e.Session["ALLUSERS"] != "2" ) { // If "ALLUSERS" is "1" or "", this is a quiet command line installation, and we need to set the right paths here, since the UI haven't. if (e.Session["APPDIR"] != "") { // If "APPDIR" param was specified, just use that as is e.Session["INSTALLDIR"] = e.Session["APPDIR"]; } else if (e.Session["ALLUSERS"] == "") { // Install for current user e.Session["INSTALLDIR"] = System.Environment.ExpandEnvironmentVariables(@"%LOCALAPPDATA%\Programs\Symphony\" + e.ProductName); } else { // Install for all users e.Session["INSTALLDIR"] = e.Session["PROGRAMSFOLDER"] + @"\Symphony\" + e.ProductName; } } // Try to close all running symphony instances before installing. Since we have started using the EndSession message to tell the app to exit, // we don't really need to force terminate anymore. But the older versions of SDA does not listen for the EndSession event, so we still need // this code to ensure older versions gets shut down properly. System.Diagnostics.Process.GetProcessesByName("Symphony").ForEach(p => { if( System.IO.Path.GetFileName(p.MainModule.FileName) =="Symphony.exe") { if( !p.HasExited ) { p.Kill(); p.WaitForExit(); } } }); } } catch (System.ComponentModel.Win32Exception ex) { // We always seem to get this specific exception triggered, but the application still close down correctly. // The exception description is "Only part of a ReadProcessMemory or WriteProcessMemory request was completed". // We ignore that specific exception, so as not to put false error outputs into the log. if (ex.NativeErrorCode != 299) { e.Session.Log("Error trying to close all Symphony instances: " + ex.ToString() ); } } catch (System.Exception ex) { e.Session.Log("Error trying to close all Symphony instances: " + ex.ToString() ); } } } public class CustomActions { // InstallVariant custom action [CustomAction] public static ActionResult InstallVariant(Session session) { try { // Create the InstallVariant.info file var installDir = session.Property("INSTALLDIR"); var filename = System.IO.Path.Combine(installDir, @"config\InstallVariant.info"); var installVariantFile = new System.IO.StreamWriter(filename); // Generate new GUID for each time we install, and write it as a text string to the file var guid = System.Guid.NewGuid(); installVariantFile.Write(guid.ToString()); installVariantFile.Close(); } catch (System.Exception e) { session.Log("Error executing InstallVariant: " + e.ToString() ); return ActionResult.Failure; } return ActionResult.Success; } // UpdateConfig custom action [CustomAction] public static ActionResult UpdateConfig(Session session) { try { // Read the Symphony.config file var installDir = session.Property("INSTALLDIR"); var filename = System.IO.Path.Combine(installDir, @"config\Symphony.config"); string data = System.IO.File.ReadAllText(filename); // Replace all the relevant settings with values from the properties data = ReplaceProperty(data, "url", session.Property("POD_URL")); data = ReplaceProperty(data, "contextOriginUrl", session.Property("CONTEXT_ORIGIN_URL")); data = ReplaceProperty(data, "minimizeOnClose", session.Property("MINIMIZE_ON_CLOSE")); data = ReplaceProperty(data, "alwaysOnTop", session.Property("ALWAYS_ON_TOP")); data = ReplaceProperty(data, "launchOnStartup", session.Property("AUTO_START")); data = ReplaceProperty(data, "bringToFront", session.Property("BRING_TO_FRONT")); data = ReplaceProperty(data, "media", session.Property("MEDIA")); data = ReplaceProperty(data, "geolocation", session.Property("LOCATION")); data = ReplaceProperty(data, "notifications", session.Property("NOTIFICATIONS")); data = ReplaceProperty(data, "midiSysex", session.Property("MIDI_SYSEX")); data = ReplaceProperty(data, "pointerLock", session.Property("POINTER_LOCK")); data = ReplaceProperty(data, "fullscreen", session.Property("FULL_SCREEN")); data = ReplaceProperty(data, "openExternal", session.Property("OPEN_EXTERNAL")); data = ReplaceProperty(data, "isCustomTitleBar", session.Property("CUSTOM_TITLE_BAR")); data = ReplaceProperty(data, "devToolsEnabled", session.Property("DEV_TOOLS_ENABLED")); data = ReplaceProperty(data, "autoLaunchPath", session.Property("AUTO_LAUNCH_PATH")); // Write the contents back to the file System.IO.File.WriteAllText(filename, data); } catch (System.Exception e) { session.Log("Error executing UpdateConfig: " + e.ToString() ); return ActionResult.Failure; } return ActionResult.Success; } // Helper function called by UpdadeConfig action, for each config file value that needs to be // replaced by a value taken from the property. `data` is the entire contents of the config file. // `name` is the name of the setting in the config file (for example "url" or "minimizeOnClose". // `value` is the value to insert for the setting, and needs to be grabbed from the propery // collection before calling the function. The function returns the full config file content with // the requested replacement performed. static string ReplaceProperty( string data, string name, string value ) { // Using regular expressions to replace the existing value in the config file with the // one from the property. This is the same as the regex we used to have in the old // Advanced Installer, which looked like this: "url"\s*:\s*".*" => "url": "[POD_URL]" return System.Text.RegularExpressions.Regex.Replace(data, @"""" + name + @"""\s*:\s*"".*""", @"""" + name + @""":""" + value.Trim() + @""""); } // CleanRegistry custom action [CustomAction] public static ActionResult CleanRegistry(Session session) { try { // Remove registry keys added for auto-launch using( var key = Registry.Users.OpenSubKey(@"\.DEFAULT\Software\Microsoft\Windows\CurrentVersion\Run", true) ) { if (key != null) { key.DeleteValue("Symphony", false); } } // Remove registry keys added by protocol handlers using( var key = Registry.LocalMachine.OpenSubKey(@"Software\Classes", true) ) { if (key != null) { key.DeleteSubKeyTree("symphony", false); } } using( var key = Registry.ClassesRoot.OpenSubKey(@"\", true) ) { if (key != null) { key.DeleteSubKeyTree("symphony", false); } } } catch (System.Exception e) { session.Log("Error executing CleanRegistry: " + e.ToString() ); return ActionResult.Success; } return ActionResult.Success; } // CleanRegistryCurrentUser custom action [CustomAction] public static ActionResult CleanRegistryCurrentUser(Session session) { try { // Remove registry keys added for auto-launch using( var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true) ) { if (key != null) { key.DeleteValue("Symphony", false); key.DeleteValue("com.symphony.electron-desktop", false); key.DeleteValue("electron.app.Symphony", false); } } // Remove registry keys added by protocol handlers using( var key = Registry.CurrentUser.OpenSubKey(@"Software\Classes", true) ) { if (key != null) { key.DeleteSubKeyTree("symphony", false); } } } catch (System.Exception e) { session.Log("Error executing CleanRegistryCurrentUser: " + e.ToString() ); return ActionResult.Success; } return ActionResult.Success; } }
using System; using System.Linq; using FluentNHibernate.Automapping.TestFixtures; using FluentNHibernate.Conventions.Helpers.Builders; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.Mapping; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.Testing.FluentInterfaceTests; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.OverridingFluentInterface { [TestFixture] public class ArrayConventionTests { private PersistenceModel model; private IMappingProvider mapping; private Type mappingType; [SetUp] public void CreatePersistenceModel() { model = new PersistenceModel(); } [Test] public void AccessShouldntBeOverwritten() { Mapping(x => x.Access.Field()); Convention(x => x.Access.Property()); VerifyModel(x => x.Access.ShouldEqual("field")); } [Test] public void BatchSizeShouldntBeOverwritten() { Mapping(x => x.BatchSize(10)); Convention(x => x.BatchSize(100)); VerifyModel(x => x.BatchSize.ShouldEqual(10)); } [Test] public void CacheShouldntBeOverwritten() { Mapping(x => x.Cache.CustomUsage("fish")); Convention(x => x.Cache.ReadOnly()); VerifyModel(x => x.Cache.Usage.ShouldEqual("fish")); } [Test] public void CascadeShouldntBeOverwritten() { Mapping(x => x.Cascade.All()); Convention(x => x.Cascade.None()); VerifyModel(x => x.Cascade.ShouldEqual("all")); } [Test] public void CheckShouldntBeOverwritten() { Mapping(x => x.Check("constraint")); Convention(x => x.Check("xxx")); VerifyModel(x => x.Check.ShouldEqual("constraint")); } [Test] public void CollectionTypeShouldntBeOverwritten() { Mapping(x => x.CollectionType<int>()); Convention(x => x.CollectionType<string>()); VerifyModel(x => x.CollectionType.GetUnderlyingSystemType().ShouldEqual(typeof(int))); } [Test] public void FetchShouldntBeOverwritten() { Mapping(x => x.Fetch.Join()); Convention(x => x.Fetch.Select()); VerifyModel(x => x.Fetch.ShouldEqual("join")); } [Test] public void GenericShouldntBeOverwritten() { Mapping(x => x.Generic()); Convention(x => x.Not.Generic()); VerifyModel(x => x.Generic.ShouldEqual(true)); } [Test] public void InverseShouldntBeOverwritten() { Mapping(x => x.Inverse()); Convention(x => x.Not.Inverse()); VerifyModel(x => x.Inverse.ShouldEqual(true)); } [Test] public void LazyShouldntBeOverwritten() { Mapping(x => x.LazyLoad()); Convention(x => x.Not.LazyLoad()); VerifyModel(x => x.Lazy.ShouldEqual(true)); } [Test] public void MutableShouldntBeOverwritten() { Mapping(x => x.ReadOnly()); Convention(x => x.Not.ReadOnly()); VerifyModel(x => x.Mutable.ShouldEqual(false)); } [Test] public void OptimisticLockShouldntBeOverwritten() { Mapping(x => x.OptimisticLock.All()); Convention(x => x.OptimisticLock.Dirty()); VerifyModel(x => x.OptimisticLock.ShouldEqual("all")); } [Test] public void PersisterShouldntBeOverwritten() { Mapping(x => x.Persister<CustomPersister>()); Convention(x => x.Persister<SecondCustomPersister>()); VerifyModel(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(CustomPersister))); } [Test] public void SchemaShouldntBeOverwritten() { Mapping(x => x.Schema("dbo")); Convention(x => x.Schema("xxx")); VerifyModel(x => x.Schema.ShouldEqual("dbo")); } [Test] public void SubselectShouldntBeOverwritten() { Mapping(x => x.Subselect("whee")); Convention(x => x.Subselect("woo")); VerifyModel(x => x.Subselect.ShouldEqual("whee")); } [Test] public void TableNameShouldntBeOverwritten() { Mapping(x => x.Table("name")); Convention(x => x.Table("xxx")); VerifyModel(x => x.TableName.ShouldEqual("name")); } [Test] public void WhereShouldntBeOverwritten() { Mapping(x => x.Where("x = 1")); Convention(x => x.Where("y = 2")); VerifyModel(x => x.Where.ShouldEqual("x = 1")); } #region Helpers private void Convention(Action<IArrayInstance> convention) { model.Conventions.Add(new ArrayConventionBuilder().Always(convention)); } private void Mapping(Action<OneToManyPart<ExampleClass>> mappingDefinition) { var classMap = new ClassMap<ExampleParentClass>(); var map = classMap.HasMany(x => x.Examples) .AsArray(x => x.Id); mappingDefinition(map); mapping = classMap; mappingType = typeof(ExampleParentClass); } private void VerifyModel(Action<ArrayMapping> modelVerification) { model.Add(mapping); var generatedModels = model.BuildMappings(); var modelInstance = generatedModels .First(x => x.Classes.FirstOrDefault(c => c.Type == mappingType) != null) .Classes.First() .Collections.First(); modelVerification((ArrayMapping)modelInstance); } #endregion } }
// Copyright 2020 The Tilt Brush Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* Binary file format: int32 sentinel int32 version int32 reserved (must be 0) [ uint32 size + <size> bytes of additional header data ] int32 num_strokes num_strokes * { int32 brush_index float32x4 brush_color float32 brush_size uint32 stroke_extension_mask uint32 controlpoint_extension_mask [ int32/float32 for each set bit in stroke_extension_mask & ffff ] [ uint32 size + <size> bytes for each set bit in stroke_extension_mask & ~ffff ] int32 num_control_points num_control_points * { float32x3 position float32x4 orientation (quat) [ int32/float32 for each set bit in controlpoint_extension_mask ] } } */ using UnityEngine; using System; using System.Collections.Generic; using System.IO; using System.Linq; using StrokeFlags = TiltBrush.SketchMemoryScript.StrokeFlags; using ControlPoint = TiltBrush.PointerManager.ControlPoint; namespace TiltBrush { public static class SketchWriter { // Extensions-- we use this for stroke and control point extensibility. // // Each bit in the enum represents an extension ID in [0, 31]. // At save, we write out the extension ID mask and, grouped at a certain place in the // stream, the corresponding blocks of data in ascending order of ID. // // At load, we iterate through set bits in the mask, consuming each block of data. // // Data blocks for ControlPointExtension IDs are 4 bytes. // Data blocks for StrokeExtension IDs in [0,15] are 4 bytes. // Data blocks for StrokeExtension IDs in [16,31] are uint32 length + <length> bytes. [Flags] public enum StrokeExtension : uint { MaskSingleWord = 0xffff, None = 0, Flags = 1 << 0, // uint32, bitfield Scale = 1 << 1, // float, 1.0 is nominal Group = 1 << 2, // uint32, a value of 0 corresponds to SketchGroupTag.None so in that case, // we don't save out the group. Seed = 1 << 3, // int32; if not found then you get a random int. } [Flags] public enum ControlPointExtension : uint { None = 0, Pressure = 1 << 0, // float, 1.0 is nominal Timestamp = 1 << 1, // uint32, milliseconds } public struct AdjustedMemoryBrushStroke { public StrokeData strokeData; public StrokeFlags adjustedStrokeFlags; } private const int REQUIRED_SKETCH_VERSION_MIN = 5; private const int REQUIRED_SKETCH_VERSION_MAX = 6; private static readonly uint SKETCH_SENTINEL = 0xc576a5cd; // introduced at v5 // 5: added sketch sentinel, explicit version // 6: reserved for when we add a length-prefixed stroke extension, or more header data private static readonly int SKETCH_VERSION = 5; static public void RuntimeSelfCheck() { // Sanity-check ControlPoint's self-description; ReadMemory relies on it // being correct. unsafe { uint sizeofCP = (uint)sizeof(PointerManager.ControlPoint); uint extensionBytes = 4 * CountOnes(PointerManager.ControlPoint.EXTENSIONS); System.Diagnostics.Debug.Assert( sizeofCP == sizeof(Vector3) + sizeof(Quaternion) + extensionBytes); } } static uint CountOnes(uint val) { uint n = 0; while (val != 0) { n += 1; val = val & (val - 1); } return n; } // Enumerate the active memory list strokes, and return snapshots of the strokes. // The snapshots include adjusted stroke flags which take into account the effect // of inactive items on grouping. public static IEnumerable<AdjustedMemoryBrushStroke> EnumerateAdjustedSnapshots( IEnumerable<Stroke> strokes) { // Example grouping adjustment cases (n = ID, "C"=ContinueGroup, "x" = erased object): // |0 |1C |2C | => |0 |1C |2C | // |0 x|1C |2C | => |1 |2C | // |0 |1Cx|2C | => |0 |2C | // |0 |1Cx|2Cx| => |0 | // |0 x|1Cx|2C | => |2 | bool resetGroupContinue = false; foreach (var stroke in strokes) { AdjustedMemoryBrushStroke snapshot = new AdjustedMemoryBrushStroke(); snapshot.strokeData = stroke.GetCopyForSaveThread(); snapshot.adjustedStrokeFlags = stroke.m_Flags; if (resetGroupContinue) { snapshot.adjustedStrokeFlags &= ~StrokeFlags.IsGroupContinue; resetGroupContinue = false; } if (stroke.IsGeometryEnabled) { yield return snapshot; } else { // Effectively, if the lead stroke of group is inactive (erased), we promote // subsequent strokes to lead until one such stroke is active. resetGroupContinue = !snapshot.adjustedStrokeFlags.HasFlag(StrokeFlags.IsGroupContinue); } } } /// Write out sketch memory strokes ordered by initial control point timestamp. /// Leaves stream in indeterminate state; caller should Close() upon return. /// Output brushList provides mapping from .sketch brush index to GUID. /// While writing out the strokes we adjust the stroke flags to take into account the effect /// of inactive items on grouping. public static void WriteMemory(Stream stream, IList<AdjustedMemoryBrushStroke> strokeCopies, GroupIdMapping groupIdMapping, out List<Guid> brushList){ bool allowFastPath = BitConverter.IsLittleEndian; var writer = new TiltBrush.SketchBinaryWriter(stream); writer.UInt32(SKETCH_SENTINEL); writer.Int32(SKETCH_VERSION); writer.Int32(0); // reserved for header: must be 0 // Bump SKETCH_VERSION to >= 6 and remove this comment if non-zero data is written here writer.UInt32(0); // additional data size var brushMap = new Dictionary<Guid, int>(); // map from GUID to index brushList = new List<Guid>(); // GUID's by index // strokes writer.Int32(strokeCopies.Count); foreach (var copy in strokeCopies) { var stroke = copy.strokeData; int brushIndex; Guid brushGuid = stroke.m_BrushGuid; if (!brushMap.TryGetValue(brushGuid, out brushIndex)) { brushIndex = brushList.Count; brushMap[brushGuid] = brushIndex; brushList.Add(brushGuid); } writer.Int32(brushIndex); writer.Color(stroke.m_Color); writer.Float(stroke.m_BrushSize); // Bump SKETCH_VERSION to >= 6 and remove this comment if any // length-prefixed stroke extensions are added StrokeExtension strokeExtensionMask = StrokeExtension.Flags | StrokeExtension.Seed; if (stroke.m_BrushScale != 1) { strokeExtensionMask |= StrokeExtension.Scale; } if (stroke.m_Group != SketchGroupTag.None) { strokeExtensionMask |= StrokeExtension.Group; } writer.UInt32((uint)strokeExtensionMask); uint controlPointExtensionMask = (uint)(ControlPointExtension.Pressure | ControlPointExtension.Timestamp); writer.UInt32(controlPointExtensionMask); // Stroke extension fields, in order of appearance in the mask writer.UInt32((uint)copy.adjustedStrokeFlags); if ((uint)(strokeExtensionMask & StrokeExtension.Scale) != 0) { writer.Float(stroke.m_BrushScale); } if ((uint)(strokeExtensionMask & StrokeExtension.Group) != 0) { writer.UInt32(groupIdMapping.GetId(stroke.m_Group)); } if ((uint)(strokeExtensionMask & StrokeExtension.Seed) != 0) { writer.Int32(stroke.m_Seed); } // Control points writer.Int32(stroke.m_ControlPoints.Length); if (allowFastPath && controlPointExtensionMask == ControlPoint.EXTENSIONS) { // Fast path: write ControlPoint[] (semi-)directly into the file unsafe { int size = sizeof(ControlPoint) * stroke.m_ControlPoints.Length; fixed (ControlPoint* aPoints = stroke.m_ControlPoints) { writer.Write((IntPtr)aPoints, size); } } } else { for (int j = 0; j < stroke.m_ControlPoints.Length; ++j) { var rControlPoint = stroke.m_ControlPoints[j]; writer.Vec3(rControlPoint.m_Pos); writer.Quaternion(rControlPoint.m_Orient); // Control point extension fields, in order of appearance in the mask writer.Float(rControlPoint.m_Pressure); writer.UInt32(rControlPoint.m_TimestampMs); } } } } /// Leaves stream in indeterminate state; caller should Close() upon return. public static bool ReadMemory(Stream stream, Guid[] brushList, bool bAdditive, out bool isLegacy) { bool allowFastPath = BitConverter.IsLittleEndian; // Buffering speeds up fast path ~1.4x, slow path ~2.3x var bufferedStream = new BufferedStream(stream, 4096); // var stopwatch = new System.Diagnostics.Stopwatch(); // stopwatch.Start(); isLegacy = false; SketchMemoryScript.m_Instance.ClearRedo(); if (!bAdditive) { //clean up old draw'ring SketchMemoryScript.m_Instance.ClearMemory(); } #if (UNITY_EDITOR || EXPERIMENTAL_ENABLED) if (Config.IsExperimental) { if (App.Config.m_ReplaceBrushesOnLoad) { brushList = brushList.Select(guid => App.Config.GetReplacementBrush(guid)).ToArray(); } } #endif var strokes = GetStrokes(bufferedStream, brushList, allowFastPath); if (strokes == null) { return false; } // Check that the strokes are in timestamp order. uint headMs = uint.MinValue; foreach (var stroke in strokes) { if (stroke.HeadTimestampMs < headMs) { strokes.Sort((a,b) => a.HeadTimestampMs.CompareTo(b.HeadTimestampMs)); ControllerConsoleScript.m_Instance.AddNewLine("Bad timing data detected. Please re-save."); Debug.LogAssertion("Unsorted timing data in sketch detected. Strokes re-sorted."); break; } headMs = stroke.HeadTimestampMs; } QualityControls.m_Instance.AutoAdjustSimplifierLevel(strokes, brushList); foreach (var stroke in strokes) { // Deserialized strokes are expected in timestamp order, yielding aggregate complexity // of O(N) to populate the by-time linked list. SketchMemoryScript.m_Instance.MemoryListAdd(stroke); } // stopwatch.Stop(); // Debug.LogFormat("Reading took {0}", stopwatch.Elapsed); return true; } /// Parses a binary file into List of MemoryBrushStroke. /// Returns null on parse error. public static List<Stroke> GetStrokes( Stream stream, Guid[] brushList, bool allowFastPath) { var reader = new TiltBrush.SketchBinaryReader(stream); uint sentinel = reader.UInt32(); if (sentinel != SKETCH_SENTINEL) { Debug.LogFormat("Invalid .tilt: bad sentinel"); return null; } if (brushList == null) { Debug.Log("Invalid .tilt: no brush list"); return null; } int version = reader.Int32(); if (version < REQUIRED_SKETCH_VERSION_MIN || version > REQUIRED_SKETCH_VERSION_MAX) { Debug.LogFormat("Invalid .tilt: unsupported version {0}", version); return null; } reader.Int32(); // reserved for header: must be 0 uint moreHeader = reader.UInt32(); // additional data size if (!reader.Skip(moreHeader)) { return null; } // strokes int iNumMemories = reader.Int32(); var result = new List<Stroke>(); for (int i = 0; i < iNumMemories; ++i) { var stroke = new Stroke(); var brushIndex = reader.Int32(); stroke.m_BrushGuid = (brushIndex < brushList.Length) ? brushList[brushIndex] : Guid.Empty; stroke.m_Color = reader.Color(); stroke.m_BrushSize = reader.Float(); stroke.m_BrushScale = 1f; stroke.m_Seed = 0; uint strokeExtensionMask = reader.UInt32(); uint controlPointExtensionMask = reader.UInt32(); if ((strokeExtensionMask & (int)StrokeExtension.Seed) == 0) { // Backfill for old files saved without seeds. // This is arbitrary but should be determinstic. unchecked { int seed = i; seed = (seed * 397) ^ stroke.m_BrushGuid.GetHashCode(); seed = (seed * 397) ^ stroke.m_Color.GetHashCode(); seed = (seed * 397) ^ stroke.m_BrushSize.GetHashCode(); stroke.m_Seed = seed; } } // stroke extension fields // Iterate through set bits of mask starting from LSB via bit tricks: // isolate lowest set bit: x & ~(x-1) // clear lowest set bit: x & (x-1) for (var fields = strokeExtensionMask; fields != 0; fields &= (fields - 1)) { uint bit = (fields & ~(fields - 1)); switch ((StrokeExtension)bit) { case StrokeExtension.None: // cannot happen Debug.Assert(false); break; case StrokeExtension.Flags: stroke.m_Flags = (StrokeFlags)reader.UInt32(); break; case StrokeExtension.Scale: stroke.m_BrushScale = reader.Float(); break; case StrokeExtension.Group: { UInt32 groupId = reader.UInt32(); stroke.Group = App.GroupManager.GetGroupFromId(groupId); break; } case StrokeExtension.Seed: stroke.m_Seed = reader.Int32(); break; default: { // Skip unknown extension. if ((bit & (uint)StrokeExtension.MaskSingleWord) != 0) { reader.UInt32(); } else { uint size = reader.UInt32(); if (!reader.Skip(size)) { return null; } } break; } } } // control points int nControlPoints = reader.Int32(); stroke.m_ControlPoints = new PointerManager.ControlPoint[nControlPoints]; stroke.m_ControlPointsToDrop = new bool[nControlPoints]; if (allowFastPath && controlPointExtensionMask == PointerManager.ControlPoint.EXTENSIONS) { // Fast path: read (semi-)directly into the ControlPoint[] unsafe { int size = sizeof(PointerManager.ControlPoint) * stroke.m_ControlPoints.Length; fixed (PointerManager.ControlPoint* aPoints = stroke.m_ControlPoints) { if (!reader.ReadInto((IntPtr)aPoints, size)) { return null; } } } } else { // Slow path: deserialize field-by-field. for (int j = 0; j < nControlPoints; ++j) { PointerManager.ControlPoint rControlPoint; rControlPoint.m_Pos = reader.Vec3(); rControlPoint.m_Orient = reader.Quaternion(); // known extension field defaults rControlPoint.m_Pressure = 1.0f; rControlPoint.m_TimestampMs = 0; // control point extension fields for (var fields = controlPointExtensionMask; fields != 0; fields &= (fields - 1)) { switch ((ControlPointExtension)(fields & ~(fields - 1))) { case ControlPointExtension.None: // cannot happen Debug.Assert(false); break; case ControlPointExtension.Pressure: rControlPoint.m_Pressure = reader.Float(); break; case ControlPointExtension.Timestamp: rControlPoint.m_TimestampMs = reader.UInt32(); break; default: // skip unknown extension reader.Int32(); break; } } stroke.m_ControlPoints[j] = rControlPoint; } } // Deserialized strokes are expected in timestamp order, yielding aggregate complexity // of O(N) to populate the by-time linked list. result.Add(stroke); } return result; } } } // namespace TiltBrush
using Lucene.Net.Diagnostics; using System; using System.Text; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using BytesRef = Lucene.Net.Util.BytesRef; using IBits = Lucene.Net.Util.IBits; using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues; /// <summary> /// A range filter built on top of a cached multi-valued term field (in <see cref="IFieldCache"/>). /// /// <para>Like <see cref="FieldCacheRangeFilter"/>, this is just a specialized range query versus /// using a <see cref="TermRangeQuery"/> with <see cref="DocTermOrdsRewriteMethod"/>: it will only do /// two ordinal to term lookups.</para> /// </summary> public abstract class DocTermOrdsRangeFilter : Filter { internal readonly string field; internal readonly BytesRef lowerVal; internal readonly BytesRef upperVal; internal readonly bool includeLower; internal readonly bool includeUpper; private DocTermOrdsRangeFilter(string field, BytesRef lowerVal, BytesRef upperVal, bool includeLower, bool includeUpper) { this.field = field; this.lowerVal = lowerVal; this.upperVal = upperVal; this.includeLower = includeLower; this.includeUpper = includeUpper; } /// <summary> /// This method is implemented for each data type </summary> public override abstract DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs); /// <summary> /// Creates a BytesRef range filter using <see cref="IFieldCache.GetTermsIndex(Index.AtomicReader, string, float)"/>. This works with all /// fields containing zero or one term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// </summary> public static DocTermOrdsRangeFilter NewBytesRefRange(string field, BytesRef lowerVal, BytesRef upperVal, bool includeLower, bool includeUpper) { return new DocTermOrdsRangeFilterAnonymousInnerClassHelper(field, lowerVal, upperVal, includeLower, includeUpper); } private class DocTermOrdsRangeFilterAnonymousInnerClassHelper : DocTermOrdsRangeFilter { public DocTermOrdsRangeFilterAnonymousInnerClassHelper(string field, BytesRef lowerVal, BytesRef upperVal, bool includeLower, bool includeUpper) : base(field, lowerVal, upperVal, includeLower, includeUpper) { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { SortedSetDocValues docTermOrds = FieldCache.DEFAULT.GetDocTermOrds(context.AtomicReader, field); long lowerPoint = lowerVal == null ? -1 : docTermOrds.LookupTerm(lowerVal); long upperPoint = upperVal == null ? -1 : docTermOrds.LookupTerm(upperVal); long inclusiveLowerPoint, inclusiveUpperPoint; // Hints: // * binarySearchLookup returns -1, if value was null. // * the value is <0 if no exact hit was found, the returned value // is (-(insertion point) - 1) if (lowerPoint == -1 && lowerVal == null) { inclusiveLowerPoint = 0; } else if (includeLower && lowerPoint >= 0) { inclusiveLowerPoint = lowerPoint; } else if (lowerPoint >= 0) { inclusiveLowerPoint = lowerPoint + 1; } else { inclusiveLowerPoint = Math.Max(0, -lowerPoint - 1); } if (upperPoint == -1 && upperVal == null) { inclusiveUpperPoint = long.MaxValue; } else if (includeUpper && upperPoint >= 0) { inclusiveUpperPoint = upperPoint; } else if (upperPoint >= 0) { inclusiveUpperPoint = upperPoint - 1; } else { inclusiveUpperPoint = -upperPoint - 2; } if (inclusiveUpperPoint < 0 || inclusiveLowerPoint > inclusiveUpperPoint) { return null; } if (Debugging.AssertsEnabled) Debugging.Assert(inclusiveLowerPoint >= 0 && inclusiveUpperPoint >= 0); return new FieldCacheDocIdSet(context.AtomicReader.MaxDoc, acceptDocs, (doc) => { docTermOrds.SetDocument(doc); long ord; while ((ord = docTermOrds.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS) { if (ord > inclusiveUpperPoint) { return false; } else if (ord >= inclusiveLowerPoint) { return true; } } return false; }); } } public override sealed string ToString() { StringBuilder sb = (new StringBuilder(field)).Append(":"); return sb.Append(includeLower ? '[' : '{') .Append((lowerVal == null) ? "*" : lowerVal.ToString()) .Append(" TO ") .Append((upperVal == null) ? "*" : upperVal.ToString()) .Append(includeUpper ? ']' : '}') .ToString(); } public override sealed bool Equals(object o) { if (this == o) { return true; } if (!(o is DocTermOrdsRangeFilter)) { return false; } DocTermOrdsRangeFilter other = (DocTermOrdsRangeFilter)o; if (!this.field.Equals(other.field, StringComparison.Ordinal) || this.includeLower != other.includeLower || this.includeUpper != other.includeUpper) { return false; } if (this.lowerVal != null ? !this.lowerVal.Equals(other.lowerVal) : other.lowerVal != null) { return false; } if (this.upperVal != null ? !this.upperVal.Equals(other.upperVal) : other.upperVal != null) { return false; } return true; } public override sealed int GetHashCode() { int h = field.GetHashCode(); h ^= (lowerVal != null) ? lowerVal.GetHashCode() : 550356204; h = (h << 1) | ((int)((uint)h >> 31)); // rotate to distinguish lower from upper h ^= (upperVal != null) ? upperVal.GetHashCode() : -1674416163; h ^= (includeLower ? 1549299360 : -365038026) ^ (includeUpper ? 1721088258 : 1948649653); return h; } /// <summary> /// Returns the field name for this filter </summary> public virtual string Field => field; /// <summary> /// Returns <c>true</c> if the lower endpoint is inclusive </summary> public virtual bool IncludesLower => includeLower; /// <summary> /// Returns <c>true</c> if the upper endpoint is inclusive </summary> public virtual bool IncludesUpper => includeUpper; /// <summary> /// Returns the lower value of this range filter </summary> public virtual BytesRef LowerVal => lowerVal; /// <summary> /// Returns the upper value of this range filter </summary> public virtual BytesRef UpperVal => upperVal; } }
// 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.Xml; using System.Runtime.Serialization; using System.Globalization; namespace System.Runtime.Serialization.Json { internal class JsonReaderDelegator : XmlReaderDelegator { private DateTimeFormat _dateTimeFormat; private DateTimeArrayJsonHelperWithString _dateTimeArrayHelper; public JsonReaderDelegator(XmlReader reader) : base(reader) { } public JsonReaderDelegator(XmlReader reader, DateTimeFormat dateTimeFormat) : this(reader) { _dateTimeFormat = dateTimeFormat; } internal XmlDictionaryReaderQuotas ReaderQuotas { get { if (this.dictionaryReader == null) { return null; } else { return dictionaryReader.Quotas; } } } private DateTimeArrayJsonHelperWithString DateTimeArrayHelper { get { if (_dateTimeArrayHelper == null) { _dateTimeArrayHelper = new DateTimeArrayJsonHelperWithString(_dateTimeFormat); } return _dateTimeArrayHelper; } } internal static XmlQualifiedName ParseQualifiedName(string qname) { string name, ns; if (string.IsNullOrEmpty(qname)) { name = ns = String.Empty; } else { qname = qname.Trim(); int colon = qname.IndexOf(':'); if (colon >= 0) { name = qname.Substring(0, colon); ns = qname.Substring(colon + 1); } else { name = qname; ns = string.Empty; } } return new XmlQualifiedName(name, ns); } internal override char ReadContentAsChar() { return XmlConvert.ToChar(ReadContentAsString()); } internal override XmlQualifiedName ReadContentAsQName() { return ParseQualifiedName(ReadContentAsString()); } internal override char ReadElementContentAsChar() { return XmlConvert.ToChar(ReadElementContentAsString()); } public override byte[] ReadContentAsBase64() { if (isEndOfEmptyElement) return Array.Empty<byte>(); byte[] buffer; if (dictionaryReader == null) { XmlDictionaryReader tempDictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader); buffer = ByteArrayHelperWithString.Instance.ReadArray(tempDictionaryReader, JsonGlobals.itemString, string.Empty, tempDictionaryReader.Quotas.MaxArrayLength); } else { buffer = ByteArrayHelperWithString.Instance.ReadArray(dictionaryReader, JsonGlobals.itemString, string.Empty, dictionaryReader.Quotas.MaxArrayLength); } return buffer; } internal override byte[] ReadElementContentAsBase64() { if (isEndOfEmptyElement) { throw new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement")); } bool isEmptyElement = reader.IsStartElement() && reader.IsEmptyElement; byte[] buffer; if (isEmptyElement) { reader.Read(); buffer = Array.Empty<byte>(); } else { reader.ReadStartElement(); buffer = ReadContentAsBase64(); reader.ReadEndElement(); } return buffer; } internal override DateTime ReadContentAsDateTime() { return ParseJsonDate(ReadContentAsString(), _dateTimeFormat); } internal static DateTime ParseJsonDate(string originalDateTimeValue, DateTimeFormat dateTimeFormat) { if (dateTimeFormat == null) { return ParseJsonDateInDefaultFormat(originalDateTimeValue); } else { return DateTime.ParseExact(originalDateTimeValue, dateTimeFormat.FormatString, dateTimeFormat.FormatProvider, dateTimeFormat.DateTimeStyles); } } internal static DateTime ParseJsonDateInDefaultFormat(string originalDateTimeValue) { // Dates are represented in JSON as "\/Date(number of ticks)\/". // The number of ticks is the number of milliseconds since January 1, 1970. string dateTimeValue; if (!string.IsNullOrEmpty(originalDateTimeValue)) { dateTimeValue = originalDateTimeValue.Trim(); } else { dateTimeValue = originalDateTimeValue; } if (string.IsNullOrEmpty(dateTimeValue) || !dateTimeValue.StartsWith(JsonGlobals.DateTimeStartGuardReader, StringComparison.Ordinal) || !dateTimeValue.EndsWith(JsonGlobals.DateTimeEndGuardReader, StringComparison.Ordinal)) { throw new FormatException(SR.Format(SR.JsonInvalidDateTimeString, originalDateTimeValue, JsonGlobals.DateTimeStartGuardWriter, JsonGlobals.DateTimeEndGuardWriter)); } string ticksvalue = dateTimeValue.Substring(6, dateTimeValue.Length - 8); long millisecondsSinceUnixEpoch; DateTimeKind dateTimeKind = DateTimeKind.Utc; int indexOfTimeZoneOffset = ticksvalue.IndexOf('+', 1); if (indexOfTimeZoneOffset == -1) { indexOfTimeZoneOffset = ticksvalue.IndexOf('-', 1); } if (indexOfTimeZoneOffset != -1) { dateTimeKind = DateTimeKind.Local; ticksvalue = ticksvalue.Substring(0, indexOfTimeZoneOffset); } try { millisecondsSinceUnixEpoch = Int64.Parse(ticksvalue, CultureInfo.InvariantCulture); } catch (ArgumentException exception) { throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception); } catch (FormatException exception) { throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception); } catch (OverflowException exception) { throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception); } // Convert from # milliseconds since epoch to # of 100-nanosecond units, which is what DateTime understands long ticks = millisecondsSinceUnixEpoch * 10000 + JsonGlobals.unixEpochTicks; try { DateTime dateTime = new DateTime(ticks, DateTimeKind.Utc); switch (dateTimeKind) { case DateTimeKind.Local: return dateTime.ToLocalTime(); case DateTimeKind.Unspecified: return DateTime.SpecifyKind(dateTime.ToLocalTime(), DateTimeKind.Unspecified); case DateTimeKind.Utc: default: return dateTime; } } catch (ArgumentException exception) { throw XmlExceptionHelper.CreateConversionException(ticksvalue, "DateTime", exception); } } internal override DateTime ReadElementContentAsDateTime() { return ParseJsonDate(ReadElementContentAsString(), _dateTimeFormat); } #if USE_REFEMIT public override bool TryReadDateTimeArray(XmlObjectSerializerReadContext context, #else internal override bool TryReadDateTimeArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out DateTime[] array) { return TryReadJsonDateTimeArray(context, itemName, itemNamespace, arrayLength, out array); } internal bool TryReadJsonDateTimeArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out DateTime[] array) { if ((dictionaryReader == null) || (arrayLength != -1)) { array = null; return false; } array = this.DateTimeArrayHelper.ReadArray(dictionaryReader, XmlDictionaryString.GetString(itemName), XmlDictionaryString.GetString(itemNamespace), GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); return true; } private class DateTimeArrayJsonHelperWithString : ArrayHelper<string, DateTime> { private DateTimeFormat _dateTimeFormat; public DateTimeArrayJsonHelperWithString(DateTimeFormat dateTimeFormat) { _dateTimeFormat = dateTimeFormat; } protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, DateTime[] array, int offset, int count) { XmlJsonReader.CheckArray(array, offset, count); int actual = 0; while (actual < count && reader.IsStartElement(JsonGlobals.itemString, string.Empty)) { array[offset + actual] = JsonReaderDelegator.ParseJsonDate(reader.ReadElementContentAsString(), _dateTimeFormat); actual++; } return actual; } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) { throw NotImplemented.ByDesign; } } // Overridden because base reader relies on XmlConvert.ToUInt64 for conversion to ulong internal override ulong ReadContentAsUnsignedLong() { string value = reader.ReadContentAsString(); if (value == null || value.Length == 0) { throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64"))); } try { return ulong.Parse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo); } catch (ArgumentException exception) { throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception); } catch (FormatException exception) { throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception); } catch (OverflowException exception) { throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception); } } // Overridden because base reader relies on XmlConvert.ToUInt64 for conversion to ulong internal override UInt64 ReadElementContentAsUnsignedLong() { if (isEndOfEmptyElement) { throw new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement")); } string value = reader.ReadElementContentAsString(); if (value == null || value.Length == 0) { throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64"))); } try { return ulong.Parse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo); } catch (ArgumentException exception) { throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception); } catch (FormatException exception) { throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception); } catch (OverflowException exception) { throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception); } } } }
// // System.Web.UI.WebControls.TextBox.cs // // Authors: // Gaurav Vaish ([email protected]) // Andreas Nahr ([email protected]) // // (C) Gaurav Vaish (2002) // (C) 2003 Andreas Nahr // // // 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.Specialized; using System.ComponentModel; using System.Globalization; using System.Web; using System.Web.UI; namespace System.Web.UI.WebControls { #if NET_2_0 [ControlValuePropertyAttribute ("Text")] [DesignerAttribute ("System.Web.UI.Design.WebControls.PreviewControlDesigner, System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.IDesigner")] #endif [ControlBuilder (typeof (TextBoxControlBuilder))] [DefaultEvent("TextChanged")] [DefaultProperty("Text")] [ParseChildren(false)] [ValidationProperty("Text")] [DataBindingHandler("System.Web.UI.Design.TextDataBindingHandler, " + Consts.AssemblySystem_Design)] public class TextBox : WebControl, IPostBackDataHandler { static readonly object TextChangedEvent = new object (); public TextBox() : base (HtmlTextWriterTag.Input) { } #if NET_2_0 [ThemeableAttribute (false)] #endif [DefaultValue (false), WebCategory ("Behavior")] [WebSysDescription ("The control automatically posts back after changing the text.")] public virtual bool AutoPostBack { get { object o = ViewState ["AutoPostBack"]; return (o == null) ? false : (bool) o; } set { ViewState ["AutoPostBack"] = value; } } #if !NET_2_0 [Bindable (true)] #endif [DefaultValue (0), WebCategory ("Appearance")] [WebSysDescription ("The width of this control specified in characters.")] public virtual int Columns { get { object o = ViewState ["Columns"]; return (o == null) ? 0 : (int) o; } set { if (value < 0) throw new ArgumentOutOfRangeException ("value", "Columns value has to be 0 for 'not set' or bigger than 0."); ViewState ["Columns"] = value; } } #if NET_2_0 [ThemeableAttribute (false)] #else [Bindable (true)] #endif [DefaultValue (0), WebCategory ("Behavior")] [WebSysDescription ("The maximum number of characters you can enter in this control.")] public virtual int MaxLength { get { object o = ViewState ["MaxLength"]; return (o == null) ? 0 : (int) o; } set { if (value < 0) throw new ArgumentOutOfRangeException ("value", "MaxLength value has to be 0 for 'not set' or bigger than 0."); ViewState ["MaxLength"] = value; } } #if NET_2_0 [ThemeableAttribute (false)] #endif [DefaultValue (false), Bindable (true), WebCategory ("Behavior")] [WebSysDescription ("If the control is ReadOnly you cannot enter new text.")] public virtual bool ReadOnly { get { object o = ViewState ["ReadOnly"]; return (o == null) ? false : (bool) o; } set { ViewState ["ReadOnly"] = value; } } #if NET_2_0 [ThemeableAttribute (false)] #else [Bindable (true)] #endif [DefaultValue (0), WebCategory ("Behavior")] [WebSysDescription ("The number of lines that this multiline contol spans.")] public virtual int Rows { get { object o = ViewState ["Rows"]; return (o == null) ? 0 : (int) o; } set { if (value < 0) throw new ArgumentOutOfRangeException ("value", "Rows value has to be 0 for 'not set' or bigger than 0."); ViewState ["Rows"] = value; } } #if NET_2_0 [LocalizableAttribute (true)] [EditorAttribute ("System.ComponentModel.Design.MultilineStringEditor,System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] #endif [DefaultValue (""), Bindable (true), WebCategory ("Appearance")] [PersistenceMode (PersistenceMode.EncodedInnerDefaultProperty)] [WebSysDescription ("The text that this control initially displays.")] public virtual string Text { get { object o = ViewState ["Text"]; return (o == null) ? String.Empty : (string) o; } set { ViewState ["Text"] = value; } } #if NET_2_0 [ThemeableAttribute (false)] #endif [DefaultValue (typeof (TextBoxMode), "SingleLine"), WebCategory ("Behavior")] [WebSysDescription ("A mode of how the control operates.")] public virtual TextBoxMode TextMode { get { object o = ViewState ["TextMode"]; return (o == null) ? TextBoxMode.SingleLine : (TextBoxMode) o; } set { if(!Enum.IsDefined (typeof(TextBoxMode), value)) throw new ArgumentOutOfRangeException ("value", "Only existing modes are allowed"); ViewState ["TextMode"] = value; } } [DefaultValue (true), WebCategory ("Layout")] [WebSysDescription ("Determines if a line wraps at line-end.")] public virtual bool Wrap { get { object o = ViewState ["Wrap"]; return (o == null) ? true : (bool) o; } set { ViewState ["Wrap"] = value; } } [WebCategory ("Action")] [WebSysDescription ("Raised when the text is changed.")] public event EventHandler TextChanged { add { Events.AddHandler (TextChangedEvent, value); } remove { Events.RemoveHandler (TextChangedEvent, value); } } protected override HtmlTextWriterTag TagKey { get { if(TextMode == TextBoxMode.MultiLine) return HtmlTextWriterTag.Textarea; return HtmlTextWriterTag.Input; } } protected override void AddAttributesToRender (HtmlTextWriter writer) { if(Page != null) Page.VerifyRenderingInServerForm (this); NumberFormatInfo invar = NumberFormatInfo.InvariantInfo; writer.AddAttribute (HtmlTextWriterAttribute.Name, UniqueID); if (TextMode == TextBoxMode.MultiLine) { if (Rows > 0) writer.AddAttribute (HtmlTextWriterAttribute.Rows, Rows.ToString (invar)); if (Columns > 0) writer.AddAttribute (HtmlTextWriterAttribute.Cols, Columns.ToString (invar)); if (!Wrap) writer.AddAttribute(HtmlTextWriterAttribute.Wrap, "off"); } else { string mode; if (TextMode == TextBoxMode.Password) { mode = "password"; } else { mode = "text"; if (Text.Length > 0) writer.AddAttribute (HtmlTextWriterAttribute.Value, Text); } writer.AddAttribute (HtmlTextWriterAttribute.Type, mode); if (MaxLength > 0) writer.AddAttribute (HtmlTextWriterAttribute.Maxlength, MaxLength.ToString (invar)); if (Columns > 0) writer.AddAttribute (HtmlTextWriterAttribute.Size, Columns.ToString (invar)); } if (ReadOnly) writer.AddAttribute (HtmlTextWriterAttribute.ReadOnly, "readonly"); base.AddAttributesToRender (writer); if (AutoPostBack && Page != null){ writer.AddAttribute (HtmlTextWriterAttribute.Onchange, Page.ClientScript.GetPostBackClientEvent (this, "")); writer.AddAttribute ("language", "javascript"); } } protected override void AddParsedSubObject(object obj) { if(!(obj is LiteralControl)) throw new HttpException ("Cannot have children of type" + obj.GetType ()); Text = ((LiteralControl) obj).Text; } protected override void OnPreRender (EventArgs e) { base.OnPreRender (e); bool enabled = Enabled; if (Page != null) { if (AutoPostBack && enabled) Page.RequiresPostBackScript (); } /* Don't save passwords in ViewState */ if (TextMode == TextBoxMode.Password || (enabled && Visible && Events [TextChangedEvent] == null)) ViewState.SetItemDirty ("Text", false); } protected virtual void OnTextChanged (EventArgs e) { if(Events != null){ EventHandler eh = (EventHandler) (Events [TextChangedEvent]); if(eh != null) eh (this, e); } } protected override void Render (HtmlTextWriter writer) { RenderBeginTag(writer); if (TextMode == TextBoxMode.MultiLine) HttpUtility.HtmlEncode (Text, writer); RenderEndTag(writer); } #if NET_2_0 bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection) { return LoadPostData (postDataKey, postCollection); } protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection) #else bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection) #endif { if (postCollection [postDataKey] != Text){ Text = postCollection [postDataKey]; return true; } return false; } #if NET_2_0 void IPostBackDataHandler.RaisePostDataChangedEvent () { RaisePostDataChangedEvent (); } protected virtual void RaisePostDataChangedEvent () { OnTextChanged (EventArgs.Empty); } #else void IPostBackDataHandler.RaisePostDataChangedEvent () { OnTextChanged (EventArgs.Empty); } #endif } }
namespace VersionOne.ServiceHost.ConfigurationTool { partial class ConfigurationForm { /// <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.msMenu = new System.Windows.Forms.MenuStrip(); this.miFile = new System.Windows.Forms.ToolStripMenuItem(); this.miNewFile = new System.Windows.Forms.ToolStripMenuItem(); this.miOpenFile = new System.Windows.Forms.ToolStripMenuItem(); this.miSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.miSaveFile = new System.Windows.Forms.ToolStripMenuItem(); this.miSaveFileAs = new System.Windows.Forms.ToolStripMenuItem(); this.miSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.miExit = new System.Windows.Forms.ToolStripMenuItem(); this.miTools = new System.Windows.Forms.ToolStripMenuItem(); this.miGenerateSnapshot = new System.Windows.Forms.ToolStripMenuItem(); this.miSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.miOptions = new System.Windows.Forms.ToolStripMenuItem(); this.miHelp = new System.Windows.Forms.ToolStripMenuItem(); this.miAbout = new System.Windows.Forms.ToolStripMenuItem(); this.tsMenu = new System.Windows.Forms.ToolStrip(); this.tsbOpen = new System.Windows.Forms.ToolStripButton(); this.tsbSave = new System.Windows.Forms.ToolStripButton(); this.ctlSplitContainer = new System.Windows.Forms.SplitContainer(); this.tvServices = new System.Windows.Forms.TreeView(); this.pnlControlHolder = new System.Windows.Forms.Panel(); this.pnlHeader = new System.Windows.Forms.Panel(); this.lblHeader = new System.Windows.Forms.Label(); this.msMenu.SuspendLayout(); this.tsMenu.SuspendLayout(); this.ctlSplitContainer.Panel1.SuspendLayout(); this.ctlSplitContainer.Panel2.SuspendLayout(); this.ctlSplitContainer.SuspendLayout(); this.pnlHeader.SuspendLayout(); this.SuspendLayout(); // // msMenu // this.msMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miFile, this.miTools, this.miHelp}); this.msMenu.Location = new System.Drawing.Point(0, 0); this.msMenu.Name = "msMenu"; this.msMenu.Size = new System.Drawing.Size(750, 24); this.msMenu.TabIndex = 0; this.msMenu.Text = "menuStrip1"; // // miFile // this.miFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miNewFile, this.miOpenFile, this.miSeparator1, this.miSaveFile, this.miSaveFileAs, this.miSeparator2, this.miExit}); this.miFile.Name = "miFile"; this.miFile.Size = new System.Drawing.Size(35, 20); this.miFile.Text = "&File"; // // miNewFile // this.miNewFile.Image = global::VersionOne.ServiceHost.ConfigurationTool.Resources.NewFileImage; this.miNewFile.ImageTransparentColor = System.Drawing.Color.Magenta; this.miNewFile.Name = "miNewFile"; this.miNewFile.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.miNewFile.Size = new System.Drawing.Size(151, 22); this.miNewFile.Text = "&New"; // // miOpenFile // this.miOpenFile.Image = global::VersionOne.ServiceHost.ConfigurationTool.Resources.OpenFileImage; this.miOpenFile.ImageTransparentColor = System.Drawing.Color.Magenta; this.miOpenFile.Name = "miOpenFile"; this.miOpenFile.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.miOpenFile.Size = new System.Drawing.Size(151, 22); this.miOpenFile.Text = "&Open"; // // miSeparator1 // this.miSeparator1.Name = "miSeparator1"; this.miSeparator1.Size = new System.Drawing.Size(148, 6); // // miSaveFile // this.miSaveFile.Image = global::VersionOne.ServiceHost.ConfigurationTool.Resources.SaveFileImage; this.miSaveFile.ImageTransparentColor = System.Drawing.Color.Magenta; this.miSaveFile.Name = "miSaveFile"; this.miSaveFile.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.miSaveFile.Size = new System.Drawing.Size(151, 22); this.miSaveFile.Text = "&Save"; // // miSaveFileAs // this.miSaveFileAs.Name = "miSaveFileAs"; this.miSaveFileAs.Size = new System.Drawing.Size(151, 22); this.miSaveFileAs.Text = "Save &As"; // // miSeparator2 // this.miSeparator2.Name = "miSeparator2"; this.miSeparator2.Size = new System.Drawing.Size(148, 6); // // miExit // this.miExit.Name = "miExit"; this.miExit.Size = new System.Drawing.Size(151, 22); this.miExit.Text = "E&xit"; // // miTools // this.miTools.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miGenerateSnapshot, this.miSeparator3, this.miOptions}); this.miTools.Name = "miTools"; this.miTools.Size = new System.Drawing.Size(44, 20); this.miTools.Text = "&Tools"; // // miGenerateSnapshot // this.miGenerateSnapshot.Name = "miGenerateSnapshot"; this.miGenerateSnapshot.Size = new System.Drawing.Size(206, 22); this.miGenerateSnapshot.Text = "Create settings snapshot"; // // miSeparator3 // this.miSeparator3.Name = "miSeparator3"; this.miSeparator3.Size = new System.Drawing.Size(203, 6); // // miOptions // this.miOptions.Name = "miOptions"; this.miOptions.Size = new System.Drawing.Size(206, 22); this.miOptions.Text = "&Options"; // // miHelp // this.miHelp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miAbout}); this.miHelp.Name = "miHelp"; this.miHelp.Size = new System.Drawing.Size(40, 20); this.miHelp.Text = "&Help"; // // miAbout // this.miAbout.Name = "miAbout"; this.miAbout.Size = new System.Drawing.Size(126, 22); this.miAbout.Text = "&About..."; // // tsMenu // this.tsMenu.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.tsMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tsbOpen, this.tsbSave}); this.tsMenu.Location = new System.Drawing.Point(0, 24); this.tsMenu.Name = "tsMenu"; this.tsMenu.Size = new System.Drawing.Size(750, 25); this.tsMenu.TabIndex = 1; this.tsMenu.Text = "toolStrip1"; // // tsbOpen // this.tsbOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tsbOpen.Image = global::VersionOne.ServiceHost.ConfigurationTool.Resources.OpenFileImage; this.tsbOpen.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsbOpen.Name = "tsbOpen"; this.tsbOpen.Size = new System.Drawing.Size(23, 22); this.tsbOpen.Text = "Open configuration"; // // tsbSave // this.tsbSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tsbSave.Image = global::VersionOne.ServiceHost.ConfigurationTool.Resources.SaveFileImage; this.tsbSave.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsbSave.Name = "tsbSave"; this.tsbSave.Size = new System.Drawing.Size(23, 22); this.tsbSave.Text = "Save changes"; // // ctlSplitContainer // this.ctlSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.ctlSplitContainer.Location = new System.Drawing.Point(0, 49); this.ctlSplitContainer.Name = "ctlSplitContainer"; // // ctlSplitContainer.Panel1 // this.ctlSplitContainer.Panel1.Controls.Add(this.tvServices); // // ctlSplitContainer.Panel2 // this.ctlSplitContainer.Panel2.Controls.Add(this.pnlControlHolder); this.ctlSplitContainer.Panel2.Controls.Add(this.pnlHeader); this.ctlSplitContainer.Size = new System.Drawing.Size(750, 671); this.ctlSplitContainer.SplitterDistance = 249; this.ctlSplitContainer.TabIndex = 2; // // tvServices // this.tvServices.Dock = System.Windows.Forms.DockStyle.Fill; this.tvServices.Location = new System.Drawing.Point(0, 0); this.tvServices.Name = "tvServices"; this.tvServices.Size = new System.Drawing.Size(249, 671); this.tvServices.TabIndex = 0; // // pnlControlHolder // this.pnlControlHolder.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pnlControlHolder.Location = new System.Drawing.Point(0, 29); this.pnlControlHolder.Name = "pnlControlHolder"; this.pnlControlHolder.Size = new System.Drawing.Size(501, 747); this.pnlControlHolder.TabIndex = 1; // // pnlHeader // this.pnlHeader.BackColor = System.Drawing.Color.Gainsboro; this.pnlHeader.Controls.Add(this.lblHeader); this.pnlHeader.Dock = System.Windows.Forms.DockStyle.Top; this.pnlHeader.Location = new System.Drawing.Point(0, 0); this.pnlHeader.Name = "pnlHeader"; this.pnlHeader.Size = new System.Drawing.Size(497, 29); this.pnlHeader.TabIndex = 0; // // lblHeader // this.lblHeader.AutoSize = true; this.lblHeader.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.lblHeader.Location = new System.Drawing.Point(4, 2); this.lblHeader.Name = "lblHeader"; this.lblHeader.Size = new System.Drawing.Size(193, 24); this.lblHeader.TabIndex = 0; this.lblHeader.Text = "Current Service name"; // // ConfigurationForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(750, 720); this.Controls.Add(this.ctlSplitContainer); this.Controls.Add(this.tsMenu); this.Controls.Add(this.msMenu); this.Icon = global::VersionOne.ServiceHost.ConfigurationTool.Resources.V1Logo; this.MainMenuStrip = this.msMenu; this.MinimumSize = new System.Drawing.Size(750, 720); this.Name = "ConfigurationForm"; this.Text = "ServiceHost Settings"; this.msMenu.ResumeLayout(false); this.msMenu.PerformLayout(); this.tsMenu.ResumeLayout(false); this.tsMenu.PerformLayout(); this.ctlSplitContainer.Panel1.ResumeLayout(false); this.ctlSplitContainer.Panel2.ResumeLayout(false); this.ctlSplitContainer.ResumeLayout(false); this.pnlHeader.ResumeLayout(false); this.pnlHeader.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion // There is known bug in code generation for SplitContainer, the order of generated statements makes it fail. // That's why this part should be extracted to separate method to be called just after InitializeComponent. private void PostInitializeComponent() { ctlSplitContainer.Panel1MinSize = 100; ctlSplitContainer.Panel2MinSize = 450; ctlSplitContainer.SplitterDistance = 208; } private System.Windows.Forms.MenuStrip msMenu; private System.Windows.Forms.ToolStripMenuItem miFile; private System.Windows.Forms.ToolStripMenuItem miNewFile; private System.Windows.Forms.ToolStripMenuItem miOpenFile; private System.Windows.Forms.ToolStripSeparator miSeparator1; private System.Windows.Forms.ToolStripMenuItem miSaveFile; private System.Windows.Forms.ToolStripMenuItem miSaveFileAs; private System.Windows.Forms.ToolStripSeparator miSeparator2; private System.Windows.Forms.ToolStripMenuItem miExit; private System.Windows.Forms.ToolStripMenuItem miTools; private System.Windows.Forms.ToolStripMenuItem miOptions; private System.Windows.Forms.ToolStripMenuItem miHelp; private System.Windows.Forms.ToolStripMenuItem miAbout; private System.Windows.Forms.ToolStrip tsMenu; private System.Windows.Forms.ToolStripMenuItem miGenerateSnapshot; private System.Windows.Forms.ToolStripSeparator miSeparator3; private System.Windows.Forms.ToolStripButton tsbOpen; private System.Windows.Forms.ToolStripButton tsbSave; private System.Windows.Forms.SplitContainer ctlSplitContainer; private System.Windows.Forms.TreeView tvServices; private System.Windows.Forms.Panel pnlHeader; private System.Windows.Forms.Label lblHeader; private System.Windows.Forms.Panel pnlControlHolder; } }
// ReSharper disable UseNameofExpression // ReSharper disable CheckNamespace namespace Should.Core.Assertions { using System; using System.Collections; using System.Collections.Generic; using Exceptions; /// <summary> /// Contains various static methods that are used to verify that conditions are met during the /// process of running tests. /// </summary> public class Assert { /// <summary> /// Used by the Throws and DoesNotThrow methods. /// </summary> public delegate void ThrowsDelegate(); /// <summary> /// Used by the Throws and DoesNotThrow methods. /// </summary> public delegate object ThrowsDelegateWithReturn(); /// <summary> /// Initializes a new instance of the <see cref="Assert"/> class. /// </summary> protected Assert() { } /// <summary> /// Verifies that a collection contains a given object. /// </summary> /// <typeparam name="T">The type of the object to be verified</typeparam> /// <param name="expected">The object expected to be in the collection</param> /// <param name="collection">The collection to be inspected</param> /// <exception cref="ContainsException">Thrown when the object is not present in the collection</exception> public static void Contains<T>(T expected, IEnumerable<T> collection) { Contains(expected, collection, GetEqualityComparer<T>()); } /// <summary> /// Verifies that a collection contains a given object, using an equality comparer. /// </summary> /// <typeparam name="T">The type of the object to be verified</typeparam> /// <param name="expected">The object expected to be in the collection</param> /// <param name="collection">The collection to be inspected</param> /// <param name="comparer">The comparer used to equate objects in the collection with the expected object</param> /// <exception cref="ContainsException">Thrown when the object is not present in the collection</exception> public static void Contains<T>(T expected, IEnumerable<T> collection, IEqualityComparer<T> comparer) { // ReSharper disable once LoopCanBeConvertedToQuery foreach (var item in collection) if (comparer.Equals(expected, item)) return; throw new ContainsException(expected); } /// <summary> /// Verifies that a string contains a given sub-string, using the current culture. /// </summary> /// <param name="expectedSubString">The sub-string expected to be in the string</param> /// <param name="actualString">The string to be inspected</param> /// <exception cref="ContainsException">Thrown when the sub-string is not present inside the string</exception> public static int Contains(string expectedSubString, string actualString) { return Contains(expectedSubString, actualString, StringComparison.CurrentCulture); } /// <summary> /// Verifies that a string contains a given sub-string, using the given comparison type. /// </summary> /// <param name="expectedSubString">The sub-string expected to be in the string</param> /// <param name="actualString">The string to be inspected</param> /// <param name="comparisonType">The type of string comparison to perform</param> /// <exception cref="ContainsException">Thrown when the sub-string is not present inside the string</exception> public static int Contains(string expectedSubString, string actualString, StringComparison comparisonType) { var indexOf = actualString.IndexOf(expectedSubString, comparisonType); if (indexOf < 0) throw new ContainsException(expectedSubString); return indexOf; } /// <summary> /// /// </summary> /// <param name="expectedStartString"></param> /// <param name="actualString"></param> /// <exception cref="StartsWithException">Thrown when the sub-string is not present at the start of the string</exception> public static void StartsWith(string expectedStartString, string actualString) { if (actualString.StartsWith(expectedStartString) == false) throw new StartsWithException(expectedStartString, actualString); } /// <summary> /// Verifies that a collection does not contain a given object. /// </summary> /// <typeparam name="T">The type of the object to be compared</typeparam> /// <param name="expected">The object that is expected not to be in the collection</param> /// <param name="collection">The collection to be inspected</param> /// <exception cref="DoesNotContainException">Thrown when the object is present inside the container</exception> public static void DoesNotContain<T>(T expected, IEnumerable<T> collection) { DoesNotContain(expected, collection, GetEqualityComparer<T>()); } /// <summary> /// Verifies that a collection does not contain a given object, using an equality comparer. /// </summary> /// <typeparam name="T">The type of the object to be compared</typeparam> /// <param name="expected">The object that is expected not to be in the collection</param> /// <param name="collection">The collection to be inspected</param> /// <param name="comparer">The comparer used to equate objects in the collection with the expected object</param> /// <exception cref="DoesNotContainException">Thrown when the object is present inside the container</exception> public static void DoesNotContain<T>(T expected, IEnumerable<T> collection, IEqualityComparer<T> comparer) { // ReSharper disable once LoopCanBeConvertedToQuery foreach (var item in collection) if (comparer.Equals(expected, item)) throw new DoesNotContainException(expected); } /// <summary> /// Verifies that a string does not contain a given sub-string, using the current culture. /// </summary> /// <param name="expectedSubString">The sub-string which is expected not to be in the string</param> /// <param name="actualString">The string to be inspected</param> /// <exception cref="DoesNotContainException">Thrown when the sub-string is present inside the string</exception> public static void DoesNotContain(string expectedSubString, string actualString) { DoesNotContain(expectedSubString, actualString, StringComparison.CurrentCulture); } /// <summary> /// Verifies that a string does not contain a given sub-string, using the current culture. /// </summary> /// <param name="expectedSubString">The sub-string which is expected not to be in the string</param> /// <param name="actualString">The string to be inspected</param> /// <param name="comparisonType">The type of string comparison to perform</param> /// <exception cref="DoesNotContainException">Thrown when the sub-string is present inside the given string</exception> public static void DoesNotContain(string expectedSubString, string actualString, StringComparison comparisonType) { if (actualString.IndexOf(expectedSubString, comparisonType) >= 0) throw new DoesNotContainException(expectedSubString); } ///// <summary> ///// Verifies that a block of code does not throw any exceptions. ///// </summary> ///// <param name="testCode">A delegate to the code to be tested</param> //public static void DoesNotThrow(ThrowsDelegate testCode) //{ // Exception ex = Record.Exception(testCode); // if (ex != null) // throw new DoesNotThrowException(ex); //} /// <summary> /// Verifies that a collection is empty. /// </summary> /// <param name="collection">The collection to be inspected</param> /// <exception cref="ArgumentNullException">Thrown when the collection is null</exception> /// <exception cref="EmptyException">Thrown when the collection is not empty</exception> public static void Empty(IEnumerable collection) { if (collection == null) throw new ArgumentNullException("collection", "cannot be null"); #pragma warning disable 168 // ReSharper disable once LoopCanBeConvertedToQuery // ReSharper disable once UnusedVariable foreach (var @object in collection) throw new EmptyException(); #pragma warning restore 168 } /// <summary> /// Verifies that two objects are equal, using a default comparer. /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> /// <param name="expected">The expected value</param> /// <param name="actual">The value to be compared against</param> /// <exception cref="EqualException">Thrown when the objects are not equal</exception> public static void Equal<T>(T expected, T actual) { Equal(expected, actual, GetEqualityComparer<T>()); } /// <summary> /// Verifies that two objects are equal, using a default comparer. /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> /// <param name="expected">The expected value</param> /// <param name="actual">The value to be compared against</param> /// <param name="userMessage">The user message to be shown on failure</param> /// <exception cref="EqualException">Thrown when the objects are not equal</exception> public static void Equal<T>(T expected, T actual, string userMessage) { Equal(expected, actual, GetEqualityComparer<T>(), userMessage); } /// <summary> /// Verifies that two objects are equal, using a custom comparer. /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> /// <param name="expected">The expected value</param> /// <param name="actual">The value to be compared against</param> /// <param name="comparer">The comparer used to compare the two objects</param> /// <exception cref="EqualException">Thrown when the objects are not equal</exception> public static void Equal<T>(T expected, T actual, IEqualityComparer<T> comparer) { if (!comparer.Equals(expected, actual)) throw new EqualException(expected, actual); } /// <summary> /// Verifies that two objects are equal, using a custom comparer. /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> /// <param name="expected">The expected value</param> /// <param name="actual">The value to be compared against</param> /// <param name="comparer">The comparer used to compare the two objects</param> /// <param name="userMessage"></param> /// <exception cref="EqualException">Thrown when the objects are not equal</exception> public static void Equal<T>(T expected, T actual, IEqualityComparer<T> comparer, string userMessage) { if (!comparer.Equals(expected, actual)) throw new EqualException(expected, actual, userMessage); } /// <summary> /// Verifies that two doubles are equal within a tolerance range. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The value to compare against</param> /// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param> public static void Equal(double expected, double actual, double tolerance) { var difference = Math.Abs(actual - expected); if (difference > tolerance) throw new EqualException(expected + " +/- " + tolerance, actual); } /// <summary> /// Verifies that two doubles are equal within a tolerance range. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The value to compare against</param> /// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param> /// <param name="userMessage">The user message to be shown on failure</param> public static void Equal(double expected, double actual, double tolerance, string userMessage) { var difference = Math.Abs(actual - expected); if (difference > tolerance) throw new EqualException(expected + " +/- " + tolerance, actual, userMessage); } /// <summary> /// Verifies that two values are not equal, using a default comparer. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param> /// <exception cref="NotEqualException">Thrown when the objects are equal</exception> public static void NotEqual(double expected, double actual, double tolerance) { var difference = Math.Abs(actual - expected); if (difference <= tolerance) throw new NotEqualException(expected + " +/- " + tolerance, actual); } /// <summary> /// Verifies that two values are not equal, using a default comparer. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param> /// <param name="userMessage">The user message to be shown on failure</param> /// <exception cref="NotEqualException">Thrown when the objects are equal</exception> public static void NotEqual(double expected, double actual, double tolerance, string userMessage) { var difference = Math.Abs(actual - expected); if (difference <= tolerance) throw new NotEqualException(expected + " +/- " + tolerance, actual, userMessage); } /// <summary> /// Verifies that two dates are equal within a tolerance range. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The value to compare against</param> /// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param> public static void Equal(DateTime expected, DateTime actual, TimeSpan tolerance) { var difference = Math.Abs((actual - expected).Ticks); if (difference > tolerance.Ticks) throw new EqualException(expected + " +/- " + tolerance, actual); } /// <summary> /// Verifies that two dates are not equal within a tolerance range. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The value to compare against</param> /// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param> public static void NotEqual(DateTime expected, DateTime actual, TimeSpan tolerance) { var difference = Math.Abs((actual - expected).Ticks); if (difference <= tolerance.Ticks) throw new NotEqualException(expected + " +/- " + tolerance, actual); } /// <summary> /// Verifies that two dates are equal within a tolerance range. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The value to compare against</param> /// <param name="precision">The level of precision to use when making the comparison</param> public static void Equal(DateTime expected, DateTime actual, DatePrecision precision) { if (precision.Truncate(expected) != precision.Truncate(actual)) throw new EqualException(precision.Truncate(actual), precision.Truncate(actual)); } /// <summary> /// Verifies that two doubles are not equal within a tolerance range. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The value to compare against</param> /// <param name="precision">The level of precision to use when making the comparison</param> public static void NotEqual(DateTime expected, DateTime actual, DatePrecision precision) { if (precision.Truncate(expected) == precision.Truncate(actual)) throw new NotEqualException(precision.Truncate(actual), precision.Truncate(actual)); } /// <summary>Do not call this method.</summary> [Obsolete("This is an override of Object.Equals(). Call Assert.Equal() instead.", true)] public new static bool Equals(object a, object b) { throw new InvalidOperationException("Assert.Equals should not be used"); } /// <summary> /// Verifies that the condition is false. /// </summary> /// <param name="condition">The condition to be tested</param> /// <exception cref="FalseException">Thrown if the condition is not false</exception> public static void False(bool condition) { False(condition, null); } /// <summary> /// Verifies that the condition is false. /// </summary> /// <param name="condition">The condition to be tested</param> /// <param name="userMessage">The message to show when the condition is not false</param> /// <exception cref="FalseException">Thrown if the condition is not false</exception> public static void False(bool condition, string userMessage) { if (condition) throw new FalseException(userMessage); } private static IEqualityComparer<T> GetEqualityComparer<T>() { return new AssertEqualityComparer<T>(); } private static IComparer<T> GetComparer<T>() { return new AssertComparer<T>(); } /// <summary>Verifies that an object is greater than the exclusive minimum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="left">The object to be evaluated.</param> /// <param name="right">An object representing the exclusive minimum value of paramref name="value"/>.</param> public static void GreaterThan<T>(T left, T right) { GreaterThan(left, right, GetComparer<T>()); } /// <summary>Verifies that an object is greater than the exclusive minimum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="left">The object to be evaluated.</param> /// <param name="right">An object representing the exclusive minimum value of paramref name="value"/>.</param> /// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param> public static void GreaterThan<T>(T left, T right, IComparer<T> comparer) { if (comparer.Compare(left, right) <= 0) throw new GreaterThanException(left, right); } /// <summary>Verifies that an object is greater than the inclusive minimum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="left">The object to be evaluated.</param> /// <param name="right">An object representing the inclusive minimum value of paramref name="value"/>.</param> public static void GreaterThanOrEqual<T>(T left, T right) { GreaterThanOrEqual(left, right, GetComparer<T>()); } /// <summary>Verifies that an object is greater than the inclusive minimum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="left">The object to be evaluated.</param> /// <param name="right">An object representing the inclusive minimum value of paramref name="value"/>.</param> /// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param> public static void GreaterThanOrEqual<T>(T left, T right, IComparer<T> comparer) { if (comparer.Compare(left, right) < 0) throw new GreaterThanOrEqualException(left, right); } /// <summary> /// Verifies that a value is within a given range. /// </summary> /// <typeparam name="T">The type of the value to be compared</typeparam> /// <param name="actual">The actual value to be evaluated</param> /// <param name="low">The (inclusive) low value of the range</param> /// <param name="high">The (inclusive) high value of the range</param> /// <exception cref="InRangeException">Thrown when the value is not in the given range</exception> public static void InRange<T>(T actual, T low, T high) { InRange(actual, low, high, GetComparer<T>()); } /// <summary> /// Verifies that a value is within a given range, using a comparer. /// </summary> /// <typeparam name="T">The type of the value to be compared</typeparam> /// <param name="actual">The actual value to be evaluated</param> /// <param name="low">The (inclusive) low value of the range</param> /// <param name="high">The (inclusive) high value of the range</param> /// <param name="comparer">The comparer used to evaluate the value's range</param> /// <exception cref="InRangeException">Thrown when the value is not in the given range</exception> public static void InRange<T>(T actual, T low, T high, IComparer<T> comparer) { if (comparer.Compare(low, actual) > 0 || comparer.Compare(actual, high) > 0) throw new InRangeException(actual, low, high); } /// <summary> /// Verifies that an object is of the given type or a derived type. /// </summary> /// <typeparam name="T">The type the object should be</typeparam> /// <param name="object">The object to be evaluated</param> /// <returns>The object, casted to type T when successful</returns> /// <exception cref="IsAssignableFromException">Thrown when the object is not the given type</exception> public static T IsAssignableFrom<T>(object @object) { IsAssignableFrom(typeof (T), @object); return (T) @object; } /// <summary> /// Verifies that an object is of the given type or a derived type. /// </summary> /// <param name="expectedType">The type the object should be</param> /// <param name="object">The object to be evaluated</param> /// <exception cref="IsAssignableFromException">Thrown when the object is not the given type</exception> public static void IsAssignableFrom(Type expectedType, object @object) { // ReSharper disable once UseMethodIsInstanceOfType if (@object == null || !expectedType.IsAssignableFrom(@object.GetType())) throw new IsAssignableFromException(expectedType, @object); } /// <summary> /// Verifies that an object is of the given type or a derived type. /// </summary> /// <typeparam name="T">The type the object should be</typeparam> /// <param name="object">The object to be evaluated</param> /// <param name="userMessage">The user message to show on failure</param> /// <returns>The object, casted to type T when successful</returns> /// <exception cref="IsAssignableFromException">Thrown when the object is not the given type</exception> public static T IsAssignableFrom<T>(object @object, string userMessage) { IsAssignableFrom(typeof (T), @object, userMessage); return (T) @object; } /// <summary> /// Verifies that an object is of the given type or a derived type. /// </summary> /// <param name="expectedType">The type the object should be</param> /// <param name="userMessage">The user message to show on failure</param> /// <param name="object">The object to be evaluated</param> /// <exception cref="IsAssignableFromException">Thrown when the object is not the given type</exception> public static void IsAssignableFrom(Type expectedType, object @object, string userMessage) { // ReSharper disable once UseMethodIsInstanceOfType if (@object == null || !expectedType.IsAssignableFrom(@object.GetType())) throw new IsAssignableFromException(expectedType, @object, userMessage); } /// <summary> /// Verifies that an object is not exactly the given type. /// </summary> /// <typeparam name="T">The type the object should not be</typeparam> /// <param name="object">The object to be evaluated</param> /// <exception cref="IsNotTypeException">Thrown when the object is the given type</exception> public static void IsNotType<T>(object @object) { IsNotType(typeof (T), @object); } /// <summary> /// Verifies that an object is not exactly the given type. /// </summary> /// <param name="expectedType">The type the object should not be</param> /// <param name="object">The object to be evaluated</param> /// <exception cref="IsNotTypeException">Thrown when the object is the given type</exception> public static void IsNotType(Type expectedType, object @object) { // ReSharper disable once CheckForReferenceEqualityInstead.1 if (expectedType.Equals(@object.GetType())) throw new IsNotTypeException(expectedType, @object); } /// <summary> /// Verifies that an object is exactly the given type (and not a derived type). /// </summary> /// <typeparam name="T">The type the object should be</typeparam> /// <param name="object">The object to be evaluated</param> /// <returns>The object, casted to type T when successful</returns> /// <exception cref="IsTypeException">Thrown when the object is not the given type</exception> public static T IsType<T>(object @object) { IsType(typeof (T), @object); return (T) @object; } /// <summary> /// Verifies that an object is exactly the given type (and not a derived type). /// </summary> /// <param name="expectedType">The type the object should be</param> /// <param name="object">The object to be evaluated</param> /// <exception cref="IsTypeException">Thrown when the object is not the given type</exception> public static void IsType(Type expectedType, object @object) { // ReSharper disable once CheckForReferenceEqualityInstead.1 if (@object == null || !expectedType.Equals(@object.GetType())) throw new IsTypeException(expectedType, @object); } /// <summary>Verifies that an object is less than the exclusive maximum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="left">The object to be evaluated.</param> /// <param name="right">An object representing the exclusive maximum value of paramref name="value"/>.</param> public static void LessThan<T>(T left, T right) { LessThan(left, right, GetComparer<T>()); } /// <summary>Verifies that an object is less than the exclusive maximum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="left">The object to be evaluated.</param> /// <param name="right">An object representing the exclusive maximum value of paramref name="value"/>.</param> /// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param> public static void LessThan<T>(T left, T right, IComparer<T> comparer) { if (comparer.Compare(left, right) >= 0) throw new LessThanException(left, right); } /// <summary>Verifies that an object is less than the inclusive maximum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="left">The object to be evaluated.</param> /// <param name="right">An object representing the inclusive maximum value of paramref name="value"/>.</param> public static void LessThanOrEqual<T>(T left, T right) { LessThanOrEqual(left, right, GetComparer<T>()); } /// <summary>Verifies that an object is less than the inclusive maximum value.</summary> /// <typeparam name="T">The type of the objects to be compared.</typeparam> /// <param name="left">The object to be evaluated.</param> /// <param name="right">An object representing the inclusive maximum value of paramref name="value"/>.</param> /// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param> public static void LessThanOrEqual<T>(T left, T right, IComparer<T> comparer) { if (comparer.Compare(left, right) > 0) throw new LessThanOrEqualException(left, right); } /// <summary> /// Verifies that a collection is not empty. /// </summary> /// <param name="collection">The collection to be inspected</param> /// <exception cref="ArgumentNullException">Thrown when a null collection is passed</exception> /// <exception cref="NotEmptyException">Thrown when the collection is empty</exception> public static void NotEmpty(IEnumerable collection) { if (collection == null) throw new ArgumentNullException("collection", "cannot be null"); #pragma warning disable 168 // ReSharper disable once LoopCanBeConvertedToQuery // ReSharper disable once UnusedVariable foreach (var @object in collection) return; #pragma warning restore 168 throw new NotEmptyException(); } /// <summary> /// Verifies that two objects are not equal, using a default comparer. /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> /// <param name="expected">The expected object</param> /// <param name="actual">The actual object</param> /// <exception cref="NotEqualException">Thrown when the objects are equal</exception> public static void NotEqual<T>(T expected, T actual) { NotEqual(expected, actual, GetEqualityComparer<T>()); } /// <summary> /// Verifies that two objects are not equal, using a custom comparer. /// </summary> /// <typeparam name="T">The type of the objects to be compared</typeparam> /// <param name="expected">The expected object</param> /// <param name="actual">The actual object</param> /// <param name="comparer">The comparer used to examine the objects</param> /// <exception cref="NotEqualException">Thrown when the objects are equal</exception> public static void NotEqual<T>(T expected, T actual, IEqualityComparer<T> comparer) { if (comparer.Equals(expected, actual)) throw new NotEqualException(expected, actual); } /// <summary> /// Verifies that a value is not within a given range, using the default comparer. /// </summary> /// <typeparam name="T">The type of the value to be compared</typeparam> /// <param name="actual">The actual value to be evaluated</param> /// <param name="low">The (inclusive) low value of the range</param> /// <param name="high">The (inclusive) high value of the range</param> /// <exception cref="NotInRangeException">Thrown when the value is in the given range</exception> public static void NotInRange<T>(T actual, T low, T high) { NotInRange(actual, low, high, GetComparer<T>()); } /// <summary> /// Verifies that a value is not within a given range, using a comparer. /// </summary> /// <typeparam name="T">The type of the value to be compared</typeparam> /// <param name="actual">The actual value to be evaluated</param> /// <param name="low">The (inclusive) low value of the range</param> /// <param name="high">The (inclusive) high value of the range</param> /// <param name="comparer">The comparer used to evaluate the value's range</param> /// <exception cref="NotInRangeException">Thrown when the value is in the given range</exception> public static void NotInRange<T>(T actual, T low, T high, IComparer<T> comparer) { if (comparer.Compare(low, actual) <= 0 && comparer.Compare(actual, high) <= 0) throw new NotInRangeException(actual, low, high); } /// <summary> /// Verifies that an object reference is not null. /// </summary> /// <param name="object">The object to be validated</param> /// <exception cref="NotNullException">Thrown when the object is not null</exception> public static void NotNull(object @object) { if (@object == null) throw new NotNullException(); } /// <summary> /// Verifies that an object reference is not null. /// </summary> /// <param name="object">The object to be validated</param> /// <param name="message"></param> /// <exception cref="NotNullException">Thrown when the object is not null</exception> public static void NotNull(object @object, string message) { if (@object == null) throw new NotNullException(message); } /// <summary> /// Verifies that two objects are not the same instance. /// </summary> /// <param name="expected">The expected object instance</param> /// <param name="actual">The actual object instance</param> /// <exception cref="NotSameException">Thrown when the objects are the same instance</exception> public static void NotSame(object expected, object actual) { if (ReferenceEquals(expected, actual)) throw new NotSameException(); } /// <summary> /// Verifies that an object reference is null. /// </summary> /// <param name="object">The object to be inspected</param> /// <exception cref="NullException">Thrown when the object reference is not null</exception> public static void Null(object @object) { if (@object != null) throw new NullException(@object); } /// <summary> /// Verifies that two objects are the same instance. /// </summary> /// <param name="expected">The expected object instance</param> /// <param name="actual">The actual object instance</param> /// <exception cref="SameException">Thrown when the objects are not the same instance</exception> public static void Same(object expected, object actual) { if (!ReferenceEquals(expected, actual)) throw new SameException(expected, actual); } /// <summary> /// Verifies that the given collection contains only a single /// element of the given type. /// </summary> /// <param name="collection">The collection.</param> /// <returns>The single item in the collection.</returns> /// <exception cref="SingleException">Thrown when the collection does not contain /// exactly one element.</exception> public static object Single(IEnumerable collection) { if (collection == null) throw new ArgumentNullException("collection"); var count = 0; object result = null; foreach (var item in collection) { result = item; ++count; } if (count != 1) throw new SingleException(count); return result; } /// <summary> /// Verifies that the given collection contains only a single /// element of the given type. /// </summary> /// <typeparam name="T">The collection type.</typeparam> /// <param name="collection">The collection.</param> /// <returns>The single item in the collection.</returns> /// <exception cref="SingleException">Thrown when the collection does not contain /// exactly one element.</exception> public static T Single<T>(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException("collection"); var count = 0; var result = default(T); foreach (var item in collection) { result = item; ++count; } if (count != 1) throw new SingleException(count); return result; } /// <summary> /// Verifies that the exact exception is thrown (and not a derived exception type). /// </summary> /// <typeparam name="T">The type of the exception expected to be thrown</typeparam> /// <param name="testCode">A delegate to the code to be tested</param> /// <returns>The exception that was thrown, when successful</returns> /// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception> public static T Throws<T>(ThrowsDelegate testCode) where T : Exception { return (T) Throws(typeof (T), testCode); } /// <summary> /// Verifies that the exact exception is thrown (and not a derived exception type). /// </summary> /// <typeparam name="T">The type of the exception expected to be thrown</typeparam> /// <param name="userMessage">The message to be shown if the test fails</param> /// <param name="testCode">A delegate to the code to be tested</param> /// <returns>The exception that was thrown, when successful</returns> /// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception> public static T Throws<T>(string userMessage, ThrowsDelegate testCode) where T : Exception { return (T) Throws(typeof (T), testCode); } /// <summary> /// Verifies that the exact exception is thrown (and not a derived exception type). /// Generally used to test property accessors. /// </summary> /// <typeparam name="T">The type of the exception expected to be thrown</typeparam> /// <param name="testCode">A delegate to the code to be tested</param> /// <returns>The exception that was thrown, when successful</returns> /// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception> public static T Throws<T>(ThrowsDelegateWithReturn testCode) where T : Exception { return (T) Throws(typeof (T), testCode); } /// <summary> /// Verifies that the exact exception is thrown (and not a derived exception type). /// Generally used to test property accessors. /// </summary> /// <typeparam name="T">The type of the exception expected to be thrown</typeparam> /// <param name="userMessage">The message to be shown if the test fails</param> /// <param name="testCode">A delegate to the code to be tested</param> /// <returns>The exception that was thrown, when successful</returns> /// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception> public static T Throws<T>(string userMessage, ThrowsDelegateWithReturn testCode) where T : Exception { return (T) Throws(typeof (T), testCode); } /// <summary> /// Verifies that the exact exception is thrown (and not a derived exception type). /// </summary> /// <param name="exceptionType">The type of the exception expected to be thrown</param> /// <param name="testCode">A delegate to the code to be tested</param> /// <returns>The exception that was thrown, when successful</returns> /// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception> public static Exception Throws(Type exceptionType, ThrowsDelegate testCode) { var exception = Record.Exception(testCode); if (exception == null) throw new ThrowsException(exceptionType); if (exceptionType != exception.GetType()) throw new ThrowsException(exceptionType, exception); return exception; } /// <summary> /// Verifies that the exact exception is thrown (and not a derived exception type). /// Generally used to test property accessors. /// </summary> /// <param name="exceptionType">The type of the exception expected to be thrown</param> /// <param name="testCode">A delegate to the code to be tested</param> /// <returns>The exception that was thrown, when successful</returns> /// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception> public static Exception Throws(Type exceptionType, ThrowsDelegateWithReturn testCode) { var exception = Record.Exception(testCode); if (exception == null) throw new ThrowsException(exceptionType); if (exceptionType != exception.GetType()) throw new ThrowsException(exceptionType, exception); return exception; } /// <summary> /// Verifies that a block of code does not throw any exceptions. /// </summary> /// <param name="testCode">A delegate to the code to be tested</param> public static void DoesNotThrow(ThrowsDelegate testCode) { var ex = Record.Exception(testCode); if (ex != null) throw new DoesNotThrowException(ex); } /// <summary> /// Verifies that an expression is true. /// </summary> /// <param name="condition">The condition to be inspected</param> /// <exception cref="TrueException">Thrown when the condition is false</exception> public static void True(bool condition) { True(condition, null); } /// <summary> /// Verifies that an expression is true. /// </summary> /// <param name="condition">The condition to be inspected</param> /// <param name="userMessage">The message to be shown when the condition is false</param> /// <exception cref="TrueException">Thrown when the condition is false</exception> public static void True(bool condition, string userMessage) { if (!condition) throw new TrueException(userMessage); } } }
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// LoadBalancersOperations operations. /// </summary> internal partial class LoadBalancersOperations : IServiceOperations<NetworkManagementClient>, ILoadBalancersOperations { /// <summary> /// Initializes a new instance of the LoadBalancersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LoadBalancersOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoadBalancer>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoadBalancer>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<LoadBalancer>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<LoadBalancer> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoadBalancer>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoadBalancer>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // Copyright (c) Microsoft 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 Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Reflection; namespace Microsoft.Azure.Commands.Compute.Automation { public abstract class ComputeAutomationBaseCmdlet : Microsoft.Azure.Commands.Compute.ComputeClientBaseCmdlet { public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ComputeAutomationAutoMapperProfile.Initialize(); } protected static PSArgument[] ConvertFromObjectsToArguments(string[] names, object[] objects) { var arguments = new PSArgument[objects.Length]; for (int index = 0; index < objects.Length; index++) { arguments[index] = new PSArgument { Name = names[index], Type = objects[index].GetType(), Value = objects[index] }; } return arguments; } protected static object[] ConvertFromArgumentsToObjects(object[] arguments) { if (arguments == null) { return null; } var objects = new object[arguments.Length]; for (int index = 0; index < arguments.Length; index++) { if (arguments[index] is PSArgument) { objects[index] = ((PSArgument)arguments[index]).Value; } else { objects[index] = arguments[index]; } } return objects; } public IContainerServiceOperations ContainerServiceClient { get { return ComputeClient.ComputeManagementClient.ContainerService; } } public IVirtualMachineScaleSetsOperations VirtualMachineScaleSetsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSets; } } public IVirtualMachineScaleSetVMsOperations VirtualMachineScaleSetVMsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSetVMs; } } public static string FormatObject(Object obj) { var objType = obj.GetType(); System.Reflection.PropertyInfo[] pros = objType.GetProperties(); string result = "\n"; var resultTuples = new List<Tuple<string, string, int>>(); var totalTab = GetTabLength(obj, 0, 0, resultTuples) + 1; foreach (var t in resultTuples) { string preTab = new string(' ', t.Item3 * 2); string postTab = new string(' ', totalTab - t.Item3 * 2 - t.Item1.Length); result += preTab + t.Item1 + postTab + ": " + t.Item2 + "\n"; } return result; } private static int GetTabLength(Object obj, int max, int depth, List<Tuple<string, string, int>> tupleList) { var objType = obj.GetType(); var propertySet = new List<PropertyInfo>(); if (objType.BaseType != null) { foreach (var property in objType.BaseType.GetProperties()) { propertySet.Add(property); } } foreach (var property in objType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)) { propertySet.Add(property); } foreach (var property in propertySet) { Object childObject = property.GetValue(obj, null); var isJObject = childObject as Newtonsoft.Json.Linq.JObject; if (isJObject != null) { var objStringValue = Newtonsoft.Json.JsonConvert.SerializeObject(childObject); int i = objStringValue.IndexOf("xmlCfg"); if (i >= 0) { var xmlCfgString = objStringValue.Substring(i + 7); int start = xmlCfgString.IndexOf('"'); int end = xmlCfgString.IndexOf('"', start + 1); xmlCfgString = xmlCfgString.Substring(start + 1, end - start - 1); objStringValue = objStringValue.Replace(xmlCfgString, "..."); } tupleList.Add(MakeTuple(property.Name, objStringValue, depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } else { var elem = childObject as IList; if (elem != null) { if (elem.Count != 0) { max = Math.Max(max, depth * 2 + property.Name.Length + 4); for (int i = 0; i < elem.Count; i++) { Type propType = elem[i].GetType(); if (propType.IsSerializable) { tupleList.Add(MakeTuple(property.Name + "[" + i + "]", elem[i].ToString(), depth)); } else { tupleList.Add(MakeTuple(property.Name + "[" + i + "]", "", depth)); max = Math.Max(max, GetTabLength((Object)elem[i], max, depth + 1, tupleList)); } } } } else { if (property.PropertyType.IsSerializable) { if (childObject != null) { tupleList.Add(MakeTuple(property.Name, childObject.ToString(), depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } } else { var isDictionary = childObject as IDictionary; if (isDictionary != null) { tupleList.Add(MakeTuple(property.Name, Newtonsoft.Json.JsonConvert.SerializeObject(childObject), depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } else if (childObject != null) { tupleList.Add(MakeTuple(property.Name, "", depth)); max = Math.Max(max, GetTabLength(childObject, max, depth + 1, tupleList)); } } } } } return max; } private static Tuple<string, string, int> MakeTuple(string key, string value, int depth) { return new Tuple<string, string, int>(key, value, depth); } } }
// 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.Reflection.Emit { using System; using System.Globalization; using System.Diagnostics.SymbolStore; using System.Runtime.InteropServices; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Security.Permissions; using System.Threading; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security; internal class DynamicILGenerator : ILGenerator { internal DynamicScope m_scope; private int m_methodSigToken; internal unsafe DynamicILGenerator(DynamicMethod method, byte[] methodSignature, int size) : base(method, size) { m_scope = new DynamicScope(); m_methodSigToken = m_scope.GetTokenFor(methodSignature); } [System.Security.SecurityCritical] // auto-generated internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) { dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, module, m_methodBuilder.Name, (byte[])m_scope[m_methodSigToken], new DynamicResolver(this)); } #if FEATURE_APPX private bool ProfileAPICheck { get { return ((DynamicMethod)m_methodBuilder).ProfileAPICheck; } } #endif // FEATURE_APPX // *** ILGenerator api *** public override LocalBuilder DeclareLocal(Type localType, bool pinned) { LocalBuilder localBuilder; if (localType == null) throw new ArgumentNullException(nameof(localType)); Contract.EndContractBlock(); RuntimeType rtType = localType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); #if FEATURE_APPX if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName)); #endif localBuilder = new LocalBuilder(m_localCount, localType, m_methodBuilder); // add the localType to local signature m_localSignature.AddArgument(localType, pinned); m_localCount++; return localBuilder; } // // // Token resolution calls // // [System.Security.SecuritySafeCritical] // auto-generated public override void Emit(OpCode opcode, MethodInfo meth) { if (meth == null) throw new ArgumentNullException(nameof(meth)); Contract.EndContractBlock(); int stackchange = 0; int token = 0; DynamicMethod dynMeth = meth as DynamicMethod; if (dynMeth == null) { RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo; if (rtMeth == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(meth)); RuntimeType declaringType = rtMeth.GetRuntimeType(); if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray)) token = GetTokenFor(rtMeth, declaringType); else token = GetTokenFor(rtMeth); } else { // rule out not allowed operations on DynamicMethods if (opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn) || opcode.Equals(OpCodes.Ldvirtftn)) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOpCodeOnDynamicMethod")); } token = GetTokenFor(dynMeth); } EnsureCapacity(7); InternalEmit(opcode); if (opcode.StackBehaviourPush == StackBehaviour.Varpush && meth.ReturnType != typeof(void)) { stackchange++; } if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { stackchange -= meth.GetParametersNoCopy().Length; } // Pop the "this" parameter if the method is non-static, // and the instruction is not newobj/ldtoken/ldftn. if (!meth.IsStatic && !(opcode.Equals(OpCodes.Newobj) || opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn))) { stackchange--; } UpdateStackSize(opcode, stackchange); PutInteger4(token); } [System.Runtime.InteropServices.ComVisible(true)] public override void Emit(OpCode opcode, ConstructorInfo con) { if (con == null) throw new ArgumentNullException(nameof(con)); Contract.EndContractBlock(); RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo; if (rtConstructor == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(con)); RuntimeType declaringType = rtConstructor.GetRuntimeType(); int token; if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray)) // need to sort out the stack size story token = GetTokenFor(rtConstructor, declaringType); else token = GetTokenFor(rtConstructor); EnsureCapacity(7); InternalEmit(opcode); // need to sort out the stack size story UpdateStackSize(opcode, 1); PutInteger4(token); } public override void Emit(OpCode opcode, Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); int token = GetTokenFor(rtType); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(token); } public override void Emit(OpCode opcode, FieldInfo field) { if (field == null) throw new ArgumentNullException(nameof(field)); Contract.EndContractBlock(); RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo; if (runtimeField == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), nameof(field)); int token; if (field.DeclaringType == null) token = GetTokenFor(runtimeField); else token = GetTokenFor(runtimeField, runtimeField.GetRuntimeType()); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(token); } public override void Emit(OpCode opcode, String str) { if (str == null) throw new ArgumentNullException(nameof(str)); Contract.EndContractBlock(); int tempVal = GetTokenForString(str); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(tempVal); } // // // Signature related calls (vararg, calli) // // [System.Security.SecuritySafeCritical] // overrides SC public override void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { int stackchange = 0; SignatureHelper sig; if (optionalParameterTypes != null) if ((callingConvention & CallingConventions.VarArgs) == 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention")); sig = GetMemberRefSignature(callingConvention, returnType, parameterTypes, optionalParameterTypes); EnsureCapacity(7); Emit(OpCodes.Calli); // If there is a non-void return type, push one. if (returnType != typeof(void)) stackchange++; // Pop off arguments if any. if (parameterTypes != null) stackchange -= parameterTypes.Length; // Pop off vararg arguments. if (optionalParameterTypes != null) stackchange -= optionalParameterTypes.Length; // Pop the this parameter if the method has a this parameter. if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis) stackchange--; // Pop the native function pointer. stackchange--; UpdateStackSize(OpCodes.Calli, stackchange); int token = GetTokenForSig(sig.GetSignature(true)); PutInteger4(token); } public override void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) { int stackchange = 0; int cParams = 0; int i; SignatureHelper sig; if (parameterTypes != null) cParams = parameterTypes.Length; sig = SignatureHelper.GetMethodSigHelper(unmanagedCallConv, returnType); if (parameterTypes != null) for (i = 0; i < cParams; i++) sig.AddArgument(parameterTypes[i]); // If there is a non-void return type, push one. if (returnType != typeof(void)) stackchange++; // Pop off arguments if any. if (parameterTypes != null) stackchange -= cParams; // Pop the native function pointer. stackchange--; UpdateStackSize(OpCodes.Calli, stackchange); EnsureCapacity(7); Emit(OpCodes.Calli); int token = GetTokenForSig(sig.GetSignature(true)); PutInteger4(token); } [System.Security.SecuritySafeCritical] // auto-generated public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) { if (methodInfo == null) throw new ArgumentNullException(nameof(methodInfo)); if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))) throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), nameof(opcode)); if (methodInfo.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo)); if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo)); Contract.EndContractBlock(); int tk; int stackchange = 0; tk = GetMemberRefToken(methodInfo, optionalParameterTypes); EnsureCapacity(7); InternalEmit(opcode); // Push the return value if there is one. if (methodInfo.ReturnType != typeof(void)) stackchange++; // Pop the parameters. stackchange -= methodInfo.GetParameterTypes().Length; // Pop the this parameter if the method is non-static and the // instruction is not newobj. if (!(methodInfo is SymbolMethod) && methodInfo.IsStatic == false && !(opcode.Equals(OpCodes.Newobj))) stackchange--; // Pop the optional parameters off the stack. if (optionalParameterTypes != null) stackchange -= optionalParameterTypes.Length; UpdateStackSize(opcode, stackchange); PutInteger4(tk); } public override void Emit(OpCode opcode, SignatureHelper signature) { if (signature == null) throw new ArgumentNullException(nameof(signature)); Contract.EndContractBlock(); int stackchange = 0; EnsureCapacity(7); InternalEmit(opcode); // The only IL instruction that has VarPop behaviour, that takes a // Signature token as a parameter is calli. Pop the parameters and // the native function pointer. To be conservative, do not pop the // this pointer since this information is not easily derived from // SignatureHelper. if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { Contract.Assert(opcode.Equals(OpCodes.Calli), "Unexpected opcode encountered for StackBehaviour VarPop."); // Pop the arguments.. stackchange -= signature.ArgumentCount; // Pop native function pointer off the stack. stackchange--; UpdateStackSize(opcode, stackchange); } int token = GetTokenForSig(signature.GetSignature(true)); ; PutInteger4(token); } // // // Exception related generation // // public override Label BeginExceptionBlock() { return base.BeginExceptionBlock(); } public override void EndExceptionBlock() { base.EndExceptionBlock(); } public override void BeginExceptFilterBlock() { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } public override void BeginCatchBlock(Type exceptionType) { if (CurrExcStackCount == 0) throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock")); Contract.EndContractBlock(); __ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1]; RuntimeType rtType = exceptionType as RuntimeType; if (current.GetCurrentState() == __ExceptionInfo.State_Filter) { if (exceptionType != null) { throw new ArgumentException(Environment.GetResourceString("Argument_ShouldNotSpecifyExceptionType")); } this.Emit(OpCodes.Endfilter); } else { // execute this branch if previous clause is Catch or Fault if (exceptionType == null) throw new ArgumentNullException(nameof(exceptionType)); if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); Label endLabel = current.GetEndLabel(); this.Emit(OpCodes.Leave, endLabel); // if this is a catch block the exception will be pushed on the stack and we need to update the stack info UpdateStackSize(OpCodes.Nop, 1); } current.MarkCatchAddr(ILOffset, exceptionType); // this is relying on too much implementation details of the base and so it's highly breaking // Need to have a more integreted story for exceptions current.m_filterAddr[current.m_currentCatch - 1] = GetTokenFor(rtType); } public override void BeginFaultBlock() { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } public override void BeginFinallyBlock() { base.BeginFinallyBlock(); } // // // debugger related calls. // // [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override void UsingNamespace(String ns) { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override void MarkSequencePoint(ISymbolDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn) { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } public override void BeginScope() { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } public override void EndScope() { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } [System.Security.SecurityCritical] // auto-generated private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes) { Type[] parameterTypes; if (optionalParameterTypes != null && (methodInfo.CallingConvention & CallingConventions.VarArgs) == 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention")); RuntimeMethodInfo rtMeth = methodInfo as RuntimeMethodInfo; DynamicMethod dm = methodInfo as DynamicMethod; if (rtMeth == null && dm == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(methodInfo)); ParameterInfo[] paramInfo = methodInfo.GetParametersNoCopy(); if (paramInfo != null && paramInfo.Length != 0) { parameterTypes = new Type[paramInfo.Length]; for (int i = 0; i < paramInfo.Length; i++) parameterTypes[i] = paramInfo[i].ParameterType; } else { parameterTypes = null; } SignatureHelper sig = GetMemberRefSignature(methodInfo.CallingConvention, MethodBuilder.GetMethodBaseReturnType(methodInfo), parameterTypes, optionalParameterTypes); if (rtMeth != null) return GetTokenForVarArgMethod(rtMeth, sig); else return GetTokenForVarArgMethod(dm, sig); } [System.Security.SecurityCritical] // auto-generated internal override SignatureHelper GetMemberRefSignature( CallingConventions call, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { int cParams; int i; SignatureHelper sig; if (parameterTypes == null) cParams = 0; else cParams = parameterTypes.Length; sig = SignatureHelper.GetMethodSigHelper(call, returnType); for (i = 0; i < cParams; i++) sig.AddArgument(parameterTypes[i]); if (optionalParameterTypes != null && optionalParameterTypes.Length != 0) { // add the sentinel sig.AddSentinel(); for (i = 0; i < optionalParameterTypes.Length; i++) sig.AddArgument(optionalParameterTypes[i]); } return sig; } internal override void RecordTokenFixup() { // DynamicMethod doesn't need fixup. } #region GetTokenFor helpers private int GetTokenFor(RuntimeType rtType) { #if FEATURE_APPX if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName)); #endif return m_scope.GetTokenFor(rtType.TypeHandle); } private int GetTokenFor(RuntimeFieldInfo runtimeField) { #if FEATURE_APPX if (ProfileAPICheck) { RtFieldInfo rtField = runtimeField as RtFieldInfo; if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName)); } #endif return m_scope.GetTokenFor(runtimeField.FieldHandle); } private int GetTokenFor(RuntimeFieldInfo runtimeField, RuntimeType rtType) { #if FEATURE_APPX if (ProfileAPICheck) { RtFieldInfo rtField = runtimeField as RtFieldInfo; if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName)); if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName)); } #endif return m_scope.GetTokenFor(runtimeField.FieldHandle, rtType.TypeHandle); } private int GetTokenFor(RuntimeConstructorInfo rtMeth) { #if FEATURE_APPX if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName)); #endif return m_scope.GetTokenFor(rtMeth.MethodHandle); } private int GetTokenFor(RuntimeConstructorInfo rtMeth, RuntimeType rtType) { #if FEATURE_APPX if (ProfileAPICheck) { if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName)); if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName)); } #endif return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle); } private int GetTokenFor(RuntimeMethodInfo rtMeth) { #if FEATURE_APPX if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName)); #endif return m_scope.GetTokenFor(rtMeth.MethodHandle); } private int GetTokenFor(RuntimeMethodInfo rtMeth, RuntimeType rtType) { #if FEATURE_APPX if (ProfileAPICheck) { if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName)); if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName)); } #endif return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle); } private int GetTokenFor(DynamicMethod dm) { return m_scope.GetTokenFor(dm); } private int GetTokenForVarArgMethod(RuntimeMethodInfo rtMeth, SignatureHelper sig) { #if FEATURE_APPX if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName)); #endif VarArgMethod varArgMeth = new VarArgMethod(rtMeth, sig); return m_scope.GetTokenFor(varArgMeth); } private int GetTokenForVarArgMethod(DynamicMethod dm, SignatureHelper sig) { VarArgMethod varArgMeth = new VarArgMethod(dm, sig); return m_scope.GetTokenFor(varArgMeth); } private int GetTokenForString(String s) { return m_scope.GetTokenFor(s); } private int GetTokenForSig(byte[] sig) { return m_scope.GetTokenFor(sig); } #endregion } internal class DynamicResolver : Resolver { #region Private Data Members private __ExceptionInfo[] m_exceptions; private byte[] m_exceptionHeader; private DynamicMethod m_method; private byte[] m_code; private byte[] m_localSignature; private int m_stackSize; private DynamicScope m_scope; #endregion #region Internal Methods internal DynamicResolver(DynamicILGenerator ilGenerator) { m_stackSize = ilGenerator.GetMaxStackSize(); m_exceptions = ilGenerator.GetExceptions(); m_code = ilGenerator.BakeByteArray(); m_localSignature = ilGenerator.m_localSignature.InternalGetSignatureArray(); m_scope = ilGenerator.m_scope; m_method = (DynamicMethod)ilGenerator.m_methodBuilder; m_method.m_resolver = this; } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DynamicResolver(DynamicILInfo dynamicILInfo) { m_stackSize = dynamicILInfo.MaxStackSize; m_code = dynamicILInfo.Code; m_localSignature = dynamicILInfo.LocalSignature; m_exceptionHeader = dynamicILInfo.Exceptions; //m_exceptions = dynamicILInfo.Exceptions; m_scope = dynamicILInfo.DynamicScope; m_method = dynamicILInfo.DynamicMethod; m_method.m_resolver = this; } // // We can destroy the unmanaged part of dynamic method only after the managed part is definitely gone and thus // nobody can call the dynamic method anymore. A call to finalizer alone does not guarantee that the managed // part is gone. A malicious code can keep a reference to DynamicMethod in long weak reference that survives finalization, // or we can be running during shutdown where everything is finalized. // // The unmanaged resolver keeps a reference to the managed resolver in long weak handle. If the long weak handle // is null, we can be sure that the managed part of the dynamic method is definitely gone and that it is safe to // destroy the unmanaged part. (Note that the managed finalizer has to be on the same object that the long weak handle // points to in order for this to work.) Unfortunately, we can not perform the above check when out finalizer // is called - the long weak handle won't be cleared yet. Instead, we create a helper scout object that will attempt // to do the destruction after next GC. // // The finalization does not have to be done using CriticalFinalizerObject. We have to go over all DynamicMethodDescs // during AppDomain shutdown anyway to avoid leaks e.g. if somebody stores reference to DynamicMethod in static. // ~DynamicResolver() { DynamicMethod method = m_method; if (method == null) return; if (method.m_methodHandle == null) return; DestroyScout scout = null; try { scout = new DestroyScout(); } catch { // We go over all DynamicMethodDesc during AppDomain shutdown and make sure // that everything associated with them is released. So it is ok to skip reregistration // for finalization during appdomain shutdown if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) { // Try again later. GC.ReRegisterForFinalize(this); } return; } // We can never ever have two active destroy scouts for the same method. We need to initialize the scout // outside the try/reregister block to avoid possibility of reregistration for finalization with active scout. scout.m_methodHandle = method.m_methodHandle.Value; } private class DestroyScout { internal RuntimeMethodHandleInternal m_methodHandle; [System.Security.SecuritySafeCritical] // auto-generated ~DestroyScout() { if (m_methodHandle.IsNullHandle()) return; // It is not safe to destroy the method if the managed resolver is alive. if (RuntimeMethodHandle.GetResolver(m_methodHandle) != null) { if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) { // Somebody might have been holding a reference on us via weak handle. // We will keep trying. It will be hopefully released eventually. GC.ReRegisterForFinalize(this); } return; } RuntimeMethodHandle.Destroy(m_methodHandle); } } // Keep in sync with vm/dynamicmethod.h [Flags] internal enum SecurityControlFlags { Default = 0x0, SkipVisibilityChecks = 0x1, RestrictedSkipVisibilityChecks = 0x2, HasCreationContext = 0x4, CanSkipCSEvaluation = 0x8, } internal override RuntimeType GetJitContext(ref int securityControlFlags) { RuntimeType typeOwner; SecurityControlFlags flags = SecurityControlFlags.Default; if (m_method.m_restrictedSkipVisibility) flags |= SecurityControlFlags.RestrictedSkipVisibilityChecks; else if (m_method.m_skipVisibility) flags |= SecurityControlFlags.SkipVisibilityChecks; typeOwner = m_method.m_typeOwner; #if FEATURE_COMPRESSEDSTACK if (m_method.m_creationContext != null) { flags |= SecurityControlFlags.HasCreationContext; if(m_method.m_creationContext.CanSkipEvaluation) { flags |= SecurityControlFlags.CanSkipCSEvaluation; } } #endif // FEATURE_COMPRESSEDSTACK securityControlFlags = (int)flags; return typeOwner; } private static int CalculateNumberOfExceptions(__ExceptionInfo[] excp) { int num = 0; if (excp == null) return 0; for (int i = 0; i < excp.Length; i++) num += excp[i].GetNumberOfCatches(); return num; } internal override byte[] GetCodeInfo( ref int stackSize, ref int initLocals, ref int EHCount) { stackSize = m_stackSize; if (m_exceptionHeader != null && m_exceptionHeader.Length != 0) { if (m_exceptionHeader.Length < 4) throw new FormatException(); byte header = m_exceptionHeader[0]; if ((header & 0x40) != 0) // Fat { byte[] size = new byte[4]; for (int q = 0; q < 3; q++) size[q] = m_exceptionHeader[q + 1]; EHCount = (BitConverter.ToInt32(size, 0) - 4) / 24; } else EHCount = (m_exceptionHeader[1] - 2) / 12; } else { EHCount = CalculateNumberOfExceptions(m_exceptions); } initLocals = (m_method.InitLocals) ? 1 : 0; return m_code; } internal override byte[] GetLocalsSignature() { return m_localSignature; } internal override unsafe byte[] GetRawEHInfo() { return m_exceptionHeader; } [System.Security.SecurityCritical] // auto-generated internal override unsafe void GetEHInfo(int excNumber, void* exc) { CORINFO_EH_CLAUSE* exception = (CORINFO_EH_CLAUSE*)exc; for (int i = 0; i < m_exceptions.Length; i++) { int excCount = m_exceptions[i].GetNumberOfCatches(); if (excNumber < excCount) { // found the right exception block exception->Flags = m_exceptions[i].GetExceptionTypes()[excNumber]; exception->TryOffset = m_exceptions[i].GetStartAddress(); if ((exception->Flags & __ExceptionInfo.Finally) != __ExceptionInfo.Finally) exception->TryLength = m_exceptions[i].GetEndAddress() - exception->TryOffset; else exception->TryLength = m_exceptions[i].GetFinallyEndAddress() - exception->TryOffset; exception->HandlerOffset = m_exceptions[i].GetCatchAddresses()[excNumber]; exception->HandlerLength = m_exceptions[i].GetCatchEndAddresses()[excNumber] - exception->HandlerOffset; // this is cheating because the filter address is the token of the class only for light code gen exception->ClassTokenOrFilterOffset = m_exceptions[i].GetFilterAddresses()[excNumber]; break; } excNumber -= excCount; } } internal override String GetStringLiteral(int token) { return m_scope.GetString(token); } #if FEATURE_COMPRESSEDSTACK internal override CompressedStack GetSecurityContext() { return m_method.m_creationContext; } #endif // FEATURE_COMPRESSEDSTACK [System.Security.SecurityCritical] internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle) { typeHandle = new IntPtr(); methodHandle = new IntPtr(); fieldHandle = new IntPtr(); Object handle = m_scope[token]; if (handle == null) throw new InvalidProgramException(); if (handle is RuntimeTypeHandle) { typeHandle = ((RuntimeTypeHandle)handle).Value; return; } if (handle is RuntimeMethodHandle) { methodHandle = ((RuntimeMethodHandle)handle).Value; return; } if (handle is RuntimeFieldHandle) { fieldHandle = ((RuntimeFieldHandle)handle).Value; return; } DynamicMethod dm = handle as DynamicMethod; if (dm != null) { methodHandle = dm.GetMethodDescriptor().Value; return; } GenericMethodInfo gmi = handle as GenericMethodInfo; if (gmi != null) { methodHandle = gmi.m_methodHandle.Value; typeHandle = gmi.m_context.Value; return; } GenericFieldInfo gfi = handle as GenericFieldInfo; if (gfi != null) { fieldHandle = gfi.m_fieldHandle.Value; typeHandle = gfi.m_context.Value; return; } VarArgMethod vaMeth = handle as VarArgMethod; if (vaMeth != null) { if (vaMeth.m_dynamicMethod == null) { methodHandle = vaMeth.m_method.MethodHandle.Value; typeHandle = vaMeth.m_method.GetDeclaringTypeInternal().GetTypeHandleInternal().Value; } else methodHandle = vaMeth.m_dynamicMethod.GetMethodDescriptor().Value; return; } } internal override byte[] ResolveSignature(int token, int fromMethod) { return m_scope.ResolveSignature(token, fromMethod); } internal override MethodInfo GetDynamicMethod() { return m_method.GetMethodInfo(); } #endregion } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [System.Runtime.InteropServices.ComVisible(true)] public class DynamicILInfo { #region Private Data Members private DynamicMethod m_method; private DynamicScope m_scope; private byte[] m_exceptions; private byte[] m_code; private byte[] m_localSignature; private int m_maxStackSize; private int m_methodSignature; #endregion #region Constructor internal DynamicILInfo(DynamicScope scope, DynamicMethod method, byte[] methodSignature) { m_method = method; m_scope = scope; m_methodSignature = m_scope.GetTokenFor(methodSignature); m_exceptions = EmptyArray<Byte>.Value; m_code = EmptyArray<Byte>.Value; m_localSignature = EmptyArray<Byte>.Value; } #endregion #region Internal Methods [System.Security.SecurityCritical] // auto-generated internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) { dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, module, m_method.Name, (byte[])m_scope[m_methodSignature], new DynamicResolver(this)); } internal byte[] LocalSignature { get { if (m_localSignature == null) m_localSignature = SignatureHelper.GetLocalVarSigHelper().InternalGetSignatureArray(); return m_localSignature; } } internal byte[] Exceptions { get { return m_exceptions; } } internal byte[] Code { get { return m_code; } } internal int MaxStackSize { get { return m_maxStackSize; } } #endregion #region Public ILGenerator Methods public DynamicMethod DynamicMethod { get { return m_method; } } internal DynamicScope DynamicScope { get { return m_scope; } } public void SetCode(byte[] code, int maxStackSize) { m_code = (code != null) ? (byte[])code.Clone() : EmptyArray<Byte>.Value; m_maxStackSize = maxStackSize; } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe void SetCode(byte* code, int codeSize, int maxStackSize) { if (codeSize < 0) throw new ArgumentOutOfRangeException(nameof(codeSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); if (codeSize > 0 && code == null) throw new ArgumentNullException(nameof(code)); Contract.EndContractBlock(); m_code = new byte[codeSize]; for (int i = 0; i < codeSize; i++) { m_code[i] = *code; code++; } m_maxStackSize = maxStackSize; } public void SetExceptions(byte[] exceptions) { m_exceptions = (exceptions != null) ? (byte[])exceptions.Clone() : EmptyArray<Byte>.Value; } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe void SetExceptions(byte* exceptions, int exceptionsSize) { if (exceptionsSize < 0) throw new ArgumentOutOfRangeException(nameof(exceptionsSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); if (exceptionsSize > 0 && exceptions == null) throw new ArgumentNullException(nameof(exceptions)); Contract.EndContractBlock(); m_exceptions = new byte[exceptionsSize]; for (int i = 0; i < exceptionsSize; i++) { m_exceptions[i] = *exceptions; exceptions++; } } public void SetLocalSignature(byte[] localSignature) { m_localSignature = (localSignature != null) ? (byte[])localSignature.Clone() : EmptyArray<Byte>.Value; } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe void SetLocalSignature(byte* localSignature, int signatureSize) { if (signatureSize < 0) throw new ArgumentOutOfRangeException(nameof(signatureSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); if (signatureSize > 0 && localSignature == null) throw new ArgumentNullException(nameof(localSignature)); Contract.EndContractBlock(); m_localSignature = new byte[signatureSize]; for (int i = 0; i < signatureSize; i++) { m_localSignature[i] = *localSignature; localSignature++; } } #endregion #region Public Scope Methods [System.Security.SecuritySafeCritical] // auto-generated public int GetTokenFor(RuntimeMethodHandle method) { return DynamicScope.GetTokenFor(method); } public int GetTokenFor(DynamicMethod method) { return DynamicScope.GetTokenFor(method); } public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle contextType) { return DynamicScope.GetTokenFor(method, contextType); } public int GetTokenFor(RuntimeFieldHandle field) { return DynamicScope.GetTokenFor(field); } public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle contextType) { return DynamicScope.GetTokenFor(field, contextType); } public int GetTokenFor(RuntimeTypeHandle type) { return DynamicScope.GetTokenFor(type); } public int GetTokenFor(string literal) { return DynamicScope.GetTokenFor(literal); } public int GetTokenFor(byte[] signature) { return DynamicScope.GetTokenFor(signature); } #endregion } internal class DynamicScope { #region Private Data Members internal List<Object> m_tokens; #endregion #region Constructor internal unsafe DynamicScope() { m_tokens = new List<Object>(); m_tokens.Add(null); } #endregion #region Internal Methods internal object this[int token] { get { token &= 0x00FFFFFF; if (token < 0 || token > m_tokens.Count) return null; return m_tokens[token]; } } internal int GetTokenFor(VarArgMethod varArgMethod) { m_tokens.Add(varArgMethod); return m_tokens.Count - 1 | (int)MetadataTokenType.MemberRef; } internal string GetString(int token) { return this[token] as string; } internal byte[] ResolveSignature(int token, int fromMethod) { if (fromMethod == 0) return (byte[])this[token]; VarArgMethod vaMethod = this[token] as VarArgMethod; if (vaMethod == null) return null; return vaMethod.m_signature.GetSignature(true); } #endregion #region Public Methods [System.Security.SecuritySafeCritical] // auto-generated public int GetTokenFor(RuntimeMethodHandle method) { IRuntimeMethodInfo methodReal = method.GetMethodInfo(); RuntimeMethodHandleInternal rmhi = methodReal.Value; if (methodReal != null && !RuntimeMethodHandle.IsDynamicMethod(rmhi)) { RuntimeType type = RuntimeMethodHandle.GetDeclaringType(rmhi); if ((type != null) && RuntimeTypeHandle.HasInstantiation(type)) { // Do we really need to retrieve this much info just to throw an exception? MethodBase m = RuntimeType.GetMethodBase(methodReal); Type t = m.DeclaringType.GetGenericTypeDefinition(); throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGenericLcg"), m, t)); } } m_tokens.Add(method); return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef; } public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle typeContext) { m_tokens.Add(new GenericMethodInfo(method, typeContext)); return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef; } public int GetTokenFor(DynamicMethod method) { m_tokens.Add(method); return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef; } public int GetTokenFor(RuntimeFieldHandle field) { m_tokens.Add(field); return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef; } public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle typeContext) { m_tokens.Add(new GenericFieldInfo(field, typeContext)); return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef; } public int GetTokenFor(RuntimeTypeHandle type) { m_tokens.Add(type); return m_tokens.Count - 1 | (int)MetadataTokenType.TypeDef; } public int GetTokenFor(string literal) { m_tokens.Add(literal); return m_tokens.Count - 1 | (int)MetadataTokenType.String; } public int GetTokenFor(byte[] signature) { m_tokens.Add(signature); return m_tokens.Count - 1 | (int)MetadataTokenType.Signature; } #endregion } internal sealed class GenericMethodInfo { internal RuntimeMethodHandle m_methodHandle; internal RuntimeTypeHandle m_context; internal GenericMethodInfo(RuntimeMethodHandle methodHandle, RuntimeTypeHandle context) { m_methodHandle = methodHandle; m_context = context; } } internal sealed class GenericFieldInfo { internal RuntimeFieldHandle m_fieldHandle; internal RuntimeTypeHandle m_context; internal GenericFieldInfo(RuntimeFieldHandle fieldHandle, RuntimeTypeHandle context) { m_fieldHandle = fieldHandle; m_context = context; } } internal sealed class VarArgMethod { internal RuntimeMethodInfo m_method; internal DynamicMethod m_dynamicMethod; internal SignatureHelper m_signature; internal VarArgMethod(DynamicMethod dm, SignatureHelper signature) { m_dynamicMethod = dm; m_signature = signature; } internal VarArgMethod(RuntimeMethodInfo method, SignatureHelper signature) { m_method = method; m_signature = signature; } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace WeifenLuo.WinFormsUI.Docking { using WeifenLuo.WinFormsUI.ThemeVS2012Light; /// <summary> /// Visual Studio 2012 Light theme. /// </summary> public class VS2012LightTheme : ThemeBase { //CHANGED: Exposed customization options public bool ShowWindowListButton { get; set; } = false; public bool ShowAutoHideButton { get; set; } = true; public bool ForceActiveCaptionColor { get; set; } = false; public ToolStripRenderer ToolStripRenderer { get; set; } //CHANGED: End of inserted code public VS2012LightTheme() { Skin = CreateVisualStudio2012Light(); } /// <summary> /// Applies the specified theme to the dock panel. /// </summary> /// <param name="dockPanel">The dock panel.</param> public override void Apply(DockPanel dockPanel) { if (dockPanel == null) { throw new NullReferenceException("dockPanel"); } Measures.SplitterSize = 6; dockPanel.Extender.DockPaneCaptionFactory = new VS2012LightDockPaneCaptionFactory(); dockPanel.Extender.AutoHideStripFactory = new VS2012LightAutoHideStripFactory(); dockPanel.Extender.AutoHideWindowFactory = new VS2012LightAutoHideWindowFactory(); dockPanel.Extender.DockPaneStripFactory = new VS2012LightDockPaneStripFactory(); dockPanel.Extender.DockPaneSplitterControlFactory = new VS2012LightDockPaneSplitterControlFactory(); dockPanel.Extender.DockWindowSplitterControlFactory = new VS2012LightDockWindowSplitterControlFactory(); dockPanel.Extender.DockWindowFactory = new VS2012LightDockWindowFactory(); dockPanel.Extender.PaneIndicatorFactory = new VS2012LightPaneIndicatorFactory(); dockPanel.Extender.PanelIndicatorFactory = new VS2012LightPanelIndicatorFactory(); dockPanel.Extender.DockOutlineFactory = new VS2012LightDockOutlineFactory(); Skin = CreateVisualStudio2012Light(); } private class VS2012LightDockOutlineFactory : DockPanelExtender.IDockOutlineFactory { public DockOutlineBase CreateDockOutline() { return new VS2012LightDockOutline(); } private class VS2012LightDockOutline : DockOutlineBase { public VS2012LightDockOutline() { m_dragForm = new DragForm(); SetDragForm(Rectangle.Empty); DragForm.BackColor = Color.FromArgb(0xff, 91, 173, 255); DragForm.Opacity = 0.5; DragForm.Show(false); } DragForm m_dragForm; private DragForm DragForm { get { return m_dragForm; } } protected override void OnShow() { CalculateRegion(); } protected override void OnClose() { DragForm.Close(); } private void CalculateRegion() { if (SameAsOldValue) return; if (!FloatWindowBounds.IsEmpty) SetOutline(FloatWindowBounds); else if (DockTo is DockPanel) SetOutline(DockTo as DockPanel, Dock, (ContentIndex != 0)); else if (DockTo is DockPane) SetOutline(DockTo as DockPane, Dock, ContentIndex); else SetOutline(); } private void SetOutline() { SetDragForm(Rectangle.Empty); } private void SetOutline(Rectangle floatWindowBounds) { SetDragForm(floatWindowBounds); } private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge) { Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); if (dock == DockStyle.Top) { int height = dockPanel.GetDockWindowSize(DockState.DockTop); rect = new Rectangle(rect.X, rect.Y, rect.Width, height); } else if (dock == DockStyle.Bottom) { int height = dockPanel.GetDockWindowSize(DockState.DockBottom); rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height); } else if (dock == DockStyle.Left) { int width = dockPanel.GetDockWindowSize(DockState.DockLeft); rect = new Rectangle(rect.X, rect.Y, width, rect.Height); } else if (dock == DockStyle.Right) { int width = dockPanel.GetDockWindowSize(DockState.DockRight); rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height); } else if (dock == DockStyle.Fill) { rect = dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); } SetDragForm(rect); } private void SetOutline(DockPane pane, DockStyle dock, int contentIndex) { if (dock != DockStyle.Fill) { Rectangle rect = pane.DisplayingRectangle; if (dock == DockStyle.Right) rect.X += rect.Width / 2; if (dock == DockStyle.Bottom) rect.Y += rect.Height / 2; if (dock == DockStyle.Left || dock == DockStyle.Right) rect.Width -= rect.Width / 2; if (dock == DockStyle.Top || dock == DockStyle.Bottom) rect.Height -= rect.Height / 2; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else if (contentIndex == -1) { Rectangle rect = pane.DisplayingRectangle; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else { using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex)) { RectangleF rectF = path.GetBounds(); Rectangle rect = new Rectangle((int)rectF.X, (int)rectF.Y, (int)rectF.Width, (int)rectF.Height); using (Matrix matrix = new Matrix(rect, new Point[] { new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height) })) { path.Transform(matrix); } Region region = new Region(path); SetDragForm(rect, region); } } } private void SetDragForm(Rectangle rect) { DragForm.Bounds = rect; if (rect == Rectangle.Empty) { if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = new Region(Rectangle.Empty); } else if (DragForm.Region != null) { DragForm.Region.Dispose(); DragForm.Region = null; } } private void SetDragForm(Rectangle rect, Region region) { DragForm.Bounds = rect; if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = region; } } } private class VS2012LightPanelIndicatorFactory : DockPanelExtender.IPanelIndicatorFactory { public DockPanel.IPanelIndicator CreatePanelIndicator(DockStyle style) { return new VS2012LightPanelIndicator(style); } private class VS2012LightPanelIndicator : PictureBox, DockPanel.IPanelIndicator { private static Image _imagePanelLeft = Resources.DockIndicator_PanelLeft; private static Image _imagePanelRight = Resources.DockIndicator_PanelRight; private static Image _imagePanelTop = Resources.DockIndicator_PanelTop; private static Image _imagePanelBottom = Resources.DockIndicator_PanelBottom; private static Image _imagePanelFill = Resources.DockIndicator_PanelFill; private static Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft; private static Image _imagePanelRightActive = Resources.DockIndicator_PanelRight; private static Image _imagePanelTopActive = Resources.DockIndicator_PanelTop; private static Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom; private static Image _imagePanelFillActive = Resources.DockIndicator_PanelFill; public VS2012LightPanelIndicator(DockStyle dockStyle) { m_dockStyle = dockStyle; SizeMode = PictureBoxSizeMode.AutoSize; Image = ImageInactive; } private DockStyle m_dockStyle; private DockStyle DockStyle { get { return m_dockStyle; } } private DockStyle m_status; public DockStyle Status { get { return m_status; } set { if (value != DockStyle && value != DockStyle.None) throw new InvalidEnumArgumentException(); if (m_status == value) return; m_status = value; IsActivated = (m_status != DockStyle.None); } } private Image ImageInactive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeft; else if (DockStyle == DockStyle.Right) return _imagePanelRight; else if (DockStyle == DockStyle.Top) return _imagePanelTop; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottom; else if (DockStyle == DockStyle.Fill) return _imagePanelFill; else return null; } } private Image ImageActive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeftActive; else if (DockStyle == DockStyle.Right) return _imagePanelRightActive; else if (DockStyle == DockStyle.Top) return _imagePanelTopActive; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottomActive; else if (DockStyle == DockStyle.Fill) return _imagePanelFillActive; else return null; } } private bool m_isActivated = false; private bool IsActivated { get { return m_isActivated; } set { m_isActivated = value; Image = IsActivated ? ImageActive : ImageInactive; } } public DockStyle HitTest(Point pt) { return this.Visible && ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None; } } } private class VS2012LightPaneIndicatorFactory : DockPanelExtender.IPaneIndicatorFactory { public DockPanel.IPaneIndicator CreatePaneIndicator() { return new VS2012LightPaneIndicator(); } private class VS2012LightPaneIndicator : PictureBox, DockPanel.IPaneIndicator { private static Bitmap _bitmapPaneDiamond = Resources.Dockindicator_PaneDiamond; private static Bitmap _bitmapPaneDiamondLeft = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondRight = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondTop = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondBottom = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondFill = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondHotSpot = Resources.Dockindicator_PaneDiamond_Hotspot; private static Bitmap _bitmapPaneDiamondHotSpotIndex = Resources.DockIndicator_PaneDiamond_HotspotIndex; private static DockPanel.HotSpotIndex[] _hotSpots = new[] { new DockPanel.HotSpotIndex(1, 0, DockStyle.Top), new DockPanel.HotSpotIndex(0, 1, DockStyle.Left), new DockPanel.HotSpotIndex(1, 1, DockStyle.Fill), new DockPanel.HotSpotIndex(2, 1, DockStyle.Right), new DockPanel.HotSpotIndex(1, 2, DockStyle.Bottom) }; private GraphicsPath _displayingGraphicsPath = DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond); public VS2012LightPaneIndicator() { SizeMode = PictureBoxSizeMode.AutoSize; Image = _bitmapPaneDiamond; Region = new Region(DisplayingGraphicsPath); } public GraphicsPath DisplayingGraphicsPath { get { return _displayingGraphicsPath; } } public DockStyle HitTest(Point pt) { if (!Visible) return DockStyle.None; pt = PointToClient(pt); if (!ClientRectangle.Contains(pt)) return DockStyle.None; for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++) { if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y)) return _hotSpots[i].DockStyle; } return DockStyle.None; } private DockStyle m_status = DockStyle.None; public DockStyle Status { get { return m_status; } set { m_status = value; if (m_status == DockStyle.None) Image = _bitmapPaneDiamond; else if (m_status == DockStyle.Left) Image = _bitmapPaneDiamondLeft; else if (m_status == DockStyle.Right) Image = _bitmapPaneDiamondRight; else if (m_status == DockStyle.Top) Image = _bitmapPaneDiamondTop; else if (m_status == DockStyle.Bottom) Image = _bitmapPaneDiamondBottom; else if (m_status == DockStyle.Fill) Image = _bitmapPaneDiamondFill; } } } } private class VS2012LightAutoHideWindowFactory : DockPanelExtender.IAutoHideWindowFactory { public DockPanel.AutoHideWindowControl CreateAutoHideWindow(DockPanel panel) { return new VS2012LightAutoHideWindowControl(panel); } } private class VS2012LightDockPaneSplitterControlFactory : DockPanelExtender.IDockPaneSplitterControlFactory { public DockPane.SplitterControlBase CreateSplitterControl(DockPane pane) { return new VS2012LightSplitterControl(pane); } } private class VS2012LightDockWindowSplitterControlFactory : DockPanelExtender.IDockWindowSplitterControlFactory { public SplitterBase CreateSplitterControl() { return new VS2012LightDockWindow.VS2012LightDockWindowSplitterControl(); } } private class VS2012LightDockPaneStripFactory : DockPanelExtender.IDockPaneStripFactory { public DockPaneStripBase CreateDockPaneStrip(DockPane pane) { return new VS2012LightDockPaneStrip(pane); } } private class VS2012LightAutoHideStripFactory : DockPanelExtender.IAutoHideStripFactory { public AutoHideStripBase CreateAutoHideStrip(DockPanel panel) { return new VS2012LightAutoHideStrip(panel); } } private class VS2012LightDockPaneCaptionFactory : DockPanelExtender.IDockPaneCaptionFactory { public DockPaneCaptionBase CreateDockPaneCaption(DockPane pane) { return new VS2012LightDockPaneCaption(pane); } } private class VS2012LightDockWindowFactory : DockPanelExtender.IDockWindowFactory { public DockWindow CreateDockWindow(DockPanel dockPanel, DockState dockState) { return new VS2012LightDockWindow(dockPanel, dockState); } } public static DockPanelSkin CreateVisualStudio2012Light() { var specialBlue = Color.FromArgb(0xFF, 0x00, 0x7A, 0xCC); var dot = Color.FromArgb(80, 170, 220); var activeTab = specialBlue; var mouseHoverTab = Color.FromArgb(0xFF, 28, 151, 234); var inactiveTab = SystemColors.Control; var lostFocusTab = Color.FromArgb(0xFF, 204, 206, 219); var skin = new DockPanelSkin(); skin.AutoHideStripSkin.DockStripGradient.StartColor = specialBlue; skin.AutoHideStripSkin.DockStripGradient.EndColor = SystemColors.ControlLight; skin.AutoHideStripSkin.TabGradient.TextColor = SystemColors.ControlDarkDark; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor = activeTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor = lostFocusTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor = Color.White; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor = inactiveTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor = mouseHoverTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor = Color.Black; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor = specialBlue; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.GrayText; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor = specialBlue; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor = dot; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.ControlDark; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.GrayText; return skin; } } }
// // 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 System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml; using Hyak.Common; using Microsoft.Azure.Insights; using Microsoft.Azure.Insights.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Insights { /// <summary> /// Operations for metric definitions. /// </summary> public partial class MetricDefinitionOperations : IServiceOperations<InsightsClient>, IMetricDefinitionOperations { /// <summary> /// Initializes a new instance of the MetricDefinitionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public MetricDefinitionOperations(InsightsClient client) { this._client = client; } private InsightsClient _client; /// <summary> /// Gets a reference to the Microsoft.Azure.Insights.InsightsClient. /// </summary> public InsightsClient Client { get { return this._client; } } /// <summary> /// The List Metric Definitions operation lists the metric definitions /// for the resource. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the target resource to get /// metrics for. /// </param> /// <param name='filterString'> /// Optional. An OData $filter expression that supports querying by the /// name of the metric definition. For example, "name.value eq /// 'Percentage CPU'". Name is optional, meaning the expression may be /// "". /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Metric Definitions operation response. /// </returns> public async Task<MetricDefinitionListResponse> GetMetricDefinitionsInternalAsync(string resourceUri, string filterString, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("filterString", filterString); TracingAdapter.Enter(invocationId, this, "GetMetricDefinitionsAsync", tracingParameters); } // Construct URL string url = "/" + Uri.EscapeDataString(resourceUri) + "/metricDefinitions?"; url = url + "api-version=2014-04-01"; if (filterString != null) { url = url + "&$filter=" + Uri.EscapeDataString(filterString); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result MetricDefinitionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new MetricDefinitionListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { MetricDefinitionCollection metricDefinitionCollectionInstance = new MetricDefinitionCollection(); result.MetricDefinitionCollection = metricDefinitionCollectionInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { MetricDefinition metricDefinitionInstance = new MetricDefinition(); metricDefinitionCollectionInstance.Value.Add(metricDefinitionInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { LocalizableString nameInstance = new LocalizableString(); metricDefinitionInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { Unit unitInstance = ((Unit)Enum.Parse(typeof(Unit), ((string)unitValue), true)); metricDefinitionInstance.Unit = unitInstance; } JToken primaryAggregationTypeValue = valueValue["primaryAggregationType"]; if (primaryAggregationTypeValue != null && primaryAggregationTypeValue.Type != JTokenType.Null) { AggregationType primaryAggregationTypeInstance = ((AggregationType)Enum.Parse(typeof(AggregationType), ((string)primaryAggregationTypeValue), true)); metricDefinitionInstance.PrimaryAggregationType = primaryAggregationTypeInstance; } JToken resourceUriValue = valueValue["resourceUri"]; if (resourceUriValue != null && resourceUriValue.Type != JTokenType.Null) { string resourceUriInstance = ((string)resourceUriValue); metricDefinitionInstance.ResourceUri = resourceUriInstance; } JToken metricAvailabilitiesArray = valueValue["metricAvailabilities"]; if (metricAvailabilitiesArray != null && metricAvailabilitiesArray.Type != JTokenType.Null) { foreach (JToken metricAvailabilitiesValue in ((JArray)metricAvailabilitiesArray)) { MetricAvailability metricAvailabilityInstance = new MetricAvailability(); metricDefinitionInstance.MetricAvailabilities.Add(metricAvailabilityInstance); JToken timeGrainValue = metricAvailabilitiesValue["timeGrain"]; if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null) { TimeSpan timeGrainInstance = XmlConvert.ToTimeSpan(((string)timeGrainValue)); metricAvailabilityInstance.TimeGrain = timeGrainInstance; } JToken retentionValue = metricAvailabilitiesValue["retention"]; if (retentionValue != null && retentionValue.Type != JTokenType.Null) { TimeSpan retentionInstance = XmlConvert.ToTimeSpan(((string)retentionValue)); metricAvailabilityInstance.Retention = retentionInstance; } JToken locationValue = metricAvailabilitiesValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { MetricLocation locationInstance = new MetricLocation(); metricAvailabilityInstance.Location = locationInstance; JToken tableEndpointValue = locationValue["tableEndpoint"]; if (tableEndpointValue != null && tableEndpointValue.Type != JTokenType.Null) { string tableEndpointInstance = ((string)tableEndpointValue); locationInstance.TableEndpoint = tableEndpointInstance; } JToken tableInfoArray = locationValue["tableInfo"]; if (tableInfoArray != null && tableInfoArray.Type != JTokenType.Null) { foreach (JToken tableInfoValue in ((JArray)tableInfoArray)) { MetricTableInfo metricTableInfoInstance = new MetricTableInfo(); locationInstance.TableInfo.Add(metricTableInfoInstance); JToken tableNameValue = tableInfoValue["tableName"]; if (tableNameValue != null && tableNameValue.Type != JTokenType.Null) { string tableNameInstance = ((string)tableNameValue); metricTableInfoInstance.TableName = tableNameInstance; } JToken startTimeValue = tableInfoValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); metricTableInfoInstance.StartTime = startTimeInstance; } JToken endTimeValue = tableInfoValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTime endTimeInstance = ((DateTime)endTimeValue); metricTableInfoInstance.EndTime = endTimeInstance; } JToken sasTokenValue = tableInfoValue["sasToken"]; if (sasTokenValue != null && sasTokenValue.Type != JTokenType.Null) { string sasTokenInstance = ((string)sasTokenValue); metricTableInfoInstance.SasToken = sasTokenInstance; } JToken sasTokenExpirationTimeValue = tableInfoValue["sasTokenExpirationTime"]; if (sasTokenExpirationTimeValue != null && sasTokenExpirationTimeValue.Type != JTokenType.Null) { DateTime sasTokenExpirationTimeInstance = ((DateTime)sasTokenExpirationTimeValue); metricTableInfoInstance.SasTokenExpirationTime = sasTokenExpirationTimeInstance; } } } JToken partitionKeyValue = locationValue["partitionKey"]; if (partitionKeyValue != null && partitionKeyValue.Type != JTokenType.Null) { string partitionKeyInstance = ((string)partitionKeyValue); locationInstance.PartitionKey = partitionKeyInstance; } } } } JToken propertiesSequenceElement = ((JToken)valueValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); metricDefinitionInstance.Properties.Add(propertiesKey, propertiesValue); } } JToken dimensionsArray = valueValue["dimensions"]; if (dimensionsArray != null && dimensionsArray.Type != JTokenType.Null) { foreach (JToken dimensionsValue in ((JArray)dimensionsArray)) { Dimension dimensionInstance = new Dimension(); metricDefinitionInstance.Dimensions.Add(dimensionInstance); JToken nameValue2 = dimensionsValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { LocalizableString nameInstance2 = new LocalizableString(); dimensionInstance.Name = nameInstance2; JToken valueValue3 = nameValue2["value"]; if (valueValue3 != null && valueValue3.Type != JTokenType.Null) { string valueInstance2 = ((string)valueValue3); nameInstance2.Value = valueInstance2; } JToken localizedValueValue2 = nameValue2["localizedValue"]; if (localizedValueValue2 != null && localizedValueValue2.Type != JTokenType.Null) { string localizedValueInstance2 = ((string)localizedValueValue2); nameInstance2.LocalizedValue = localizedValueInstance2; } } JToken valuesArray = dimensionsValue["values"]; if (valuesArray != null && valuesArray.Type != JTokenType.Null) { foreach (JToken valuesValue in ((JArray)valuesArray)) { LocalizableString localizableStringInstance = new LocalizableString(); dimensionInstance.Values.Add(localizableStringInstance); JToken valueValue4 = valuesValue["value"]; if (valueValue4 != null && valueValue4.Type != JTokenType.Null) { string valueInstance3 = ((string)valueValue4); localizableStringInstance.Value = valueInstance3; } JToken localizedValueValue3 = valuesValue["localizedValue"]; if (localizedValueValue3 != null && localizedValueValue3.Type != JTokenType.Null) { string localizedValueInstance3 = ((string)localizedValueValue3); localizableStringInstance.LocalizedValue = localizedValueInstance3; } } } } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System.Xml.Linq; namespace Fonlow.SyncML.Elements { public class MetaLast : SyncMLSimpleElement { public MetaLast() : base(ElementNames.SyncMLMetInf, ElementNames.Last) { } } public class MetaNext : SyncMLSimpleElement { public MetaNext() : base(ElementNames.SyncMLMetInf, ElementNames.Next) { } } /// <summary> /// Specifies the synchronization state information (i.e., sync anchor) for the currentsynchronization session. /// </summary> /// <ParentElements>MetInf</ParentElements> /// <ContentModel>(Last?, Next)</ContentModel> public class MetaAnchor : SyncMLComplexElement { private MetaAnchor() : base(ElementNames.SyncMLMetInf, ElementNames.Anchor) { } public static MetaAnchor Create() { MetaAnchor r = new MetaAnchor(); r.Next = new MetaNext(); return r; } /// <summary> /// Create next and optional last. /// </summary> public static MetaAnchor Create(string next, string last) { MetaAnchor r = new MetaAnchor(); if (last != null) r.Last = SyncMLSimpleElementFactory.Create<MetaLast>(last); r.Next = SyncMLSimpleElementFactory.Create<MetaNext>(next); return r; } public static MetaAnchor Create(XElement xmlData) { if (xmlData == null) return null; MetaAnchor r = new MetaAnchor(); r.Last = SyncMLSimpleElementFactory.Create<MetaLast>(ElementReader.Element(xmlData, ElementNames.Last)); r.Next = SyncMLSimpleElementFactory.Create<MetaNext>(ElementReader.Element(xmlData, ElementNames.Next)); return r; } private MetaLast last; public MetaLast Last { get { if (last == null) last = new MetaLast(); return last; } set { last = value; } } private MetaNext next; public MetaNext Next { get { return next; } set { next = value; ThrowExceptionIfNull(value, "Anchor/Next"); } } public override XElement Xml { get { Element.RemoveAll(); if (last != null) Element.Add(last.Xml); Element.Add(Next.Xml); return Element; } } } /// <summary> /// EMI might not need to be supported. /// Specifies the non-standard, experimental meta information (EMI) extensions supported by the device. The extensions /// are specified in terms of the XML element type name and the value. /// </summary> public class MetaEMI : SyncMLSimpleElement { public MetaEMI() : base(ElementNames.SyncMLMetInf, ElementNames.EMI) { } } public class MetaFormat : SyncMLSimpleElement { public MetaFormat() : base(ElementNames.SyncMLMetInf, ElementNames.Format) { } } public class MetaFieldLevel : SyncMLSimpleElement { public MetaFieldLevel() : base(ElementNames.SyncMLMetInf, ElementNames.FieldLevel) { } } public class MetaFreeID : SyncMLSimpleElement { public MetaFreeID() : base(ElementNames.SyncMLMetInf, ElementNames.FreeID) { } } public class MetaFreeMem : SyncMLSimpleElement { public MetaFreeMem() : base(ElementNames.SyncMLMetInf, ElementNames.FreeMem) { } } /// <summary> /// Restrictions: The content information for this element type SHOULD BE /// one of draft, final, delete, undelete, read, unread. /// When this meta-information is specified repetitively in a hierarchically of element types /// (e.g., in a SyncML collection, as well as the items in the collection), then the metainformation /// specified in the lowest level element type takes precedence. /// This element type is used to set the meta-information characteristics of a data object, such /// as the draft/final, delete/undelete, read/unread marks on a folder item or mail item. /// /// At the moment, the class does not check assigned content. /// </summary> public class MetaMark : SyncMLSimpleElement { public MetaMark() : base(ElementNames.SyncMLMetInf, ElementNames.Mark) { } } public class MetaMaxMsgSize : SyncMLSimpleElement { public MetaMaxMsgSize() : base(ElementNames.SyncMLMetInf, ElementNames.MaxMsgSize) { } } public class MetaMaxObjSize : SyncMLSimpleElement { public MetaMaxObjSize() : base(ElementNames.SyncMLMetInf, ElementNames.MaxObjSize) { } } public class MetaNextNonce : SyncMLSimpleElement { public MetaNextNonce() : base(ElementNames.SyncMLMetInf, ElementNames.NextNonce) { } } public class MetaSharedMem : SyncMLSimpleElement { public MetaSharedMem() : base(ElementNames.SyncMLMetInf, ElementNames.SharedMem) { } } public class MetaSize : SyncMLSimpleElement { public MetaSize() : base(ElementNames.SyncMLMetInf, ElementNames.Size) { } } public class MetaType : SyncMLSimpleElement { public MetaType() : base(ElementNames.SyncMLMetInf, ElementNames.Type) { } } public class MetaVersion : SyncMLSimpleElement { public MetaVersion() : base(ElementNames.SyncMLMetInf, ElementNames.Version) { } } /// <summary> /// Specifies the maximum free memory and item identifier for a source (e.g., a datastore or a device. /// </summary> ///<ContentModel>(SharedMem?, FreeMem, FreeID)</ContentModel> public class MetaMem : SyncMLComplexElement { private MetaMem() : base(ElementNames.SyncMLMetInf, ElementNames.Mem) { } public static MetaMem Create(XElement xmlData) { if (xmlData == null) return null; MetaMem r = new MetaMem(); r.FreeMem = SyncMLSimpleElementFactory.Create<MetaFreeMem>(ElementReader.Element(xmlData, ElementNames.FreeMem)); r.FreeID = SyncMLSimpleElementFactory.Create<MetaFreeID>(ElementReader.Element(xmlData, ElementNames.FreeID)); r.SharedMem = SyncMLSimpleElementFactory.Create<MetaSharedMem>(ElementReader.Element(xmlData, ElementNames.SharedMem)); return r; } public static MetaMem Create() { MetaMem r = new MetaMem(); r.FreeMem = new MetaFreeMem(); r.FreeID = new MetaFreeID(); return r; } private MetaSharedMem sharedMem; public MetaSharedMem SharedMem { get { if (sharedMem == null) sharedMem = new MetaSharedMem(); return sharedMem; } set { sharedMem = value; } } private MetaFreeMem freeMem; public MetaFreeMem FreeMem { get { return freeMem; } set { freeMem = value; ThrowExceptionIfNull(value, "Mem/FreeMem"); } } private MetaFreeID freeID; public MetaFreeID FreeID { get { return freeID; } set { freeID = value; ThrowExceptionIfNull(value, "Mem/FreeID"); } } public override XElement Xml { get { Element.RemoveAll(); if (sharedMem != null) Element.Add(sharedMem.Xml); Element.Add(FreeMem.Xml); Element.Add(FreeID.Xml); return Element; } } } /// <summary> /// Retrieve meta elements from a Meta container. /// SyncMLMeta may hold meta data of sync commands or device info, so it is not elegant to design SyncMLMeta as SyncMLComplexElement. /// The parser assume the data is about sync commands only, no device info. /// </summary> public class MetaParser { XElement navMeta; /// <summary> /// /// </summary> /// <param name="metaXml">Meta data including the Meta tag.</param> public MetaParser(XElement metaXml) { navMeta = metaXml; } XNamespace metaNamespace = ElementNames.SyncMLMetInf; public MetaFormat GetMetaFormat() { return SyncMLSimpleElementFactory.Create<MetaFormat>(navMeta.Element(metaNamespace + ElementNames.Format)); } public MetaType GetMetaType() { return SyncMLSimpleElementFactory.Create<MetaType>(navMeta.Element(metaNamespace + ElementNames.Type)); } public MetaAnchor GetMetaAnchor() { XElement n = navMeta.Element(metaNamespace + ElementNames.Anchor); if (n != null) return MetaAnchor.Create(n); else return null; } public MetaFieldLevel GetMetaFieldLevel() { return SyncMLSimpleElementFactory.Create<MetaFieldLevel>(navMeta.Element(metaNamespace + ElementNames.FieldLevel)); } public MetaMark GetMetaMark() { return SyncMLSimpleElementFactory.Create<MetaMark>(navMeta.Element(metaNamespace + ElementNames.Mark)); } public MetaMaxMsgSize GetMetaMaxMsgSize() { return SyncMLSimpleElementFactory.Create<MetaMaxMsgSize>(navMeta.Element(metaNamespace + ElementNames.MaxMsgSize)); } public MetaMaxObjSize GetMetaMaxObjSize() { return SyncMLSimpleElementFactory.Create<MetaMaxObjSize>(navMeta.Element(metaNamespace + ElementNames.MaxObjSize)); } public MetaMem GetMetaMem() { XElement n = navMeta.Element(metaNamespace + ElementNames.Mem); if (n != null) return MetaMem.Create(n); else return null; } public MetaNextNonce GetMetaNextNonce() { return SyncMLSimpleElementFactory.Create<MetaNextNonce>(navMeta.Element(metaNamespace + ElementNames.NextNonce)); } public MetaSize GetMetaSize() { return SyncMLSimpleElementFactory.Create<MetaSize>(navMeta.Element(metaNamespace + ElementNames.Size)); } public MetaVersion GetMetaVersion() { return SyncMLSimpleElementFactory.Create<MetaVersion>(navMeta.Element(metaNamespace + ElementNames.Version)); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using NodaTime; using Python.Runtime; using QuantConnect.Algorithm; using QuantConnect.Algorithm.Framework.Alphas; using QuantConnect.Benchmarks; using QuantConnect.Brokerages; using QuantConnect.Data; using QuantConnect.Data.UniverseSelection; using QuantConnect.Exceptions; using QuantConnect.Interfaces; using QuantConnect.Notifications; using QuantConnect.Orders; using QuantConnect.Python; using QuantConnect.Scheduling; using QuantConnect.Securities; using QuantConnect.Securities.Future; using QuantConnect.Securities.Option; using System; using System.Collections.Concurrent; using System.Collections.Generic; using QuantConnect.Storage; namespace QuantConnect.AlgorithmFactory.Python.Wrappers { /// <summary> /// Creates and wraps the algorithm written in python. /// </summary> public class AlgorithmPythonWrapper : IAlgorithm { private readonly dynamic _algorithm; private readonly dynamic _onData; private readonly dynamic _onOrderEvent; private readonly dynamic _onMarginCall; private readonly IAlgorithm _baseAlgorithm; /// <summary> /// True if the underlying python algorithm implements "OnEndOfDay" /// </summary> public bool IsOnEndOfDayImplemented { get; } /// <summary> /// True if the underlying python algorithm implements "OnEndOfDay(symbol)" /// </summary> public bool IsOnEndOfDaySymbolImplemented { get; } /// <summary> /// <see cref = "AlgorithmPythonWrapper"/> constructor. /// Creates and wraps the algorithm written in python. /// </summary> /// <param name="moduleName">Name of the module that can be found in the PYTHONPATH</param> public AlgorithmPythonWrapper(string moduleName) { try { using (Py.GIL()) { Logging.Log.Trace($"AlgorithmPythonWrapper(): Python version {PythonEngine.Version}: Importing python module {moduleName}"); var module = Py.Import(moduleName); Logging.Log.Trace($"AlgorithmPythonWrapper(): {moduleName} successfully imported."); var pyList = module.Dir(); foreach (var name in pyList) { Type type; var attr = module.GetAttr(name.ToString()); var repr = attr.Repr().GetStringBetweenChars('\'', '\''); if (repr.StartsWith(moduleName) && // Must be defined in the module attr.TryConvert(out type, true) && // Must be a Type typeof(QCAlgorithm).IsAssignableFrom(type)) // Must inherit from QCAlgorithm { Logging.Log.Trace("AlgorithmPythonWrapper(): Creating IAlgorithm instance."); _algorithm = attr.Invoke(); // Set pandas _algorithm.SetPandasConverter(); // IAlgorithm reference for LEAN internal C# calls (without going from C# to Python and back) _baseAlgorithm = _algorithm.AsManagedObject(type); // determines whether OnData method was defined or inherits from QCAlgorithm // If it is not, OnData from the base class will not be called var pyAlgorithm = _algorithm as PyObject; _onData = pyAlgorithm.GetPythonMethod("OnData"); _onMarginCall = pyAlgorithm.GetPythonMethod("OnMarginCall"); _onOrderEvent = pyAlgorithm.GetAttr("OnOrderEvent"); PyObject endOfDayMethod = pyAlgorithm.GetPythonMethod("OnEndOfDay"); if (endOfDayMethod != null) { // Since we have a EOD method implemented // Determine which one it is by inspecting its arg count var argCount = endOfDayMethod.GetPythonArgCount(); switch (argCount) { case 0: // EOD() IsOnEndOfDayImplemented = true; break; case 1: // EOD(Symbol) IsOnEndOfDaySymbolImplemented = true; break; } // Its important to note that even if both are implemented // python will only use the last implemented, meaning only one will // be used and seen. } } attr.Dispose(); } module.Dispose(); pyList.Dispose(); // If _algorithm could not be set, throw exception if (_algorithm == null) { throw new Exception("Please ensure that one class inherits from QCAlgorithm."); } } } catch (Exception e) { // perform exception interpretation for error in module import var interpreter = StackExceptionInterpreter.CreateFromAssemblies(AppDomain.CurrentDomain.GetAssemblies()); e = interpreter.Interpret(e, interpreter); throw new Exception($"AlgorithmPythonWrapper(): {interpreter.GetExceptionMessageHeader(e)}"); } } /// <summary> /// AlgorithmId for the backtest /// </summary> public string AlgorithmId => _baseAlgorithm.AlgorithmId; /// <summary> /// Gets the function used to define the benchmark. This function will return /// the value of the benchmark at a requested date/time /// </summary> public IBenchmark Benchmark => _baseAlgorithm.Benchmark; /// <summary> /// Gets the brokerage message handler used to decide what to do /// with each message sent from the brokerage /// </summary> public IBrokerageMessageHandler BrokerageMessageHandler { get { return _baseAlgorithm.BrokerageMessageHandler; } set { SetBrokerageMessageHandler(value); } } /// <summary> /// Gets the brokerage model used to emulate a real brokerage /// </summary> public IBrokerageModel BrokerageModel => _baseAlgorithm.BrokerageModel; /// <summary> /// Debug messages from the strategy: /// </summary> public ConcurrentQueue<string> DebugMessages => _baseAlgorithm.DebugMessages; /// <summary> /// Get Requested Backtest End Date /// </summary> public DateTime EndDate => _baseAlgorithm.EndDate; /// <summary> /// Error messages from the strategy: /// </summary> public ConcurrentQueue<string> ErrorMessages => _baseAlgorithm.ErrorMessages; /// <summary> /// Gets or sets the history provider for the algorithm /// </summary> public IHistoryProvider HistoryProvider { get { return _baseAlgorithm.HistoryProvider; } set { SetHistoryProvider(value); } } /// <summary> /// Gets whether or not this algorithm is still warming up /// </summary> public bool IsWarmingUp => _baseAlgorithm.IsWarmingUp; /// <summary> /// Algorithm is running on a live server. /// </summary> public bool LiveMode => _baseAlgorithm.LiveMode; /// <summary> /// Log messages from the strategy: /// </summary> public ConcurrentQueue<string> LogMessages => _baseAlgorithm.LogMessages; /// <summary> /// Public name for the algorithm. /// </summary> /// <remarks>Not currently used but preserved for API integrity</remarks> public string Name { get { return _baseAlgorithm.Name; } set { _baseAlgorithm.Name = value; } } /// <summary> /// Notification manager for storing and processing live event messages /// </summary> public NotificationManager Notify => _baseAlgorithm.Notify; /// <summary> /// Security portfolio management class provides wrapper and helper methods for the Security.Holdings class such as /// IsLong, IsShort, TotalProfit /// </summary> /// <remarks>Portfolio is a wrapper and helper class encapsulating the Securities[].Holdings objects</remarks> public SecurityPortfolioManager Portfolio => _baseAlgorithm.Portfolio; /// <summary> /// Gets the run time error from the algorithm, or null if none was encountered. /// </summary> public Exception RunTimeError { get { return _baseAlgorithm.RunTimeError; } set { SetRunTimeError(value); } } /// <summary> /// Customizable dynamic statistics displayed during live trading: /// </summary> public ConcurrentDictionary<string, string> RuntimeStatistics => _baseAlgorithm.RuntimeStatistics; /// <summary> /// Gets schedule manager for adding/removing scheduled events /// </summary> public ScheduleManager Schedule => _baseAlgorithm.Schedule; /// <summary> /// Security object collection class stores an array of objects representing representing each security/asset /// we have a subscription for. /// </summary> /// <remarks>It is an IDictionary implementation and can be indexed by symbol</remarks> public SecurityManager Securities => _baseAlgorithm.Securities; /// <summary> /// Gets an instance that is to be used to initialize newly created securities. /// </summary> public ISecurityInitializer SecurityInitializer => _baseAlgorithm.SecurityInitializer; /// <summary> /// Gets the Trade Builder to generate trades from executions /// </summary> public ITradeBuilder TradeBuilder => _baseAlgorithm.TradeBuilder; /// <summary> /// Gets the user settings for the algorithm /// </summary> public IAlgorithmSettings Settings => _baseAlgorithm.Settings; /// <summary> /// Gets the option chain provider, used to get the list of option contracts for an underlying symbol /// </summary> public IOptionChainProvider OptionChainProvider => _baseAlgorithm.OptionChainProvider; /// <summary> /// Gets the future chain provider, used to get the list of future contracts for an underlying symbol /// </summary> public IFutureChainProvider FutureChainProvider => _baseAlgorithm.FutureChainProvider; /// <summary> /// Gets the object store, used for persistence /// </summary> public ObjectStore ObjectStore => _baseAlgorithm.ObjectStore; /// <summary> /// Returns the current Slice object /// </summary> public Slice CurrentSlice => _baseAlgorithm.CurrentSlice; /// <summary> /// Algorithm start date for backtesting, set by the SetStartDate methods. /// </summary> public DateTime StartDate => _baseAlgorithm.StartDate; /// <summary> /// Gets or sets the current status of the algorithm /// </summary> public AlgorithmStatus Status { get { return _baseAlgorithm.Status; } set { SetStatus(value); } } /// <summary> /// Set the state of a live deployment /// </summary> /// <param name="status">Live deployment status</param> public void SetStatus(AlgorithmStatus status) => _baseAlgorithm.SetStatus(status); /// <summary> /// Set the available <see cref="TickType"/> supported by each <see cref="SecurityType"/> in <see cref="SecurityManager"/> /// </summary> /// <param name="availableDataTypes">>The different <see cref="TickType"/> each <see cref="Security"/> supports</param> public void SetAvailableDataTypes(Dictionary<SecurityType, List<TickType>> availableDataTypes) => _baseAlgorithm.SetAvailableDataTypes(availableDataTypes); /// <summary> /// Sets the option chain provider, used to get the list of option contracts for an underlying symbol /// </summary> /// <param name="optionChainProvider">The option chain provider</param> public void SetOptionChainProvider(IOptionChainProvider optionChainProvider) => _baseAlgorithm.SetOptionChainProvider(optionChainProvider); /// <summary> /// Sets the future chain provider, used to get the list of future contracts for an underlying symbol /// </summary> /// <param name="futureChainProvider">The future chain provider</param> public void SetFutureChainProvider(IFutureChainProvider futureChainProvider) => _baseAlgorithm.SetFutureChainProvider(futureChainProvider); /// <summary> /// Event fired when an algorithm generates a insight /// </summary> public event AlgorithmEvent<GeneratedInsightsCollection> InsightsGenerated { add { _baseAlgorithm.InsightsGenerated += value; } remove { _baseAlgorithm.InsightsGenerated -= value; } } /// <summary> /// Gets the time keeper instance /// </summary> public ITimeKeeper TimeKeeper => _baseAlgorithm.TimeKeeper; /// <summary> /// Data subscription manager controls the information and subscriptions the algorithms recieves. /// Subscription configurations can be added through the Subscription Manager. /// </summary> public SubscriptionManager SubscriptionManager => _baseAlgorithm.SubscriptionManager; /// <summary> /// Current date/time in the algorithm's local time zone /// </summary> public DateTime Time => _baseAlgorithm.Time; /// <summary> /// Gets the time zone of the algorithm /// </summary> public DateTimeZone TimeZone => _baseAlgorithm.TimeZone; /// <summary> /// Security transaction manager class controls the store and processing of orders. /// </summary> /// <remarks>The orders and their associated events are accessible here. When a new OrderEvent is recieved the algorithm portfolio is updated.</remarks> public SecurityTransactionManager Transactions => _baseAlgorithm.Transactions; /// <summary> /// Gets the collection of universes for the algorithm /// </summary> public UniverseManager UniverseManager => _baseAlgorithm.UniverseManager; /// <summary> /// Gets the subscription settings to be used when adding securities via universe selection /// </summary> public UniverseSettings UniverseSettings => _baseAlgorithm.UniverseSettings; /// <summary> /// Current date/time in UTC. /// </summary> public DateTime UtcTime => _baseAlgorithm.UtcTime; /// <summary> /// Gets the account currency /// </summary> public string AccountCurrency => _baseAlgorithm.AccountCurrency; /// <summary> /// Set a required SecurityType-symbol and resolution for algorithm /// </summary> /// <param name="securityType">SecurityType Enum: Equity, Commodity, FOREX or Future</param> /// <param name="symbol">Symbol Representation of the MarketType, e.g. AAPL</param> /// <param name="resolution">The <see cref="Resolution"/> of market data, Tick, Second, Minute, Hour, or Daily.</param> /// <param name="market">The market the requested security belongs to, such as 'usa' or 'fxcm'</param> /// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice.</param> /// <param name="leverage">leverage for this security</param> /// <param name="extendedMarketHours">ExtendedMarketHours send in data from 4am - 8pm, not used for FOREX</param> /// <param name="dataMappingMode">The contract mapping mode to use for the security</param> /// <param name="dataNormalizationMode">The price scaling mode to use for the security</param> public Security AddSecurity(SecurityType securityType, string symbol, Resolution? resolution, string market, bool fillDataForward, decimal leverage, bool extendedMarketHours, DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null) => _baseAlgorithm.AddSecurity(securityType, symbol, resolution, market, fillDataForward, leverage, extendedMarketHours, dataMappingMode, dataNormalizationMode); /// <summary> /// Creates and adds a new single <see cref="Future"/> contract to the algorithm /// </summary> /// <param name="symbol">The futures contract symbol</param> /// <param name="resolution">The <see cref="Resolution"/> of market data, Tick, Second, Minute, Hour, or Daily. Default is <see cref="Resolution.Minute"/></param> /// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param> /// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param> /// <returns>The new <see cref="Future"/> security</returns> public Future AddFutureContract(Symbol symbol, Resolution? resolution = null, bool fillDataForward = true, decimal leverage = 0m) => _baseAlgorithm.AddFutureContract(symbol, resolution, fillDataForward, leverage); /// <summary> /// Creates and adds a new single <see cref="Option"/> contract to the algorithm /// </summary> /// <param name="symbol">The option contract symbol</param> /// <param name="resolution">The <see cref="Resolution"/> of market data, Tick, Second, Minute, Hour, or Daily. Default is <see cref="Resolution.Minute"/></param> /// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param> /// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param> /// <returns>The new <see cref="Option"/> security</returns> public Option AddOptionContract(Symbol symbol, Resolution? resolution = null, bool fillDataForward = true, decimal leverage = 0m) => _baseAlgorithm.AddOptionContract(symbol, resolution, fillDataForward, leverage); /// <summary> /// Invoked at the end of every time step. This allows the algorithm /// to process events before advancing to the next time step. /// </summary> public void OnEndOfTimeStep() { _baseAlgorithm.OnEndOfTimeStep(); } /// <summary> /// Send debug message /// </summary> /// <param name="message">String message</param> public void Debug(string message) => _baseAlgorithm.Debug(message); /// <summary> /// Send an error message for the algorithm /// </summary> /// <param name="message">String message</param> public void Error(string message) => _baseAlgorithm.Error(message); /// <summary> /// Add a Chart object to algorithm collection /// </summary> /// <param name="chart">Chart object to add to collection.</param> public void AddChart(Chart chart) => _baseAlgorithm.AddChart(chart); /// <summary> /// Get the chart updates since the last request: /// </summary> /// <param name="clearChartData"></param> /// <returns>List of Chart Updates</returns> public List<Chart> GetChartUpdates(bool clearChartData = false) => _baseAlgorithm.GetChartUpdates(clearChartData); /// <summary> /// Gets whether or not this algorithm has been locked and fully initialized /// </summary> public bool GetLocked() => _baseAlgorithm.GetLocked(); /// <summary> /// Gets the parameter with the specified name. If a parameter /// with the specified name does not exist, null is returned /// </summary> /// <param name="name">The name of the parameter to get</param> /// <returns>The value of the specified parameter, or null if not found</returns> public string GetParameter(string name) => _baseAlgorithm.GetParameter(name); /// <summary> /// Gets the history requests required for provide warm up data for the algorithm /// </summary> /// <returns></returns> public IEnumerable<HistoryRequest> GetWarmupHistoryRequests() => _baseAlgorithm.GetWarmupHistoryRequests(); /// <summary> /// Initialise the Algorithm and Prepare Required Data: /// </summary> public void Initialize() { using (Py.GIL()) { _algorithm.Initialize(); } } /// <summary> /// Liquidate your portfolio holdings: /// </summary> /// <param name="symbolToLiquidate">Specific asset to liquidate, defaults to all.</param> /// <param name="tag">Custom tag to know who is calling this.</param> /// <returns>list of order ids</returns> public List<int> Liquidate(Symbol symbolToLiquidate = null, string tag = "Liquidated") => _baseAlgorithm.Liquidate(symbolToLiquidate, tag); /// <summary> /// Save entry to the Log /// </summary> /// <param name="message">String message</param> public void Log(string message) => _baseAlgorithm.Log(message); /// <summary> /// Brokerage disconnected event handler. This method is called when the brokerage connection is lost. /// </summary> public void OnBrokerageDisconnect() { using (Py.GIL()) { _algorithm.OnBrokerageDisconnect(); } } /// <summary> /// Brokerage message event handler. This method is called for all types of brokerage messages. /// </summary> public void OnBrokerageMessage(BrokerageMessageEvent messageEvent) { using (Py.GIL()) { _algorithm.OnBrokerageMessage(messageEvent); } } /// <summary> /// Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection. /// </summary> public void OnBrokerageReconnect() { using (Py.GIL()) { _algorithm.OnBrokerageReconnect(); } } /// <summary> /// v3.0 Handler for all data types /// </summary> /// <param name="slice">The current slice of data</param> public void OnData(Slice slice) { if (_onData != null) { using (Py.GIL()) { _onData(new PythonSlice(slice)); } } } /// <summary> /// Used to send data updates to algorithm framework models /// </summary> /// <param name="slice">The current data slice</param> public void OnFrameworkData(Slice slice) { _baseAlgorithm.OnFrameworkData(slice); } /// <summary> /// Call this event at the end of the algorithm running. /// </summary> public void OnEndOfAlgorithm() { using (Py.GIL()) { _algorithm.OnEndOfAlgorithm(); } } /// <summary> /// End of a trading day event handler. This method is called at the end of the algorithm day (or multiple times if trading multiple assets). /// </summary> /// <remarks>Method is called 10 minutes before closing to allow user to close out position.</remarks> /// <remarks>Deprecated because different assets have different market close times, /// and because Python does not support two methods with the same name</remarks> [Obsolete("This method is deprecated. Please use this overload: OnEndOfDay(Symbol symbol)")] public void OnEndOfDay() { try { using (Py.GIL()) { _algorithm.OnEndOfDay(); } } // If OnEndOfDay is not defined in the script, but OnEndOfDay(Symbol) is, a python exception occurs // Only throws if there is an error in its implementation body catch (PythonException exception) { if (!exception.Message.StartsWith("TypeError : OnEndOfDay()")) { _baseAlgorithm.SetRunTimeError(exception); } } } /// <summary> /// End of a trading day event handler. This method is called at the end of the algorithm day (or multiple times if trading multiple assets). /// </summary> /// <remarks> /// This method is left for backwards compatibility and is invoked via <see cref="OnEndOfDay(Symbol)"/>, if that method is /// override then this method will not be called without a called to base.OnEndOfDay(string) /// </remarks> /// <param name="symbol">Asset symbol for this end of day event. Forex and equities have different closing hours.</param> public void OnEndOfDay(Symbol symbol) { try { using (Py.GIL()) { _algorithm.OnEndOfDay(symbol); } } // If OnEndOfDay(Symbol) is not defined in the script, but OnEndOfDay is, a python exception occurs // Only throws if there is an error in its implementation body catch (PythonException exception) { if (!exception.Message.StartsWith("TypeError : OnEndOfDay()")) { _baseAlgorithm.SetRunTimeError(exception); } } } /// <summary> /// Margin call event handler. This method is called right before the margin call orders are placed in the market. /// </summary> /// <param name="requests">The orders to be executed to bring this algorithm within margin limits</param> public void OnMarginCall(List<SubmitOrderRequest> requests) { using (Py.GIL()) { var result = _algorithm.OnMarginCall(requests); if (_onMarginCall != null) { var pyRequests = result as PyObject; // If the method does not return or returns a non-iterable PyObject, throw an exception if (pyRequests == null || !pyRequests.IsIterable()) { throw new Exception("OnMarginCall must return a non-empty list of SubmitOrderRequest"); } requests.Clear(); foreach (PyObject pyRequest in pyRequests) { SubmitOrderRequest request; if (TryConvert(pyRequest, out request)) { requests.Add(request); } } // If the PyObject is an empty list or its items are not SubmitOrderRequest objects, throw an exception if (requests.Count == 0) { throw new Exception("OnMarginCall must return a non-empty list of SubmitOrderRequest"); } } } } /// <summary> /// Margin call warning event handler. This method is called when Portfolio.MarginRemaining is under 5% of your Portfolio.TotalPortfolioValue /// </summary> public void OnMarginCallWarning() { using (Py.GIL()) { _algorithm.OnMarginCallWarning(); } } /// <summary> /// EXPERTS ONLY:: [-!-Async Code-!-] /// New order event handler: on order status changes (filled, partially filled, cancelled etc). /// </summary> /// <param name="newEvent">Event information</param> public void OnOrderEvent(OrderEvent newEvent) { using (Py.GIL()) { _onOrderEvent(newEvent); } } /// <summary> /// Option assignment event handler. On an option assignment event for short legs the resulting information is passed to this method. /// </summary> /// <param name="assignmentEvent">Option exercise event details containing details of the assignment</param> /// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks> public void OnAssignmentOrderEvent(OrderEvent assignmentEvent) { using (Py.GIL()) { _algorithm.OnAssignmentOrderEvent(assignmentEvent); } } /// <summary> /// Event fired each time the we add/remove securities from the data feed /// </summary> /// <param name="changes">Security additions/removals for this time step</param> public void OnSecuritiesChanged(SecurityChanges changes) { using (Py.GIL()) { _algorithm.OnSecuritiesChanged(changes); } } /// <summary> /// Used to send security changes to algorithm framework models /// </summary> /// <param name="changes">Security additions/removals for this time step</param> public void OnFrameworkSecuritiesChanged(SecurityChanges changes) { using (Py.GIL()) { _algorithm.OnFrameworkSecuritiesChanged(changes); } } /// <summary> /// Called by setup handlers after Initialize and allows the algorithm a chance to organize /// the data gather in the Initialize method /// </summary> public void PostInitialize() { _baseAlgorithm.PostInitialize(); } /// <summary> /// Called when the algorithm has completed initialization and warm up. /// </summary> public void OnWarmupFinished() { using (Py.GIL()) { _algorithm.OnWarmupFinished(); } } /// <summary> /// Removes the security with the specified symbol. This will cancel all /// open orders and then liquidate any existing holdings /// </summary> /// <param name="symbol">The symbol of the security to be removed</param> public bool RemoveSecurity(Symbol symbol) => _baseAlgorithm.RemoveSecurity(symbol); /// <summary> /// Set the algorithm Id for this backtest or live run. This can be used to identify the order and equity records. /// </summary> /// <param name="algorithmId">unique 32 character identifier for backtest or live server</param> public void SetAlgorithmId(string algorithmId) => _baseAlgorithm.SetAlgorithmId(algorithmId); /// <summary> /// Sets the implementation used to handle messages from the brokerage. /// The default implementation will forward messages to debug or error /// and when a <see cref="BrokerageMessageType.Error"/> occurs, the algorithm /// is stopped. /// </summary> /// <param name="handler">The message handler to use</param> public void SetBrokerageMessageHandler(IBrokerageMessageHandler handler) => _baseAlgorithm.SetBrokerageMessageHandler(handler); /// <summary> /// Sets the brokerage model used to resolve transaction models, settlement models, /// and brokerage specified ordering behaviors. /// </summary> /// <param name="brokerageModel">The brokerage model used to emulate the real /// brokerage</param> public void SetBrokerageModel(IBrokerageModel brokerageModel) => _baseAlgorithm.SetBrokerageModel(brokerageModel); /// <summary> /// Sets the account currency cash symbol this algorithm is to manage. /// </summary> /// <remarks>Has to be called during <see cref="Initialize"/> before /// calling <see cref="SetCash(decimal)"/> or adding any <see cref="Security"/></remarks> /// <param name="accountCurrency">The account currency cash symbol to set</param> public void SetAccountCurrency(string accountCurrency) => _baseAlgorithm.SetAccountCurrency(accountCurrency); /// <summary> /// Set the starting capital for the strategy /// </summary> /// <param name="startingCash">decimal starting capital, default $100,000</param> public void SetCash(decimal startingCash) => _baseAlgorithm.SetCash(startingCash); /// <summary> /// Set the cash for the specified symbol /// </summary> /// <param name="symbol">The cash symbol to set</param> /// <param name="startingCash">Decimal cash value of portfolio</param> /// <param name="conversionRate">The current conversion rate for the</param> public void SetCash(string symbol, decimal startingCash, decimal conversionRate = 0) => _baseAlgorithm.SetCash(symbol, startingCash, conversionRate); /// <summary> /// Set the DateTime Frontier: This is the master time and is /// </summary> /// <param name="time"></param> public void SetDateTime(DateTime time) => _baseAlgorithm.SetDateTime(time); /// <summary> /// Set the start date for the backtest /// </summary> /// <param name="start">Datetime Start date for backtest</param> /// <remarks>Must be less than end date and within data available</remarks> public void SetStartDate(DateTime start) => _baseAlgorithm.SetStartDate(start); /// <summary> /// Set the end date for a backtest. /// </summary> /// <param name="end">Datetime value for end date</param> /// <remarks>Must be greater than the start date</remarks> public void SetEndDate(DateTime end) => _baseAlgorithm.SetEndDate(end); /// <summary> /// Get the last known price using the history provider. /// Useful for seeding securities with the correct price /// </summary> /// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param> /// <returns>A single <see cref="BaseData"/> object with the last known price</returns> public BaseData GetLastKnownPrice(Security security) => _baseAlgorithm.GetLastKnownPrice(security); /// <summary> /// Set the runtime error /// </summary> /// <param name="exception">Represents error that occur during execution</param> public void SetRunTimeError(Exception exception) => _baseAlgorithm.SetRunTimeError(exception); /// <summary> /// Sets <see cref="IsWarmingUp"/> to false to indicate this algorithm has finished its warm up /// </summary> public void SetFinishedWarmingUp() { _baseAlgorithm.SetFinishedWarmingUp(); // notify the algorithm OnWarmupFinished(); } /// <summary> /// Set the historical data provider /// </summary> /// <param name="historyProvider">Historical data provider</param> public void SetHistoryProvider(IHistoryProvider historyProvider) => _baseAlgorithm.SetHistoryProvider(historyProvider); /// <summary> /// Set live mode state of the algorithm run: Public setter for the algorithm property LiveMode. /// </summary> /// <param name="live">Bool live mode flag</param> public void SetLiveMode(bool live) => _baseAlgorithm.SetLiveMode(live); /// <summary> /// Set the algorithm as initialized and locked. No more cash or security changes. /// </summary> public void SetLocked() => _baseAlgorithm.SetLocked(); /// <summary> /// Set the maximum number of orders the algortihm is allowed to process. /// </summary> /// <param name="max">Maximum order count int</param> public void SetMaximumOrders(int max) => _baseAlgorithm.SetMaximumOrders(max); /// <summary> /// Sets the parameters from the dictionary /// </summary> /// <param name="parameters">Dictionary containing the parameter names to values</param> public void SetParameters(Dictionary<string, string> parameters) => _baseAlgorithm.SetParameters(parameters); /// <summary> /// Tries to convert a PyObject into a C# object /// </summary> /// <typeparam name="T">Type of the C# object</typeparam> /// <param name="pyObject">PyObject to be converted</param> /// <param name="result">C# object that of type T</param> /// <returns>True if successful conversion</returns> private bool TryConvert<T>(PyObject pyObject, out T result) { result = default(T); var type = (Type)pyObject.GetPythonType().AsManagedObject(typeof(Type)); if (type == typeof(T)) { result = (T)pyObject.AsManagedObject(typeof(T)); } return type == typeof(T); } /// <summary> /// Returns a <see cref = "string"/> that represents the current <see cref = "AlgorithmPythonWrapper"/> object. /// </summary> /// <returns></returns> public override string ToString() { if (_algorithm == null) { return base.ToString(); } using (Py.GIL()) { return _algorithm.Repr(); } } /// <summary> /// Sets the current slice /// </summary> /// <param name="slice">The Slice object</param> public void SetCurrentSlice(Slice slice) => _baseAlgorithm.SetCurrentSlice(slice); /// <summary> /// Provide the API for the algorithm. /// </summary> /// <param name="api">Initiated API</param> public void SetApi(IApi api) => _baseAlgorithm.SetApi(api); /// <summary> /// Sets the object store /// </summary> /// <param name="objectStore">The object store</param> public void SetObjectStore(IObjectStore objectStore) => _baseAlgorithm.SetObjectStore(objectStore); /// <summary> /// Checks if the asset is shortable at the brokerage /// </summary> /// <param name="symbol">Symbol to check if it is shortable</param> /// <param name="quantity">Quantity to short</param> /// <returns>True if shortable at the brokerage</returns> public bool Shortable(Symbol symbol, decimal quantity) { return _baseAlgorithm.Shortable(symbol, quantity); } } }
// 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; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Xunit; using Xunit.NetCore.Extensions; namespace System.Diagnostics.Tests { public class ProcessTests : ProcessTestBase { private class FinalizingProcess : Process { public static volatile bool WasFinalized; public static void CreateAndRelease() { new FinalizingProcess(); } protected override void Dispose(bool disposing) { if (!disposing) { WasFinalized = true; } base.Dispose(disposing); } } private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority) { _process.PriorityClass = exPriorityClass; _process.Refresh(); Assert.Equal(priority, _process.BasePriority); } private void AssertNonZeroWindowsZeroUnix(long value) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.NotEqual(0, value); } else { Assert.Equal(0, value); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))] [PlatformSpecific(PlatformID.Windows)] public void TestBasePriorityOnWindows() { ProcessPriorityClass originalPriority = _process.PriorityClass; Assert.Equal(ProcessPriorityClass.Normal, originalPriority); try { // We are not checking for RealTime case here, as RealTime priority process can // preempt the threads of all other processes, including operating system processes // performing important tasks, which may cause the machine to be unresponsive. //SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24); SetAndCheckBasePriority(ProcessPriorityClass.High, 13); SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4); SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8); } finally { _process.PriorityClass = originalPriority; } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] [OuterLoop] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void TestBasePriorityOnUnix() { ProcessPriorityClass originalPriority = _process.PriorityClass; Assert.Equal(ProcessPriorityClass.Normal, originalPriority); try { SetAndCheckBasePriority(ProcessPriorityClass.High, -11); SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19); SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0); } finally { _process.PriorityClass = originalPriority; } } [Theory] [InlineData(true)] [InlineData(false)] [InlineData(null)] public void TestEnableRaiseEvents(bool? enable) { bool exitedInvoked = false; Process p = CreateProcessLong(); if (enable.HasValue) { p.EnableRaisingEvents = enable.Value; } p.Exited += delegate { exitedInvoked = true; }; StartSleepKillWait(p); if (enable.GetValueOrDefault()) { // There's no guarantee that the Exited callback will be invoked by // the time Process.WaitForExit completes, though it's extremely likely. // There could be a race condition where WaitForExit is returning from // its wait and sees that the callback is already running asynchronously, // at which point it returns to the caller even if the callback hasn't // entirely completed. As such, we spin until the value is set. Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS)); } else { Assert.False(exitedInvoked); } } [Fact] public void TestExitCode() { { Process p = CreateProcess(); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(SuccessExitCode, p.ExitCode); } { Process p = CreateProcessLong(); StartSleepKillWait(p); Assert.NotEqual(0, p.ExitCode); } } [PlatformSpecific(PlatformID.AnyUnix)] [Fact] public void TestUseShellExecute_Unix_Succeeds() { using (var p = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = "exit", Arguments = "42" })) { Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(42, p.ExitCode); } } [Fact] public void TestExitTime() { DateTime timeBeforeProcessStart = DateTime.UtcNow; Process p = CreateProcessLong(); p.Start(); Assert.Throws<InvalidOperationException>(() => p.ExitTime); p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart, "TestExitTime is incorrect."); } [Fact] public void TestId() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle)); } else { IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunner).Select(p => p.Id); Assert.Contains(_process.Id, testProcessIds); } } [Fact] public void TestHasExited() { { Process p = CreateProcess(); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.True(p.HasExited, "TestHasExited001 failed"); } { Process p = CreateProcessLong(); p.Start(); try { Assert.False(p.HasExited, "TestHasExited002 failed"); } finally { p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } Assert.True(p.HasExited, "TestHasExited003 failed"); } } [Fact] public void TestMachineName() { // Checking that the MachineName returns some value. Assert.NotNull(_process.MachineName); } [Fact] public void TestMainModuleOnNonOSX() { string fileName = "corerun"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) fileName = "CoreRun.exe"; Process p = Process.GetCurrentProcess(); Assert.True(p.Modules.Count > 0); Assert.Equal(fileName, p.MainModule.ModuleName); Assert.EndsWith(fileName, p.MainModule.FileName); Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", fileName), p.MainModule.ToString()); } [Fact] public void TestMaxWorkingSet() { using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MaxWorkingSet; Assert.True(curValue >= 0); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { _process.MaxWorkingSet = (IntPtr)((int)curValue + 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)max; _process.Refresh(); Assert.Equal(curValue, (int)_process.MaxWorkingSet); } finally { _process.MaxWorkingSet = (IntPtr)curValue; } } } [Fact] public void TestMinWorkingSet() { using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MinWorkingSet; Assert.True(curValue >= 0); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { _process.MinWorkingSet = (IntPtr)((int)curValue - 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)min; _process.Refresh(); Assert.Equal(curValue, (int)_process.MinWorkingSet); } finally { _process.MinWorkingSet = (IntPtr)curValue; } } } [Fact] public void TestModules() { ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules; foreach (ProcessModule pModule in moduleCollection) { // Validated that we can get a value for each of the following. Assert.NotNull(pModule); Assert.NotNull(pModule.FileName); Assert.NotNull(pModule.ModuleName); // Just make sure these don't throw IntPtr baseAddr = pModule.BaseAddress; IntPtr entryAddr = pModule.EntryPointAddress; int memSize = pModule.ModuleMemorySize; } } [Fact] public void TestNonpagedSystemMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64); } [Fact] public void TestPagedMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64); } [Fact] public void TestPagedSystemMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64); } [Fact] public void TestPeakPagedMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64); } [Fact] public void TestPeakVirtualMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64); } [Fact] public void TestPeakWorkingSet64() { AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64); } [Fact] public void TestPrivateMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64); } [Fact] public void TestVirtualMemorySize64() { Assert.True(_process.VirtualMemorySize64 > 0); } [Fact] public void TestWorkingSet64() { if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // resident memory can be 0 on OSX. Assert.True(_process.WorkingSet64 >= 0); return; } Assert.True(_process.WorkingSet64 > 0); } [Fact] public void TestProcessorTime() { Assert.True(_process.UserProcessorTime.TotalSeconds >= 0); Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0); double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; double processorTimeAtHalfSpin = 0; // Perform loop to occupy cpu, takes less than a second. int i = int.MaxValue / 16; while (i > 0) { i--; if (i == int.MaxValue / 32) processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; } Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds); } [Fact] public void TestProcessStartTime() { TimeSpan allowedWindow = TimeSpan.FromSeconds(3); DateTime testStartTime = DateTime.UtcNow; using (var remote = RemoteInvoke(() => { Console.Write(Process.GetCurrentProcess().StartTime.ToUniversalTime()); return SuccessExitCode; }, new RemoteInvokeOptions { StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } })) { DateTime remoteStartTime = DateTime.Parse(remote.Process.StandardOutput.ReadToEnd()); DateTime curTime = DateTime.UtcNow; Assert.InRange(remoteStartTime, testStartTime - allowedWindow, curTime + allowedWindow); } } [Fact] [PlatformSpecific(~PlatformID.OSX)] // getting/setting affinity not supported on OSX public void TestProcessorAffinity() { IntPtr curProcessorAffinity = _process.ProcessorAffinity; try { _process.ProcessorAffinity = new IntPtr(0x1); Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity); } finally { _process.ProcessorAffinity = curProcessorAffinity; Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity); } } [Fact] public void TestPriorityBoostEnabled() { bool isPriorityBoostEnabled = _process.PriorityBoostEnabled; try { _process.PriorityBoostEnabled = true; Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed"); _process.PriorityBoostEnabled = false; Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed"); } finally { _process.PriorityBoostEnabled = isPriorityBoostEnabled; } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] [OuterLoop] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void TestPriorityClassUnix() { ProcessPriorityClass priorityClass = _process.PriorityClass; try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); } finally { _process.PriorityClass = priorityClass; } } [Fact, PlatformSpecific(PlatformID.Windows)] public void TestPriorityClassWindows() { ProcessPriorityClass priorityClass = _process.PriorityClass; try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); } finally { _process.PriorityClass = priorityClass; } } [Fact] public void TestInvalidPriorityClass() { Process p = new Process(); Assert.Throws<ArgumentException>(() => { p.PriorityClass = ProcessPriorityClass.Normal | ProcessPriorityClass.Idle; }); } [Fact] public void TestProcessName() { Assert.Equal(Path.GetFileNameWithoutExtension(_process.ProcessName), Path.GetFileNameWithoutExtension(HostRunner), StringComparer.OrdinalIgnoreCase); } [Fact] public void TestSafeHandle() { Assert.False(_process.SafeHandle.IsInvalid); } [Fact] public void TestSessionId() { uint sessionId; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId); } else { sessionId = (uint)Interop.getsid(_process.Id); } Assert.Equal(sessionId, (uint)_process.SessionId); } [Fact] public void TestGetCurrentProcess() { Process current = Process.GetCurrentProcess(); Assert.NotNull(current); int currentProcessId = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Interop.GetCurrentProcessId() : Interop.getpid(); Assert.Equal(currentProcessId, current.Id); } [Fact] public void TestGetProcessById() { Process p = Process.GetProcessById(_process.Id); Assert.Equal(_process.Id, p.Id); Assert.Equal(_process.ProcessName, p.ProcessName); } [Fact] public void TestGetProcesses() { Process currentProcess = Process.GetCurrentProcess(); // Get all the processes running on the machine, and check if the current process is one of them. var foundCurrentProcess = (from p in Process.GetProcesses() where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "TestGetProcesses001 failed"); foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName) where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "TestGetProcesses002 failed"); } [Fact] public void TestGetProcessesByName() { // Get the current process using its name Process currentProcess = Process.GetCurrentProcess(); Assert.True(Process.GetProcessesByName(currentProcess.ProcessName).Count() > 0, "TestGetProcessesByName001 failed"); Assert.True(Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Count() > 0, "TestGetProcessesByName001 failed"); } public static IEnumerable<object[]> GetTestProcess() { Process currentProcess = Process.GetCurrentProcess(); yield return new object[] { currentProcess, Process.GetProcessById(currentProcess.Id, "127.0.0.1") }; yield return new object[] { currentProcess, Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProcess.Id).Single() }; } private static bool ProcessPeformanceCounterEnabled() { try { int? value = (int?)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance", "Disable Performance Counters", null); return !value.HasValue || value.Value == 0; } catch (Exception) { // Ignore exceptions, and just assume the counter is enabled. } return true; } [PlatformSpecific(PlatformID.Windows)] [ConditionalTheory(nameof(ProcessPeformanceCounterEnabled))] [MemberData(nameof(GetTestProcess))] public void TestProcessOnRemoteMachineWindows(Process currentProcess, Process remoteProcess) { Assert.Equal(currentProcess.Id, remoteProcess.Id); Assert.Equal(currentProcess.BasePriority, remoteProcess.BasePriority); Assert.Equal(currentProcess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents); Assert.Equal("127.0.0.1", remoteProcess.MachineName); // This property throws exception only on remote processes. Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule); } [Fact, PlatformSpecific(PlatformID.AnyUnix)] public void TestProcessOnRemoteMachineUnix() { Process currentProcess = Process.GetCurrentProcess(); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1")); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1")); } [Fact] public void TestStartInfo() { { Process process = CreateProcessLong(); process.Start(); Assert.Equal(HostRunner, process.StartInfo.FileName); process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } { Process process = CreateProcessLong(); process.Start(); Assert.Throws<System.InvalidOperationException>(() => (process.StartInfo = new ProcessStartInfo())); process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } { Process process = new Process(); process.StartInfo = new ProcessStartInfo(TestConsoleApp); Assert.Equal(TestConsoleApp, process.StartInfo.FileName); } { Process process = new Process(); Assert.Throws<ArgumentNullException>(() => process.StartInfo = null); } { Process process = Process.GetCurrentProcess(); Assert.Throws<System.InvalidOperationException>(() => process.StartInfo); } } [Theory] [InlineData(@"""abc"" d e", @"abc,d,e")] [InlineData(@"""abc"" d e", @"abc,d,e")] [InlineData("\"abc\"\t\td\te", @"abc,d,e")] [InlineData(@"a\\b d""e f""g h", @"a\\b,de fg,h")] [InlineData(@"\ \\ \\\", @"\,\\,\\\")] [InlineData(@"a\\\""b c d", @"a\""b,c,d")] [InlineData(@"a\\\\""b c"" d e", @"a\\b c,d,e")] [InlineData(@"a""b c""d e""f g""h i""j k""l", @"ab cd,ef gh,ij kl")] [InlineData(@"a b c""def", @"a,b,cdef")] [InlineData(@"""\a\"" \\""\\\ b c", @"\a"" \\\\,b,c")] public void TestArgumentParsing(string inputArguments, string expectedArgv) { using (var handle = RemoteInvokeRaw((Func<string, string, string, int>)ConcatThreeArguments, inputArguments, new RemoteInvokeOptions { Start = true, StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } })) { Assert.Equal(expectedArgv, handle.Process.StandardOutput.ReadToEnd()); } } private static int ConcatThreeArguments(string one, string two, string three) { Console.Write(string.Join(",", one, two, three)); return SuccessExitCode; } // [Fact] // uncomment for diagnostic purposes to list processes to console public void TestDiagnosticsWithConsoleWriteLine() { foreach (var p in Process.GetProcesses().OrderBy(p => p.Id)) { Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count); p.Dispose(); } } [Fact] public void CanBeFinalized() { FinalizingProcess.CreateAndRelease(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(FinalizingProcess.WasFinalized); } [Theory] [InlineData(false)] [InlineData(true)] public void TestStartWithMissingFile(bool fullPath) { string path = Guid.NewGuid().ToString("N"); if (fullPath) { path = Path.GetFullPath(path); Assert.True(Path.IsPathRooted(path)); } else { Assert.False(Path.IsPathRooted(path)); } Assert.False(File.Exists(path)); Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path)); Assert.NotEqual(0, e.NativeErrorCode); } [PlatformSpecific(PlatformID.Windows)] // NativeErrorCode not 193 on Windows Nano for ERROR_BAD_EXE_FORMAT, issue #10290 [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))] public void TestStartOnWindowsWithBadFileFormat() { string path = GetTestFilePath(); File.Create(path).Dispose(); Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path)); Assert.NotEqual(0, e.NativeErrorCode); } [PlatformSpecific(PlatformID.AnyUnix)] [Fact] public void TestStartOnUnixWithBadPermissions() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.Equal(0, chmod(path, 644)); // no execute permissions Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path)); Assert.NotEqual(0, e.NativeErrorCode); } [PlatformSpecific(PlatformID.AnyUnix)] [Fact] public void TestStartOnUnixWithBadFormat() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.Equal(0, chmod(path, 744)); // execute permissions using (Process p = Process.Start(path)) { p.WaitForExit(); Assert.NotEqual(0, p.ExitCode); } } [DllImport("libc")] private static extern int chmod(string path, int mode); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using NuGet; using Splat; using Squirrel; using Squirrel.Tests.TestHelpers; using Xunit; namespace Squirrel.Tests { public class FakeUrlDownloader : IFileDownloader { public Task<byte[]> DownloadUrl(string url) { return Task.FromResult(new byte[0]); } public async Task DownloadFile(string url, string targetFile, Action<int> progress) { } } public class ApplyReleasesTests : IEnableLogger { [Fact] public async Task CleanInstallRunsSquirrelAwareAppsWithInstallFlag() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); // NB: We execute the Squirrel-aware apps, so we need to give // them a minute to settle or else the using statement will // try to blow away a running process await Task.Delay(1000); Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args2.txt"))); Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"))); var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"), Encoding.UTF8); Assert.Contains("firstrun", text); } } } [Fact] public async Task UpgradeRunsSquirrelAwareAppsWithUpgradeFlag() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); } await Task.Delay(1000); IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir); pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args2.txt"))); Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"))); var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"), Encoding.UTF8); Assert.Contains("updated|0.2.0", text); } } [Fact] public async Task RunningUpgradeAppTwiceDoesntCrash() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); } await Task.Delay(1000); IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir); pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); // NB: The 2nd time we won't have any updates to apply. We should just do nothing! using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); } } [Fact] public async Task FullUninstallRemovesAllVersions() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); } await Task.Delay(1000); IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir); pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullUninstall(); } Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"))); Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"))); Assert.False(Directory.Exists(Path.Combine(tempDir, "theApp"))); } } [Fact] public void WhenNoNewReleasesAreAvailableTheListIsEmpty() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { var appDir = Directory.CreateDirectory(Path.Combine(tempDir, "theApp")); var packages = Path.Combine(appDir.FullName, "packages"); Directory.CreateDirectory(packages); var package = "Squirrel.Core.1.0.0.0-full.nupkg"; File.Copy(IntegrationTestHelper.GetPath("fixtures", package), Path.Combine(packages, package)); var aGivenPackage = Path.Combine(packages, package); var baseEntry = ReleaseEntry.GenerateFromFile(aGivenPackage); var updateInfo = UpdateInfo.Create(baseEntry, new[] { baseEntry }, "dontcare"); Assert.Empty(updateInfo.ReleasesToApply); } } [Fact] public void ThrowsWhenOnlyDeltaReleasesAreAvailable() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { var appDir = Directory.CreateDirectory(Path.Combine(tempDir, "theApp")); var packages = Path.Combine(appDir.FullName, "packages"); Directory.CreateDirectory(packages); var baseFile = "Squirrel.Core.1.0.0.0-full.nupkg"; File.Copy(IntegrationTestHelper.GetPath("fixtures", baseFile), Path.Combine(packages, baseFile)); var basePackage = Path.Combine(packages, baseFile); var baseEntry = ReleaseEntry.GenerateFromFile(basePackage); var deltaFile = "Squirrel.Core.1.1.0.0-delta.nupkg"; File.Copy(IntegrationTestHelper.GetPath("fixtures", deltaFile), Path.Combine(packages, deltaFile)); var deltaPackage = Path.Combine(packages, deltaFile); var deltaEntry = ReleaseEntry.GenerateFromFile(deltaPackage); Assert.Throws<Exception>( () => UpdateInfo.Create(baseEntry, new[] { deltaEntry }, "dontcare")); } } [Fact] public async Task ApplyReleasesWithOneReleaseFile() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.0.0.0-full.nupkg", "Squirrel.Core.1.1.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.0.0.0-full.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var filesToFind = new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }; filesToFind.ForEach(x => { var path = Path.Combine(tempDir, "theApp", "app-1.1.0.0", x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); var vi = FileVersionInfo.GetVersionInfo(path); var verInfo = new Version(vi.FileVersion ?? "1.0.0.0"); x.Version.ShouldEqual(verInfo); }); } } [Fact] public async Task ApplyReleaseWhichRemovesAFile() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.1.0.0-full.nupkg", "Squirrel.Core.1.2.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.2.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var rootDirectory = Path.Combine(tempDir, "theApp", "app-1.2.0.0"); new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }.ForEach(x => { var path = Path.Combine(rootDirectory, x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); }); var removedFile = Path.Combine("sub", "Ionic.Zip.dll"); var deployedPath = Path.Combine(rootDirectory, removedFile); File.Exists(deployedPath).ShouldBeFalse(); } } [Fact] public async Task ApplyReleaseWhichMovesAFileToADifferentDirectory() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.1.0.0-full.nupkg", "Squirrel.Core.1.3.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.3.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var rootDirectory = Path.Combine(tempDir, "theApp", "app-1.3.0.0"); new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }.ForEach(x => { var path = Path.Combine(rootDirectory, x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); }); var oldFile = Path.Combine(rootDirectory, "sub", "Ionic.Zip.dll"); File.Exists(oldFile).ShouldBeFalse(); var newFile = Path.Combine(rootDirectory, "other", "Ionic.Zip.dll"); File.Exists(newFile).ShouldBeTrue(); } } [Fact] public async Task ApplyReleasesWithDeltaReleases() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.0.0.0-full.nupkg", "Squirrel.Core.1.1.0.0-delta.nupkg", "Squirrel.Core.1.1.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.0.0.0-full.nupkg")); var deltaEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-delta.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { deltaEntry, latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(deltaEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var filesToFind = new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }; filesToFind.ForEach(x => { var path = Path.Combine(tempDir, "theApp", "app-1.1.0.0", x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); var vi = FileVersionInfo.GetVersionInfo(path); var verInfo = new Version(vi.FileVersion ?? "1.0.0.0"); x.Version.ShouldEqual(verInfo); }); } } [Fact] public async Task CreateFullPackagesFromDeltaSmokeTest() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.0.0.0-full.nupkg", "Squirrel.Core.1.1.0.0-delta.nupkg" }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(tempDir, "theApp", "packages", x))); var urlDownloader = new FakeUrlDownloader(); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(tempDir, "theApp", "packages", "Squirrel.Core.1.0.0.0-full.nupkg")); var deltaEntry = ReleaseEntry.GenerateFromFile(Path.Combine(tempDir, "theApp", "packages", "Squirrel.Core.1.1.0.0-delta.nupkg")); var resultObs = (Task<ReleaseEntry>)fixture.GetType().GetMethod("createFullPackagesFromDeltas", BindingFlags.NonPublic | BindingFlags.Instance) .Invoke(fixture, new object[] { new[] {deltaEntry}, baseEntry }); var result = await resultObs; var zp = new ZipPackage(Path.Combine(tempDir, "theApp", "packages", result.Filename)); zp.Version.ToString().ShouldEqual("1.1.0.0"); } } [Fact] public async Task CreateShortcutsRoundTrip() { string remotePkgPath; string path; using (Utility.WithTempDirectory(out path)) { using (Utility.WithTempDirectory(out remotePkgPath)) using (var mgr = new UpdateManager(remotePkgPath, "theApp", path)) { IntegrationTestHelper.CreateFakeInstalledApp("1.0.0.1", remotePkgPath); await mgr.FullInstall(); } var fixture = new UpdateManager.ApplyReleasesImpl(Path.Combine(path, "theApp")); fixture.CreateShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot, false, null); // NB: COM is Weird. Thread.Sleep(1000); fixture.RemoveShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot); // NB: Squirrel-Aware first-run might still be running, slow // our roll before blowing away the temp path Thread.Sleep(1000); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.OsConfig.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedOsConfigServiceClientTest { [xunit::FactAttribute] public void ExecutePatchJobRequestObject() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); ExecutePatchJobRequest request = new ExecutePatchJobRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Description = "description2cf9da67", PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), DryRun = true, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", Rollout = new PatchRollout(), }; PatchJob expectedResponse = new PatchJob { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = PatchJob.Types.State.Canceled, PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), InstanceDetailsSummary = new PatchJob.Types.InstanceDetailsSummary(), DryRun = true, ErrorMessage = "error_messaged73952bd", PercentComplete = 67289115664290224, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", PatchDeploymentAsPatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.ExecutePatchJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchJob response = client.ExecutePatchJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ExecutePatchJobRequestObjectAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); ExecutePatchJobRequest request = new ExecutePatchJobRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Description = "description2cf9da67", PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), DryRun = true, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", Rollout = new PatchRollout(), }; PatchJob expectedResponse = new PatchJob { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = PatchJob.Types.State.Canceled, PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), InstanceDetailsSummary = new PatchJob.Types.InstanceDetailsSummary(), DryRun = true, ErrorMessage = "error_messaged73952bd", PercentComplete = 67289115664290224, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", PatchDeploymentAsPatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.ExecutePatchJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PatchJob>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchJob responseCallSettings = await client.ExecutePatchJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PatchJob responseCancellationToken = await client.ExecutePatchJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetPatchJobRequestObject() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchJobRequest request = new GetPatchJobRequest { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), }; PatchJob expectedResponse = new PatchJob { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = PatchJob.Types.State.Canceled, PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), InstanceDetailsSummary = new PatchJob.Types.InstanceDetailsSummary(), DryRun = true, ErrorMessage = "error_messaged73952bd", PercentComplete = 67289115664290224, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", PatchDeploymentAsPatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchJob response = client.GetPatchJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPatchJobRequestObjectAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchJobRequest request = new GetPatchJobRequest { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), }; PatchJob expectedResponse = new PatchJob { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = PatchJob.Types.State.Canceled, PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), InstanceDetailsSummary = new PatchJob.Types.InstanceDetailsSummary(), DryRun = true, ErrorMessage = "error_messaged73952bd", PercentComplete = 67289115664290224, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", PatchDeploymentAsPatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PatchJob>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchJob responseCallSettings = await client.GetPatchJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PatchJob responseCancellationToken = await client.GetPatchJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetPatchJob() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchJobRequest request = new GetPatchJobRequest { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), }; PatchJob expectedResponse = new PatchJob { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = PatchJob.Types.State.Canceled, PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), InstanceDetailsSummary = new PatchJob.Types.InstanceDetailsSummary(), DryRun = true, ErrorMessage = "error_messaged73952bd", PercentComplete = 67289115664290224, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", PatchDeploymentAsPatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchJob response = client.GetPatchJob(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPatchJobAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchJobRequest request = new GetPatchJobRequest { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), }; PatchJob expectedResponse = new PatchJob { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = PatchJob.Types.State.Canceled, PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), InstanceDetailsSummary = new PatchJob.Types.InstanceDetailsSummary(), DryRun = true, ErrorMessage = "error_messaged73952bd", PercentComplete = 67289115664290224, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", PatchDeploymentAsPatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PatchJob>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchJob responseCallSettings = await client.GetPatchJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PatchJob responseCancellationToken = await client.GetPatchJobAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetPatchJobResourceNames() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchJobRequest request = new GetPatchJobRequest { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), }; PatchJob expectedResponse = new PatchJob { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = PatchJob.Types.State.Canceled, PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), InstanceDetailsSummary = new PatchJob.Types.InstanceDetailsSummary(), DryRun = true, ErrorMessage = "error_messaged73952bd", PercentComplete = 67289115664290224, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", PatchDeploymentAsPatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchJob response = client.GetPatchJob(request.PatchJobName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPatchJobResourceNamesAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchJobRequest request = new GetPatchJobRequest { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), }; PatchJob expectedResponse = new PatchJob { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = PatchJob.Types.State.Canceled, PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), InstanceDetailsSummary = new PatchJob.Types.InstanceDetailsSummary(), DryRun = true, ErrorMessage = "error_messaged73952bd", PercentComplete = 67289115664290224, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", PatchDeploymentAsPatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PatchJob>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchJob responseCallSettings = await client.GetPatchJobAsync(request.PatchJobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PatchJob responseCancellationToken = await client.GetPatchJobAsync(request.PatchJobName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CancelPatchJobRequestObject() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); CancelPatchJobRequest request = new CancelPatchJobRequest { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), }; PatchJob expectedResponse = new PatchJob { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = PatchJob.Types.State.Canceled, PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), InstanceDetailsSummary = new PatchJob.Types.InstanceDetailsSummary(), DryRun = true, ErrorMessage = "error_messaged73952bd", PercentComplete = 67289115664290224, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", PatchDeploymentAsPatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.CancelPatchJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchJob response = client.CancelPatchJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CancelPatchJobRequestObjectAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); CancelPatchJobRequest request = new CancelPatchJobRequest { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), }; PatchJob expectedResponse = new PatchJob { PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = PatchJob.Types.State.Canceled, PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), InstanceDetailsSummary = new PatchJob.Types.InstanceDetailsSummary(), DryRun = true, ErrorMessage = "error_messaged73952bd", PercentComplete = 67289115664290224, InstanceFilter = new PatchInstanceFilter(), DisplayName = "display_name137f65c2", PatchDeploymentAsPatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.CancelPatchJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PatchJob>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchJob responseCallSettings = await client.CancelPatchJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PatchJob responseCancellationToken = await client.CancelPatchJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreatePatchDeploymentRequestObject() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); CreatePatchDeploymentRequest request = new CreatePatchDeploymentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), PatchDeploymentId = "patch_deployment_id084ea38b", PatchDeployment = new PatchDeployment(), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.CreatePatchDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment response = client.CreatePatchDeployment(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreatePatchDeploymentRequestObjectAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); CreatePatchDeploymentRequest request = new CreatePatchDeploymentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), PatchDeploymentId = "patch_deployment_id084ea38b", PatchDeployment = new PatchDeployment(), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.CreatePatchDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PatchDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment responseCallSettings = await client.CreatePatchDeploymentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PatchDeployment responseCancellationToken = await client.CreatePatchDeploymentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreatePatchDeployment() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); CreatePatchDeploymentRequest request = new CreatePatchDeploymentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), PatchDeploymentId = "patch_deployment_id084ea38b", PatchDeployment = new PatchDeployment(), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.CreatePatchDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment response = client.CreatePatchDeployment(request.Parent, request.PatchDeployment, request.PatchDeploymentId); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreatePatchDeploymentAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); CreatePatchDeploymentRequest request = new CreatePatchDeploymentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), PatchDeploymentId = "patch_deployment_id084ea38b", PatchDeployment = new PatchDeployment(), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.CreatePatchDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PatchDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment responseCallSettings = await client.CreatePatchDeploymentAsync(request.Parent, request.PatchDeployment, request.PatchDeploymentId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PatchDeployment responseCancellationToken = await client.CreatePatchDeploymentAsync(request.Parent, request.PatchDeployment, request.PatchDeploymentId, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreatePatchDeploymentResourceNames() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); CreatePatchDeploymentRequest request = new CreatePatchDeploymentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), PatchDeploymentId = "patch_deployment_id084ea38b", PatchDeployment = new PatchDeployment(), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.CreatePatchDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment response = client.CreatePatchDeployment(request.ParentAsProjectName, request.PatchDeployment, request.PatchDeploymentId); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreatePatchDeploymentResourceNamesAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); CreatePatchDeploymentRequest request = new CreatePatchDeploymentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), PatchDeploymentId = "patch_deployment_id084ea38b", PatchDeployment = new PatchDeployment(), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.CreatePatchDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PatchDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment responseCallSettings = await client.CreatePatchDeploymentAsync(request.ParentAsProjectName, request.PatchDeployment, request.PatchDeploymentId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PatchDeployment responseCancellationToken = await client.CreatePatchDeploymentAsync(request.ParentAsProjectName, request.PatchDeployment, request.PatchDeploymentId, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetPatchDeploymentRequestObject() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchDeploymentRequest request = new GetPatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment response = client.GetPatchDeployment(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPatchDeploymentRequestObjectAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchDeploymentRequest request = new GetPatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PatchDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment responseCallSettings = await client.GetPatchDeploymentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PatchDeployment responseCancellationToken = await client.GetPatchDeploymentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetPatchDeployment() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchDeploymentRequest request = new GetPatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment response = client.GetPatchDeployment(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPatchDeploymentAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchDeploymentRequest request = new GetPatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PatchDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment responseCallSettings = await client.GetPatchDeploymentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PatchDeployment responseCancellationToken = await client.GetPatchDeploymentAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetPatchDeploymentResourceNames() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchDeploymentRequest request = new GetPatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment response = client.GetPatchDeployment(request.PatchDeploymentName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPatchDeploymentResourceNamesAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); GetPatchDeploymentRequest request = new GetPatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; PatchDeployment expectedResponse = new PatchDeployment { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), Description = "description2cf9da67", InstanceFilter = new PatchInstanceFilter(), PatchConfig = new PatchConfig(), Duration = new wkt::Duration(), OneTimeSchedule = new OneTimeSchedule(), RecurringSchedule = new RecurringSchedule(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), LastExecuteTime = new wkt::Timestamp(), Rollout = new PatchRollout(), }; mockGrpcClient.Setup(x => x.GetPatchDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PatchDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); PatchDeployment responseCallSettings = await client.GetPatchDeploymentAsync(request.PatchDeploymentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PatchDeployment responseCancellationToken = await client.GetPatchDeploymentAsync(request.PatchDeploymentName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePatchDeploymentRequestObject() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); DeletePatchDeploymentRequest request = new DeletePatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePatchDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); client.DeletePatchDeployment(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePatchDeploymentRequestObjectAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); DeletePatchDeploymentRequest request = new DeletePatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePatchDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); await client.DeletePatchDeploymentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePatchDeploymentAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePatchDeployment() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); DeletePatchDeploymentRequest request = new DeletePatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePatchDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); client.DeletePatchDeployment(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePatchDeploymentAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); DeletePatchDeploymentRequest request = new DeletePatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePatchDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); await client.DeletePatchDeploymentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePatchDeploymentAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePatchDeploymentResourceNames() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); DeletePatchDeploymentRequest request = new DeletePatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePatchDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); client.DeletePatchDeployment(request.PatchDeploymentName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePatchDeploymentResourceNamesAsync() { moq::Mock<OsConfigService.OsConfigServiceClient> mockGrpcClient = new moq::Mock<OsConfigService.OsConfigServiceClient>(moq::MockBehavior.Strict); DeletePatchDeploymentRequest request = new DeletePatchDeploymentRequest { PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePatchDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigServiceClient client = new OsConfigServiceClientImpl(mockGrpcClient.Object, null); await client.DeletePatchDeploymentAsync(request.PatchDeploymentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePatchDeploymentAsync(request.PatchDeploymentName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
// 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.Xsl.Runtime { using System; using System.Diagnostics; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; /// <summary> /// This writer supports only writer methods which write attributes. Attributes are stored in a /// data structure until StartElementContent() is called, at which time the attributes are flushed /// to the wrapped writer. In the case of duplicate attributes, the last attribute's value is used. /// </summary> internal sealed class XmlAttributeCache : XmlRawWriter, IRemovableWriter { private XmlRawWriter _wrapped; private OnRemoveWriter _onRemove; // Event handler that is called when cached attributes are flushed to wrapped writer private AttrNameVal[] _arrAttrs; // List of cached attribute names and value parts private int _numEntries; // Number of attributes in the cache private int _idxLastName; // The entry containing the name of the last attribute to be cached private int _hashCodeUnion; // Set of hash bits that can quickly guarantee a name is not a duplicate /// <summary> /// Initialize the cache. Use this method instead of a constructor in order to reuse the cache. /// </summary> public void Init(XmlRawWriter wrapped) { SetWrappedWriter(wrapped); // Clear attribute list _numEntries = 0; _idxLastName = 0; _hashCodeUnion = 0; } /// <summary> /// Return the number of cached attributes. /// </summary> public int Count { get { return _numEntries; } } //----------------------------------------------- // IRemovableWriter interface //----------------------------------------------- /// <summary> /// This writer will raise this event once cached attributes have been flushed in order to signal that the cache /// no longer needs to be part of the pipeline. /// </summary> public OnRemoveWriter OnRemoveWriterEvent { get { return _onRemove; } set { _onRemove = value; } } /// <summary> /// The wrapped writer will callback on this method if it wishes to remove itself from the pipeline. /// </summary> private void SetWrappedWriter(XmlRawWriter writer) { // If new writer might remove itself from pipeline, have it callback on this method when its ready to go IRemovableWriter removable = writer as IRemovableWriter; if (removable != null) removable.OnRemoveWriterEvent = SetWrappedWriter; _wrapped = writer; } //----------------------------------------------- // XmlWriter interface //----------------------------------------------- /// <summary> /// Add an attribute to the cache. If an attribute if the same name already exists, replace it. /// </summary> public override void WriteStartAttribute(string prefix, string localName, string ns) { int hashCode; int idx = 0; Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); // Compute hashcode based on first letter of the localName hashCode = (1 << ((int)localName[0] & 31)); // If the hashcode is not in the union, then name will not be found by a scan if ((_hashCodeUnion & hashCode) != 0) { // The name may or may not be present, so scan for it Debug.Assert(_numEntries != 0); do { if (_arrAttrs[idx].IsDuplicate(localName, ns, hashCode)) break; // Next attribute name idx = _arrAttrs[idx].NextNameIndex; } while (idx != 0); } else { // Insert hashcode into union _hashCodeUnion |= hashCode; } // Insert new attribute; link attribute names together in a list EnsureAttributeCache(); if (_numEntries != 0) _arrAttrs[_idxLastName].NextNameIndex = _numEntries; _idxLastName = _numEntries++; _arrAttrs[_idxLastName].Init(prefix, localName, ns, hashCode); } /// <summary> /// No-op. /// </summary> public override void WriteEndAttribute() { } /// <summary> /// Pass through namespaces to underlying writer. If any attributes have been cached, flush them. /// </summary> internal override void WriteNamespaceDeclaration(string prefix, string ns) { FlushAttributes(); _wrapped.WriteNamespaceDeclaration(prefix, ns); } /// <summary> /// Add a block of text to the cache. This text block makes up some or all of the untyped string /// value of the current attribute. /// </summary> public override void WriteString(string text) { Debug.Assert(text != null); Debug.Assert(_arrAttrs != null && _numEntries != 0); EnsureAttributeCache(); _arrAttrs[_numEntries++].Init(text); } /// <summary> /// All other WriteValue methods are implemented by XmlWriter to delegate to WriteValue(object) or WriteValue(string), so /// only these two methods need to be implemented. /// </summary> public override void WriteValue(object value) { Debug.Assert(value is XmlAtomicValue, "value should always be an XmlAtomicValue, as XmlAttributeCache is only used by XmlQueryOutput"); Debug.Assert(_arrAttrs != null && _numEntries != 0); EnsureAttributeCache(); _arrAttrs[_numEntries++].Init((XmlAtomicValue)value); } public override void WriteValue(string value) { WriteValue(value); } /// <summary> /// Send cached, non-overridden attributes to the specified writer. Calling this method has /// the side effect of clearing the attribute cache. /// </summary> internal override void StartElementContent() { FlushAttributes(); // Call StartElementContent on wrapped writer _wrapped.StartElementContent(); } public override void WriteStartElement(string prefix, string localName, string ns) { Debug.Fail("Should never be called on XmlAttributeCache."); } internal override void WriteEndElement(string prefix, string localName, string ns) { Debug.Fail("Should never be called on XmlAttributeCache."); } public override void WriteComment(string text) { Debug.Fail("Should never be called on XmlAttributeCache."); } public override void WriteProcessingInstruction(string name, string text) { Debug.Fail("Should never be called on XmlAttributeCache."); } public override void WriteEntityRef(string name) { Debug.Fail("Should never be called on XmlAttributeCache."); } /// <summary> /// Forward call to wrapped writer. /// </summary> public override void Close() { _wrapped.Close(); } /// <summary> /// Forward call to wrapped writer. /// </summary> public override void Flush() { _wrapped.Flush(); } //----------------------------------------------- // Helper methods //----------------------------------------------- private void FlushAttributes() { int idx = 0, idxNext; string localName; while (idx != _numEntries) { // Get index of next attribute's name (0 if this is the last attribute) idxNext = _arrAttrs[idx].NextNameIndex; if (idxNext == 0) idxNext = _numEntries; // If localName is null, then this is a duplicate attribute that has been marked as "deleted" localName = _arrAttrs[idx].LocalName; if (localName != null) { string prefix = _arrAttrs[idx].Prefix; string ns = _arrAttrs[idx].Namespace; _wrapped.WriteStartAttribute(prefix, localName, ns); // Output all of this attribute's text or typed values while (++idx != idxNext) { string text = _arrAttrs[idx].Text; if (text != null) _wrapped.WriteString(text); else _wrapped.WriteValue(_arrAttrs[idx].Value); } _wrapped.WriteEndAttribute(); } else { // Skip over duplicate attributes idx = idxNext; } } // Notify event listener that attributes have been flushed if (_onRemove != null) _onRemove(_wrapped); } private struct AttrNameVal { private string _localName; private string _prefix; private string _namespaceName; private string _text; private XmlAtomicValue _value; private int _hashCode; private int _nextNameIndex; public string LocalName { get { return _localName; } } public string Prefix { get { return _prefix; } } public string Namespace { get { return _namespaceName; } } public string Text { get { return _text; } } public XmlAtomicValue Value { get { return _value; } } public int NextNameIndex { get { return _nextNameIndex; } set { _nextNameIndex = value; } } /// <summary> /// Cache an attribute's name and type. /// </summary> public void Init(string prefix, string localName, string ns, int hashCode) { _localName = localName; _prefix = prefix; _namespaceName = ns; _hashCode = hashCode; _nextNameIndex = 0; } /// <summary> /// Cache all or part of the attribute's string value. /// </summary> public void Init(string text) { _text = text; _value = null; } /// <summary> /// Cache all or part of the attribute's typed value. /// </summary> public void Init(XmlAtomicValue value) { _text = null; _value = value; } /// <summary> /// Returns true if this attribute has the specified name (and thus is a duplicate). /// </summary> public bool IsDuplicate(string localName, string ns, int hashCode) { // If attribute is not marked as deleted if (_localName != null) { // And if hash codes match, if (_hashCode == hashCode) { // And if local names match, if (_localName.Equals(localName)) { // And if namespaces match, if (_namespaceName.Equals(ns)) { // Then found duplicate attribute, so mark the attribute as deleted _localName = null; return true; } } } } return false; } } #if DEBUG private const int DefaultCacheSize = 2; #else private const int DefaultCacheSize = 32; #endif /// <summary> /// Ensure that attribute array has been created and is large enough for at least one /// additional entry. /// </summary> private void EnsureAttributeCache() { if (_arrAttrs == null) { // Create caching array _arrAttrs = new AttrNameVal[DefaultCacheSize]; } else if (_numEntries >= _arrAttrs.Length) { // Resize caching array Debug.Assert(_numEntries == _arrAttrs.Length); AttrNameVal[] arrNew = new AttrNameVal[_numEntries * 2]; Array.Copy(_arrAttrs, arrNew, _numEntries); _arrAttrs = arrNew; } } } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using DecodeHintType = com.google.zxing.DecodeHintType; using ReaderException = com.google.zxing.ReaderException; using ResultPoint = com.google.zxing.ResultPoint; using ResultPointCallback = com.google.zxing.ResultPointCallback; using BitMatrix = com.google.zxing.common.BitMatrix; using DetectorResult = com.google.zxing.common.DetectorResult; using GridSampler = com.google.zxing.common.GridSampler; using PerspectiveTransform = com.google.zxing.common.PerspectiveTransform; using Version = com.google.zxing.qrcode.decoder.Version; namespace com.google.zxing.qrcode.detector { /// <summary> <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code /// is rotated or skewed, or partially obscured.</p> /// /// </summary> /// <author> Sean Owen /// </author> /// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source /// </author> public class Detector { virtual protected internal BitMatrix Image { get { return image; } } virtual protected internal ResultPointCallback ResultPointCallback { get { return resultPointCallback; } } //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private BitMatrix image; private ResultPointCallback resultPointCallback; public Detector(BitMatrix image) { this.image = image; } /// <summary> <p>Detects a QR Code in an image, simply.</p> /// /// </summary> /// <returns> {@link DetectorResult} encapsulating results of detecting a QR Code /// </returns> /// <throws> ReaderException if no QR Code can be found </throws> public virtual DetectorResult detect() { return detect(null); } /// <summary> <p>Detects a QR Code in an image, simply.</p> /// /// </summary> /// <param name="hints">optional hints to detector /// </param> /// <returns> {@link DetectorResult} encapsulating results of detecting a QR Code /// </returns> /// <throws> ReaderException if no QR Code can be found </throws> public virtual DetectorResult detect(System.Collections.Hashtable hints) { resultPointCallback = hints == null?null:(ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK]; FinderPatternFinder finder = new FinderPatternFinder(image, resultPointCallback); FinderPatternInfo info = finder.find(hints); return processFinderPatternInfo(info); } protected internal virtual DetectorResult processFinderPatternInfo(FinderPatternInfo info) { FinderPattern topLeft = info.TopLeft; FinderPattern topRight = info.TopRight; FinderPattern bottomLeft = info.BottomLeft; float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft); if (moduleSize < 1.0f) { throw ReaderException.Instance; } int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize); Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension); int modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7; AlignmentPattern alignmentPattern = null; // Anything above version 1 has an alignment pattern if (provisionalVersion.AlignmentPatternCenters.Length > 0) { // Guess where a "bottom right" finder pattern would have been float bottomRightX = topRight.X - topLeft.X + bottomLeft.X; float bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y; // Estimate that alignment pattern is closer by 3 modules // from "bottom right" to known top left location //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" int estAlignmentX = (int) (topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X)); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" int estAlignmentY = (int) (topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y)); // Kind of arbitrary -- expand search radius before giving up for (int i = 4; i <= 16; i <<= 1) { try { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" alignmentPattern = findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, (float) i); break; } catch (ReaderException) { // try next round } } // If we didn't find alignment pattern... well try anyway without it } PerspectiveTransform transform = createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension); BitMatrix bits = sampleGrid(image, transform, dimension); ResultPoint[] points; if (alignmentPattern == null) { points = new ResultPoint[]{bottomLeft, topLeft, topRight}; } else { points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern}; } return new DetectorResult(bits, points); } public virtual PerspectiveTransform createTransform(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, ResultPoint alignmentPattern, int dimension) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float dimMinusThree = (float) dimension - 3.5f; float bottomRightX; float bottomRightY; float sourceBottomRightX; float sourceBottomRightY; if (alignmentPattern != null) { bottomRightX = alignmentPattern.X; bottomRightY = alignmentPattern.Y; sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0f; } else { // Don't have an alignment pattern, just make up the bottom-right point bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X; bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y; sourceBottomRightX = sourceBottomRightY = dimMinusThree; } PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral(3.5f, 3.5f, dimMinusThree, 3.5f, sourceBottomRightX, sourceBottomRightY, 3.5f, dimMinusThree, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRightX, bottomRightY, bottomLeft.X, bottomLeft.Y); return transform; } private static BitMatrix sampleGrid(BitMatrix image, PerspectiveTransform transform, int dimension) { GridSampler sampler = GridSampler.Instance; return sampler.sampleGrid(image, dimension, transform); } /// <summary> <p>Computes the dimension (number of modules on a size) of the QR Code based on the position /// of the finder patterns and estimated module size.</p> /// </summary> protected internal static int computeDimension(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, float moduleSize) { int tltrCentersDimension = round(ResultPoint.distance(topLeft, topRight) / moduleSize); int tlblCentersDimension = round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize); int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; switch (dimension & 0x03) { // mod 4 case 0: dimension++; break; // 1? do nothing case 2: dimension--; break; case 3: throw ReaderException.Instance; } return dimension; } /// <summary> <p>Computes an average estimated module size based on estimated derived from the positions /// of the three finder patterns.</p> /// </summary> protected internal virtual float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft) { // Take the average return (calculateModuleSizeOneWay(topLeft, topRight) + calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f; } /// <summary> <p>Estimates module size based on two finder patterns -- it uses /// {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the /// width of each, measuring along the axis between their centers.</p> /// </summary> private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.X, (int) pattern.Y, (int) otherPattern.X, (int) otherPattern.Y); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.X, (int) otherPattern.Y, (int) pattern.X, (int) pattern.Y); if (System.Single.IsNaN(moduleSizeEst1)) { return moduleSizeEst2 / 7.0f; } if (System.Single.IsNaN(moduleSizeEst2)) { return moduleSizeEst1 / 7.0f; } // Average them, and divide by 7 since we've counted the width of 3 black modules, // and 1 white and 1 black module on either side. Ergo, divide sum by 14. return (moduleSizeEst1 + moduleSizeEst2) / 14.0f; } /// <summary> See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of /// a finder pattern by looking for a black-white-black run from the center in the direction /// of another point (another finder pattern center), and in the opposite direction too.</p> /// </summary> private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) { float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); // Now count other way -- don't run off image though of course float scale = 1.0f; int otherToX = fromX - (toX - fromX); if (otherToX < 0) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" scale = (float) fromX / (float) (fromX - otherToX); otherToX = 0; } else if (otherToX >= image.Width) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" scale = (float) (image.Width - 1 - fromX) / (float) (otherToX - fromX); otherToX = image.Width - 1; } //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" int otherToY = (int) (fromY - (toY - fromY) * scale); scale = 1.0f; if (otherToY < 0) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" scale = (float) fromY / (float) (fromY - otherToY); otherToY = 0; } else if (otherToY >= image.Height) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" scale = (float) (image.Height - 1 - fromY) / (float) (otherToY - fromY); otherToY = image.Height - 1; } //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" otherToX = (int) (fromX + (otherToX - fromX) * scale); result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); return result - 1.0f; // -1 because we counted the middle pixel twice } /// <summary> <p>This method traces a line from a point in the image, in the direction towards another point. /// It begins in a black region, and keeps going until it finds white, then black, then white again. /// It reports the distance from the start to this point.</p> /// /// <p>This is used when figuring out how wide a finder pattern is, when the finder pattern /// may be skewed or rotated.</p> /// </summary> private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) { // Mild variant of Bresenham's algorithm; // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm bool steep = System.Math.Abs(toY - fromY) > System.Math.Abs(toX - fromX); if (steep) { int temp = fromX; fromX = fromY; fromY = temp; temp = toX; toX = toY; toY = temp; } int dx = System.Math.Abs(toX - fromX); int dy = System.Math.Abs(toY - fromY); int error = - dx >> 1; int ystep = fromY < toY?1:- 1; int xstep = fromX < toX?1:- 1; int state = 0; // In black pixels, looking for white, first or second time for (int x = fromX, y = fromY; x != toX; x += xstep) { int realX = steep?y:x; int realY = steep?x:y; if (state == 1) { // In white pixels, looking for black if (image.get_Renamed(realX, realY)) { state++; } } else { if (!image.get_Renamed(realX, realY)) { state++; } } if (state == 3) { // Found black, white, black, and stumbled back onto white; done int diffX = x - fromX; int diffY = y - fromY; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return (float) System.Math.Sqrt((double) (diffX * diffX + diffY * diffY)); } error += dy; if (error > 0) { if (y == toY) { break; } y += ystep; error -= dx; } } int diffX2 = toX - fromX; int diffY2 = toY - fromY; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return (float) System.Math.Sqrt((double) (diffX2 * diffX2 + diffY2 * diffY2)); } /// <summary> <p>Attempts to locate an alignment pattern in a limited region of the image, which is /// guessed to contain it. This method uses {@link AlignmentPattern}.</p> /// /// </summary> /// <param name="overallEstModuleSize">estimated module size so far /// </param> /// <param name="estAlignmentX">x coordinate of center of area probably containing alignment pattern /// </param> /// <param name="estAlignmentY">y coordinate of above /// </param> /// <param name="allowanceFactor">number of pixels in all directions to search from the center /// </param> /// <returns> {@link AlignmentPattern} if found, or null otherwise /// </returns> /// <throws> ReaderException if an unexpected error occurs during detection </throws> protected internal virtual AlignmentPattern findAlignmentInRegion(float overallEstModuleSize, int estAlignmentX, int estAlignmentY, float allowanceFactor) { // Look for an alignment pattern (3 modules in size) around where it // should be //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" int allowance = (int) (allowanceFactor * overallEstModuleSize); int alignmentAreaLeftX = System.Math.Max(0, estAlignmentX - allowance); int alignmentAreaRightX = System.Math.Min(image.Width - 1, estAlignmentX + allowance); if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) { throw ReaderException.Instance; } int alignmentAreaTopY = System.Math.Max(0, estAlignmentY - allowance); int alignmentAreaBottomY = System.Math.Min(image.Height - 1, estAlignmentY + allowance); AlignmentPatternFinder alignmentFinder = new AlignmentPatternFinder(image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, resultPointCallback); return alignmentFinder.find(); } /// <summary> Ends up being a bit faster than Math.round(). This merely rounds its argument to the nearest int, /// where x.5 rounds up. /// </summary> private static int round(float d) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return (int) (d + 0.5f); } } }
using System; using System.Collections.Generic; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium.Support.UI { [TestFixture] public class SelectBrowserTests : DriverTestFixture { [OneTimeSetUp] public void RunBeforeAnyTest() { EnvironmentManager.Instance.WebServer.Start(); } [OneTimeTearDown] public void RunAfterAnyTests() { EnvironmentManager.Instance.CloseCurrentDriver(); EnvironmentManager.Instance.WebServer.Stop(); } [SetUp] public void Setup() { driver.Url = formsPage; } [Test] public void ShouldThrowAnExceptionIfTheElementIsNotASelectElement() { IWebElement element = driver.FindElement(By.Name("checky")); Assert.Throws<UnexpectedTagNameException>(() => { SelectElement elementWrapper = new SelectElement(element); }); } [Test] public void ShouldIndicateThatASelectCanSupportMultipleOptions() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); Assert.IsTrue(elementWrapper.IsMultiple); } [Test] public void ShouldIndicateThatASelectCanSupportMultipleOptionsWithEmptyMultipleAttribute() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); Assert.IsTrue(elementWrapper.IsMultiple); } [Test] public void ShouldIndicateThatASelectCanSupportMultipleOptionsWithTrueMultipleAttribute() { IWebElement element = driver.FindElement(By.Name("multi_true")); SelectElement elementWrapper = new SelectElement(element); Assert.IsTrue(elementWrapper.IsMultiple); } [Test] public void ShouldNotIndicateThatANormalSelectSupportsMulitpleOptions() { IWebElement element = driver.FindElement(By.Name("selectomatic")); SelectElement elementWrapper = new SelectElement(element); Assert.IsFalse(elementWrapper.IsMultiple); } [Test] public void ShouldIndicateThatASelectCanSupportMultipleOptionsWithFalseMultipleAttribute() { IWebElement element = driver.FindElement(By.Name("multi_false")); SelectElement elementWrapper = new SelectElement(element); Assert.IsTrue(elementWrapper.IsMultiple); } [Test] public void ShouldReturnAllOptionsWhenAsked() { IWebElement element = driver.FindElement(By.Name("selectomatic")); SelectElement elementWrapper = new SelectElement(element); IList<IWebElement> returnedOptions = elementWrapper.Options; Assert.AreEqual(4, returnedOptions.Count); string one = returnedOptions[0].Text; Assert.AreEqual("One", one); string two = returnedOptions[1].Text; Assert.AreEqual("Two", two); string three = returnedOptions[2].Text; Assert.AreEqual("Four", three); string four = returnedOptions[3].Text; Assert.AreEqual("Still learning how to count, apparently", four); } [Test] public void ShouldReturnOptionWhichIsSelected() { IWebElement element = driver.FindElement(By.Name("selectomatic")); SelectElement elementWrapper = new SelectElement(element); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(1, returnedOptions.Count); string one = returnedOptions[0].Text; Assert.AreEqual("One", one); } [Test] public void ShouldReturnOptionsWhichAreSelected() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(2, returnedOptions.Count); string one = returnedOptions[0].Text; Assert.AreEqual("Eggs", one); string two = returnedOptions[1].Text; Assert.AreEqual("Sausages", two); } [Test] public void ShouldReturnFirstSelectedOption() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); IWebElement firstSelected = elementWrapper.AllSelectedOptions[0]; Assert.AreEqual("Eggs", firstSelected.Text); } // [Test] // [ExpectedException(typeof(NoSuchElementException))] // The .NET bindings do not have a "FirstSelectedOption" property, // and no one has asked for it to this point. Given that, this test // is not a valid test. public void ShouldThrowANoSuchElementExceptionIfNothingIsSelected() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); Assert.AreEqual(0, elementWrapper.AllSelectedOptions.Count); } [Test] public void ShouldAllowOptionsToBeSelectedByVisibleText() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByText("select_2"); IWebElement firstSelected = elementWrapper.AllSelectedOptions[0]; Assert.AreEqual("select_2", firstSelected.Text); } [Test] public void ShouldNotAllowInvisibleOptionsToBeSelectedByVisibleText() { IWebElement element = driver.FindElement(By.Name("invisi_select")); SelectElement elementWrapper = new SelectElement(element); Assert.Throws<NoSuchElementException>(() => elementWrapper.SelectByText("Apples")); } [Test] public void ShouldThrowExceptionOnSelectByVisibleTextIfOptionDoesNotExist() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); Assert.Throws<NoSuchElementException>(() => elementWrapper.SelectByText("not there")); } [Test] public void ShouldAllowOptionsToBeSelectedByIndex() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByIndex(1); IWebElement firstSelected = elementWrapper.AllSelectedOptions[0]; Assert.AreEqual("select_2", firstSelected.Text); } [Test] public void ShouldThrowExceptionOnSelectByIndexIfOptionDoesNotExist() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); Assert.Throws<NoSuchElementException>(() => elementWrapper.SelectByIndex(10)); } [Test] public void ShouldAllowOptionsToBeSelectedByReturnedValue() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByValue("select_2"); IWebElement firstSelected = elementWrapper.AllSelectedOptions[0]; Assert.AreEqual("select_2", firstSelected.Text); } [Test] public void ShouldThrowExceptionOnSelectByReturnedValueIfOptionDoesNotExist() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); Assert.Throws<NoSuchElementException>(() => elementWrapper.SelectByValue("not there")); } [Test] public void ShouldAllowUserToDeselectAllWhenSelectSupportsMultipleSelections() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.DeselectAll(); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(0, returnedOptions.Count); } [Test] public void ShouldNotAllowUserToDeselectAllWhenSelectDoesNotSupportMultipleSelections() { IWebElement element = driver.FindElement(By.Name("selectomatic")); SelectElement elementWrapper = new SelectElement(element); Assert.Throws<InvalidOperationException>(() => elementWrapper.DeselectAll()); } [Test] public void ShouldAllowUserToDeselectOptionsByVisibleText() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.DeselectByText("Eggs"); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(1, returnedOptions.Count); } [Test] public void ShouldNotAllowUserToDeselectOptionsByInvisibleText() { IWebElement element = driver.FindElement(By.Name("invisi_select")); SelectElement elementWrapper = new SelectElement(element); Assert.Throws<NoSuchElementException>(() => elementWrapper.DeselectByText("Apples")); } [Test] public void ShouldAllowOptionsToBeDeselectedByIndex() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.DeselectByIndex(0); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(1, returnedOptions.Count); } [Test] public void ShouldAllowOptionsToBeDeselectedByReturnedValue() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.DeselectByValue("eggs"); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(1, returnedOptions.Count); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Dynamic.Utils; namespace System.Linq.Expressions.Compiler { internal partial class StackSpiller { /// <summary> /// Rewrite the expression /// </summary> /// /// <param name="node">Expression to rewrite</param> /// <param name="stack">State of the stack before the expression is emitted.</param> /// <returns>Rewritten expression.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private Result RewriteExpression(Expression node, Stack stack) { if (node == null) { return new Result(RewriteAction.None, null); } Result result; switch (node.NodeType) { case ExpressionType.Add: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.AddChecked: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.And: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.AndAlso: result = RewriteLogicalBinaryExpression(node, stack); break; case ExpressionType.ArrayLength: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.ArrayIndex: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.Call: result = RewriteMethodCallExpression(node, stack); break; case ExpressionType.Coalesce: result = RewriteLogicalBinaryExpression(node, stack); break; case ExpressionType.Conditional: result = RewriteConditionalExpression(node, stack); break; case ExpressionType.Convert: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.ConvertChecked: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.Divide: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.Equal: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.ExclusiveOr: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.GreaterThan: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.GreaterThanOrEqual: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.Invoke: result = RewriteInvocationExpression(node, stack); break; case ExpressionType.Lambda: result = RewriteLambdaExpression(node, stack); break; case ExpressionType.LeftShift: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.LessThan: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.LessThanOrEqual: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.ListInit: result = RewriteListInitExpression(node, stack); break; case ExpressionType.MemberAccess: result = RewriteMemberExpression(node, stack); break; case ExpressionType.MemberInit: result = RewriteMemberInitExpression(node, stack); break; case ExpressionType.Modulo: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.Multiply: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.MultiplyChecked: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.Negate: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.UnaryPlus: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.NegateChecked: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.New: result = RewriteNewExpression(node, stack); break; case ExpressionType.NewArrayInit: result = RewriteNewArrayExpression(node, stack); break; case ExpressionType.NewArrayBounds: result = RewriteNewArrayExpression(node, stack); break; case ExpressionType.Not: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.NotEqual: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.Or: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.OrElse: result = RewriteLogicalBinaryExpression(node, stack); break; case ExpressionType.Power: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.RightShift: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.Subtract: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.SubtractChecked: result = RewriteBinaryExpression(node, stack); break; case ExpressionType.TypeAs: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.TypeIs: result = RewriteTypeBinaryExpression(node, stack); break; case ExpressionType.Assign: result = RewriteAssignBinaryExpression(node, stack); break; case ExpressionType.Block: result = RewriteBlockExpression(node, stack); break; case ExpressionType.Decrement: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.Dynamic: result = RewriteDynamicExpression(node, stack); break; case ExpressionType.Extension: result = RewriteExtensionExpression(node, stack); break; case ExpressionType.Goto: result = RewriteGotoExpression(node, stack); break; case ExpressionType.Increment: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.Index: result = RewriteIndexExpression(node, stack); break; case ExpressionType.Label: result = RewriteLabelExpression(node, stack); break; case ExpressionType.Loop: result = RewriteLoopExpression(node, stack); break; case ExpressionType.Switch: result = RewriteSwitchExpression(node, stack); break; case ExpressionType.Throw: result = RewriteThrowUnaryExpression(node, stack); break; case ExpressionType.Try: result = RewriteTryExpression(node, stack); break; case ExpressionType.Unbox: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.TypeEqual: result = RewriteTypeBinaryExpression(node, stack); break; case ExpressionType.OnesComplement: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.IsTrue: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.IsFalse: result = RewriteUnaryExpression(node, stack); break; case ExpressionType.AddAssign: case ExpressionType.AndAssign: case ExpressionType.DivideAssign: case ExpressionType.ExclusiveOrAssign: case ExpressionType.LeftShiftAssign: case ExpressionType.ModuloAssign: case ExpressionType.MultiplyAssign: case ExpressionType.OrAssign: case ExpressionType.PowerAssign: case ExpressionType.RightShiftAssign: case ExpressionType.SubtractAssign: case ExpressionType.AddAssignChecked: case ExpressionType.MultiplyAssignChecked: case ExpressionType.SubtractAssignChecked: case ExpressionType.PreIncrementAssign: case ExpressionType.PreDecrementAssign: case ExpressionType.PostIncrementAssign: case ExpressionType.PostDecrementAssign: result = RewriteReducibleExpression(node, stack); break; case ExpressionType.Quote: case ExpressionType.Parameter: case ExpressionType.Constant: case ExpressionType.RuntimeVariables: case ExpressionType.Default: case ExpressionType.DebugInfo: return new Result(RewriteAction.None, node); default: throw ContractUtils.Unreachable; } VerifyRewrite(result, node); return result; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.OsConfig.V1Alpha.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedOsConfigZonalServiceClientTest { [xunit::FactAttribute] public void GetOSPolicyAssignmentRequestObject() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), }; OSPolicyAssignment expectedResponse = new OSPolicyAssignment { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), Description = "description2cf9da67", OsPolicies = { new OSPolicy(), }, InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(), Rollout = new OSPolicyAssignment.Types.Rollout(), RevisionId = "revision_id8d9ae05d", RevisionCreateTime = new wkt::Timestamp(), RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling, Baseline = false, Deleted = true, Reconciling = false, Uid = "uida2d37198", }; mockGrpcClient.Setup(x => x.GetOSPolicyAssignment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); OSPolicyAssignment response = client.GetOSPolicyAssignment(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetOSPolicyAssignmentRequestObjectAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), }; OSPolicyAssignment expectedResponse = new OSPolicyAssignment { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), Description = "description2cf9da67", OsPolicies = { new OSPolicy(), }, InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(), Rollout = new OSPolicyAssignment.Types.Rollout(), RevisionId = "revision_id8d9ae05d", RevisionCreateTime = new wkt::Timestamp(), RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling, Baseline = false, Deleted = true, Reconciling = false, Uid = "uida2d37198", }; mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); OSPolicyAssignment responseCallSettings = await client.GetOSPolicyAssignmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); OSPolicyAssignment responseCancellationToken = await client.GetOSPolicyAssignmentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetOSPolicyAssignment() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), }; OSPolicyAssignment expectedResponse = new OSPolicyAssignment { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), Description = "description2cf9da67", OsPolicies = { new OSPolicy(), }, InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(), Rollout = new OSPolicyAssignment.Types.Rollout(), RevisionId = "revision_id8d9ae05d", RevisionCreateTime = new wkt::Timestamp(), RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling, Baseline = false, Deleted = true, Reconciling = false, Uid = "uida2d37198", }; mockGrpcClient.Setup(x => x.GetOSPolicyAssignment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); OSPolicyAssignment response = client.GetOSPolicyAssignment(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetOSPolicyAssignmentAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), }; OSPolicyAssignment expectedResponse = new OSPolicyAssignment { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), Description = "description2cf9da67", OsPolicies = { new OSPolicy(), }, InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(), Rollout = new OSPolicyAssignment.Types.Rollout(), RevisionId = "revision_id8d9ae05d", RevisionCreateTime = new wkt::Timestamp(), RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling, Baseline = false, Deleted = true, Reconciling = false, Uid = "uida2d37198", }; mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); OSPolicyAssignment responseCallSettings = await client.GetOSPolicyAssignmentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); OSPolicyAssignment responseCancellationToken = await client.GetOSPolicyAssignmentAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetOSPolicyAssignmentResourceNames() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), }; OSPolicyAssignment expectedResponse = new OSPolicyAssignment { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), Description = "description2cf9da67", OsPolicies = { new OSPolicy(), }, InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(), Rollout = new OSPolicyAssignment.Types.Rollout(), RevisionId = "revision_id8d9ae05d", RevisionCreateTime = new wkt::Timestamp(), RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling, Baseline = false, Deleted = true, Reconciling = false, Uid = "uida2d37198", }; mockGrpcClient.Setup(x => x.GetOSPolicyAssignment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); OSPolicyAssignment response = client.GetOSPolicyAssignment(request.OSPolicyAssignmentName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetOSPolicyAssignmentResourceNamesAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), }; OSPolicyAssignment expectedResponse = new OSPolicyAssignment { OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"), Description = "description2cf9da67", OsPolicies = { new OSPolicy(), }, InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(), Rollout = new OSPolicyAssignment.Types.Rollout(), RevisionId = "revision_id8d9ae05d", RevisionCreateTime = new wkt::Timestamp(), RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling, Baseline = false, Deleted = true, Reconciling = false, Uid = "uida2d37198", }; mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); OSPolicyAssignment responseCallSettings = await client.GetOSPolicyAssignmentAsync(request.OSPolicyAssignmentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); OSPolicyAssignment responseCancellationToken = await client.GetOSPolicyAssignmentAsync(request.OSPolicyAssignmentName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetInstanceOSPoliciesComplianceRequestObject() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Instance = "instance99a62371", State = OSPolicyComplianceState.Unknown, DetailedState = "detailed_state6d8e814a", DetailedStateReason = "detailed_state_reason493b0c87", OsPolicyCompliances = { new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(), }, LastComplianceCheckTime = new wkt::Timestamp(), LastComplianceRunId = "last_compliance_run_id45f5c46a", }; mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesCompliance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); InstanceOSPoliciesCompliance response = client.GetInstanceOSPoliciesCompliance(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInstanceOSPoliciesComplianceRequestObjectAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Instance = "instance99a62371", State = OSPolicyComplianceState.Unknown, DetailedState = "detailed_state6d8e814a", DetailedStateReason = "detailed_state_reason493b0c87", OsPolicyCompliances = { new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(), }, LastComplianceCheckTime = new wkt::Timestamp(), LastComplianceRunId = "last_compliance_run_id45f5c46a", }; mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesComplianceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceOSPoliciesCompliance>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); InstanceOSPoliciesCompliance responseCallSettings = await client.GetInstanceOSPoliciesComplianceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InstanceOSPoliciesCompliance responseCancellationToken = await client.GetInstanceOSPoliciesComplianceAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetInstanceOSPoliciesCompliance() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Instance = "instance99a62371", State = OSPolicyComplianceState.Unknown, DetailedState = "detailed_state6d8e814a", DetailedStateReason = "detailed_state_reason493b0c87", OsPolicyCompliances = { new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(), }, LastComplianceCheckTime = new wkt::Timestamp(), LastComplianceRunId = "last_compliance_run_id45f5c46a", }; mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesCompliance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); InstanceOSPoliciesCompliance response = client.GetInstanceOSPoliciesCompliance(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInstanceOSPoliciesComplianceAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Instance = "instance99a62371", State = OSPolicyComplianceState.Unknown, DetailedState = "detailed_state6d8e814a", DetailedStateReason = "detailed_state_reason493b0c87", OsPolicyCompliances = { new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(), }, LastComplianceCheckTime = new wkt::Timestamp(), LastComplianceRunId = "last_compliance_run_id45f5c46a", }; mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesComplianceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceOSPoliciesCompliance>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); InstanceOSPoliciesCompliance responseCallSettings = await client.GetInstanceOSPoliciesComplianceAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InstanceOSPoliciesCompliance responseCancellationToken = await client.GetInstanceOSPoliciesComplianceAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetInstanceOSPoliciesComplianceResourceNames() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Instance = "instance99a62371", State = OSPolicyComplianceState.Unknown, DetailedState = "detailed_state6d8e814a", DetailedStateReason = "detailed_state_reason493b0c87", OsPolicyCompliances = { new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(), }, LastComplianceCheckTime = new wkt::Timestamp(), LastComplianceRunId = "last_compliance_run_id45f5c46a", }; mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesCompliance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); InstanceOSPoliciesCompliance response = client.GetInstanceOSPoliciesCompliance(request.InstanceOSPoliciesComplianceName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInstanceOSPoliciesComplianceResourceNamesAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceOSPoliciesComplianceRequest request = new GetInstanceOSPoliciesComplianceRequest { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; InstanceOSPoliciesCompliance expectedResponse = new InstanceOSPoliciesCompliance { InstanceOSPoliciesComplianceName = InstanceOSPoliciesComplianceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Instance = "instance99a62371", State = OSPolicyComplianceState.Unknown, DetailedState = "detailed_state6d8e814a", DetailedStateReason = "detailed_state_reason493b0c87", OsPolicyCompliances = { new InstanceOSPoliciesCompliance.Types.OSPolicyCompliance(), }, LastComplianceCheckTime = new wkt::Timestamp(), LastComplianceRunId = "last_compliance_run_id45f5c46a", }; mockGrpcClient.Setup(x => x.GetInstanceOSPoliciesComplianceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceOSPoliciesCompliance>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); InstanceOSPoliciesCompliance responseCallSettings = await client.GetInstanceOSPoliciesComplianceAsync(request.InstanceOSPoliciesComplianceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InstanceOSPoliciesCompliance responseCancellationToken = await client.GetInstanceOSPoliciesComplianceAsync(request.InstanceOSPoliciesComplianceName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetInventoryRequestObject() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInventoryRequest request = new GetInventoryRequest { InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), View = InventoryView.Basic, }; Inventory expectedResponse = new Inventory { OsInfo = new Inventory.Types.OsInfo(), Items = { { "key8a0b6e3c", new Inventory.Types.Item() }, }, InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetInventory(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); Inventory response = client.GetInventory(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInventoryRequestObjectAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInventoryRequest request = new GetInventoryRequest { InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), View = InventoryView.Basic, }; Inventory expectedResponse = new Inventory { OsInfo = new Inventory.Types.OsInfo(), Items = { { "key8a0b6e3c", new Inventory.Types.Item() }, }, InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetInventoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Inventory>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); Inventory responseCallSettings = await client.GetInventoryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Inventory responseCancellationToken = await client.GetInventoryAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetInventory() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInventoryRequest request = new GetInventoryRequest { InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; Inventory expectedResponse = new Inventory { OsInfo = new Inventory.Types.OsInfo(), Items = { { "key8a0b6e3c", new Inventory.Types.Item() }, }, InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetInventory(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); Inventory response = client.GetInventory(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInventoryAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInventoryRequest request = new GetInventoryRequest { InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; Inventory expectedResponse = new Inventory { OsInfo = new Inventory.Types.OsInfo(), Items = { { "key8a0b6e3c", new Inventory.Types.Item() }, }, InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetInventoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Inventory>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); Inventory responseCallSettings = await client.GetInventoryAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Inventory responseCancellationToken = await client.GetInventoryAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetInventoryResourceNames() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInventoryRequest request = new GetInventoryRequest { InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; Inventory expectedResponse = new Inventory { OsInfo = new Inventory.Types.OsInfo(), Items = { { "key8a0b6e3c", new Inventory.Types.Item() }, }, InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetInventory(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); Inventory response = client.GetInventory(request.InventoryName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetInventoryResourceNamesAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInventoryRequest request = new GetInventoryRequest { InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; Inventory expectedResponse = new Inventory { OsInfo = new Inventory.Types.OsInfo(), Items = { { "key8a0b6e3c", new Inventory.Types.Item() }, }, InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetInventoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Inventory>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); Inventory responseCallSettings = await client.GetInventoryAsync(request.InventoryName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Inventory responseCancellationToken = await client.GetInventoryAsync(request.InventoryName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetVulnerabilityReportRequestObject() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; VulnerabilityReport expectedResponse = new VulnerabilityReport { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Vulnerabilities = { new VulnerabilityReport.Types.Vulnerability(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetVulnerabilityReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); VulnerabilityReport response = client.GetVulnerabilityReport(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetVulnerabilityReportRequestObjectAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; VulnerabilityReport expectedResponse = new VulnerabilityReport { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Vulnerabilities = { new VulnerabilityReport.Types.Vulnerability(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetVulnerabilityReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityReport>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); VulnerabilityReport responseCallSettings = await client.GetVulnerabilityReportAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); VulnerabilityReport responseCancellationToken = await client.GetVulnerabilityReportAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetVulnerabilityReport() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; VulnerabilityReport expectedResponse = new VulnerabilityReport { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Vulnerabilities = { new VulnerabilityReport.Types.Vulnerability(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetVulnerabilityReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); VulnerabilityReport response = client.GetVulnerabilityReport(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetVulnerabilityReportAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; VulnerabilityReport expectedResponse = new VulnerabilityReport { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Vulnerabilities = { new VulnerabilityReport.Types.Vulnerability(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetVulnerabilityReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityReport>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); VulnerabilityReport responseCallSettings = await client.GetVulnerabilityReportAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); VulnerabilityReport responseCancellationToken = await client.GetVulnerabilityReportAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetVulnerabilityReportResourceNames() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; VulnerabilityReport expectedResponse = new VulnerabilityReport { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Vulnerabilities = { new VulnerabilityReport.Types.Vulnerability(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetVulnerabilityReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); VulnerabilityReport response = client.GetVulnerabilityReport(request.VulnerabilityReportName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetVulnerabilityReportResourceNamesAsync() { moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), }; VulnerabilityReport expectedResponse = new VulnerabilityReport { VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"), Vulnerabilities = { new VulnerabilityReport.Types.Vulnerability(), }, UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetVulnerabilityReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityReport>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null); VulnerabilityReport responseCallSettings = await client.GetVulnerabilityReportAsync(request.VulnerabilityReportName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); VulnerabilityReport responseCancellationToken = await client.GetVulnerabilityReportAsync(request.VulnerabilityReportName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.CSharp.Analyzers.Maintainability.CSharpUseNameofInPlaceOfStringAnalyzer, Microsoft.CodeQuality.Analyzers.Maintainability.UseNameOfInPlaceOfStringFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.VisualBasic.Analyzers.Maintainability.BasicUseNameofInPlaceOfStringAnalyzer, Microsoft.CodeQuality.Analyzers.Maintainability.UseNameOfInPlaceOfStringFixer>; namespace Microsoft.CodeQuality.Analyzers.Maintainability.UnitTests { public class UseNameofInPlaceOfStringTests { #region Unit tests for no analyzer diagnostic [Fact] public async Task NoDiagnostic_NoArguments() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int x) { throw new ArgumentNullException(); } }"); } [Fact] public async Task NoDiagnostic_NullLiteral() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int x) { throw new ArgumentNullException(null); } }"); } [Fact] public async Task NoDiagnostic_StringIsAReservedWord() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int x) { throw new ArgumentNullException(""static""); } }"); } [Fact] public async Task NoDiagnostic_NoMatchingParametersInScope() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int y) { throw new ArgumentNullException(""x""); } }"); } [Fact] public async Task NoDiagnostic_NameColonOtherParameterName() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int y) { Console.WriteLine(format:""x""); } }"); } [Fact] public async Task NoDiagnostic_NotStringLiteral() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int x) { string param = ""x""; throw new ArgumentNullException(param); } }"); } [Fact] public async Task NoDiagnostic_NotValidIdentifier() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int x) { throw new ArgumentNullException(""9x""); } }"); } [Fact] public async Task NoDiagnostic_NoArgumentList() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int x) { throw new ArgumentNullException({|CS1002:|}{|CS1026:|} } }"); } [Fact] public async Task NoDiagnostic_NoMatchingParameter() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int x) { throw new {|CS1729:ArgumentNullException|}(""test"", ""test2"", ""test3""); } }"); } [Fact] public async Task NoDiagnostic_MatchesParameterButNotCalledParamName() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int x) { Console.WriteLine(""x""); } }"); } [Fact] public async Task NoDiagnostic_MatchesPropertyButNotCalledPropertyName() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.ComponentModel; public class Person : INotifyPropertyChanged { private string name; public event PropertyChangedEventHandler PropertyChanged; public string PersonName { get { return name; } set { name = value; Console.WriteLine(""PersonName""); } } protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } }"); } [Fact] public async Task NoDiagnostic_PositionalArgumentOtherParameterName() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int x) { Console.WriteLine(""x""); } }"); } [WorkItem(1426, "https://github.com/dotnet/roslyn-analyzers/issues/1426")] [Fact] public async Task NoDiagnostic_1426() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Runtime.CompilerServices; public class C { int M([CallerMemberName] string propertyName = """") { return 0; } public bool Property { set { M(); } } }"); } [WorkItem(1524, "https://github.com/dotnet/roslyn-analyzers/issues/1524")] [Fact] public async Task NoDiagnostic_CSharp5() { await new VerifyCS.Test { TestCode = @" using System; class C { void M(int x) { throw new ArgumentNullException(""x""); } }", LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp5 }.RunAsync(); } [WorkItem(1524, "https://github.com/dotnet/roslyn-analyzers/issues/1524")] [Fact] public async Task Diagnostic_CSharp6() { await new VerifyCS.Test { TestCode = @" using System; class C { void M(int x) { throw new ArgumentNullException(""x""); } }", LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp6, ExpectedDiagnostics = { GetCSharpNameofResultAt(7, 41, "x"), } }.RunAsync(); } [WorkItem(1524, "https://github.com/dotnet/roslyn-analyzers/issues/1524")] [Fact] public async Task NoDiagnostic_VB12() { await new VerifyVB.Test { TestCode = @" Imports System Module Mod1 Sub f(s As String) Throw New ArgumentNullException(""s"") End Sub End Module", LanguageVersion = CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic12 }.RunAsync(); } [WorkItem(1524, "https://github.com/dotnet/roslyn-analyzers/issues/1524")] [Fact] public async Task Diagnostic_VB14() { await new VerifyVB.Test { TestCode = @" Imports System Module Mod1 Sub f(s As String) Throw New ArgumentNullException(""s"") End Sub End Module", LanguageVersion = CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14, ExpectedDiagnostics = { GetBasicNameofResultAt(6, 41, "s"), } }.RunAsync(); } #endregion #region Unit tests for analyzer diagnostic(s) [Fact] public async Task Diagnostic_ArgumentMatchesAParameterInScope() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int x) { throw new ArgumentNullException(""x""); } }", GetCSharpNameofResultAt(7, 41, "x")); } [Fact] public async Task Diagnostic_VB_ArgumentMatchesAParameterInScope() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Module Mod1 Sub f(s As String) Throw New ArgumentNullException(""s"") End Sub End Module", GetBasicNameofResultAt(6, 41, "s")); } [Fact] public async Task Diagnostic_ArgumentMatchesAPropertyInScope() { await VerifyCS.VerifyAnalyzerAsync(@" using System.ComponentModel; public class Person : INotifyPropertyChanged { private string name; public event PropertyChangedEventHandler PropertyChanged; public string PersonName { get { return name; } set { name = value; OnPropertyChanged(""PersonName""); } } protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } }", GetCSharpNameofResultAt(14, 31, "PersonName")); } [Fact] public async Task Diagnostic_ArgumentMatchesAPropertyInScope2() { await VerifyCS.VerifyAnalyzerAsync(@" using System.ComponentModel; public class Person : INotifyPropertyChanged { private string name; public event PropertyChangedEventHandler PropertyChanged; public string PersonName { get { return name; } set { name = value; OnPropertyChanged(""PersonName""); } } public string PersonName2 { get { return name; } set { name = value; OnPropertyChanged(nameof(PersonName2)); } } protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } }", GetCSharpNameofResultAt(15, 31, "PersonName")); } [Fact] public async Task Diagnostic_ArgumentNameColonParamName() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class C { void M(int x) { throw new ArgumentNullException(paramName:""x""); } }", GetCSharpNameofResultAt(7, 51, "x")); } [Fact] public async Task Diagnostic_ArgumentNameColonPropertyName() { await VerifyCS.VerifyAnalyzerAsync(@" using System.ComponentModel; public class Person : INotifyPropertyChanged { private string name; public event PropertyChangedEventHandler PropertyChanged; public string PersonName { get { return name; } set { name = value; OnPropertyChanged(propertyName:""PersonName""); } } protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } }", GetCSharpNameofResultAt(14, 44, "PersonName")); } [Fact] public async Task Diagnostic_AnonymousFunctionMultiline1() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Test { void Method(int x) { Action<int> a = (int y) => { throw new ArgumentException(""somemessage"", ""x""); }; } }", GetCSharpNameofResultAt(10, 56, "x")); } [Fact] public async Task Diagnostic_AnonymousFunctionMultiLine2() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Test { void Method(int x) { Action<int> a = (int y) => { throw new ArgumentException(""somemessage"", ""y""); }; } }", GetCSharpNameofResultAt(10, 56, "y")); } [Fact] public async Task Diagnostic_AnonymousFunctionSingleLine1() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Test { void Method(int x) { Action<int> a = (int y) => throw new ArgumentException(""somemessage"", ""y""); } }", GetCSharpNameofResultAt(8, 79, "y")); } [Fact] public async Task Diagnostic_AnonymousFunctionSingleLine2() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Test { void Method(int x) { Action<int> a = (int y) => throw new ArgumentException(""somemessage"", ""x""); } }", GetCSharpNameofResultAt(8, 79, "x")); } [Fact] public async Task Diagnostic_AnonymousFunctionMultipleParameters() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Test { void Method(int x) { Action<int, int> a = (j, k) => throw new ArgumentException(""somemessage"", ""x""); } }", GetCSharpNameofResultAt(8, 83, "x")); } [Fact] public async Task Diagnostic_LocalFunction1() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Test { void Method(int x) { void AnotherMethod(int y, int z) { throw new ArgumentException(""somemessage"", ""x""); } } }", GetCSharpNameofResultAt(10, 60, "x")); } [Fact] public async Task Diagnostic_LocalFunction2() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Test { void Method(int x) { void AnotherMethod(int y, int z) { throw new ArgumentException(""somemessage"", ""y""); } } }", GetCSharpNameofResultAt(10, 60, "y")); } [Fact] public async Task Diagnostic_Delegate() { await VerifyCS.VerifyAnalyzerAsync(@" using System; namespace ConsoleApp14 { class Program { class test { Action<int> x2 = delegate (int xyz) { throw new ArgumentNullException(""xyz""); }; } } }", GetCSharpNameofResultAt(12, 49, "xyz")); } #endregion private static DiagnosticResult GetBasicNameofResultAt(int line, int column, string name) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(name); private static DiagnosticResult GetCSharpNameofResultAt(int line, int column, string name) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(name); } }
// 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 { using System; using System.Reflection; using System.Runtime; using System.Threading; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; [Serializable] [ClassInterface(ClassInterfaceType.AutoDual)] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Delegate : ICloneable, ISerializable { // _target is the object we will invoke on [System.Security.SecurityCritical] internal Object _target; // MethodBase, either cached after first request or assigned from a DynamicMethod // For open delegates to collectible types, this may be a LoaderAllocator object [System.Security.SecurityCritical] internal Object _methodBase; // _methodPtr is a pointer to the method we will invoke // It could be a small thunk if this is a static or UM call [System.Security.SecurityCritical] internal IntPtr _methodPtr; // In the case of a static method passed to a delegate, this field stores // whatever _methodPtr would have stored: and _methodPtr points to a // small thunk which removes the "this" pointer before going on // to _methodPtrAux. [System.Security.SecurityCritical] internal IntPtr _methodPtrAux; // This constructor is called from the class generated by the // compiler generated code [System.Security.SecuritySafeCritical] // auto-generated protected Delegate(Object target,String method) { if (target == null) throw new ArgumentNullException("target"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodName to // such and don't allow relaxed signature matching (which could make // the choice of target method ambiguous) for backwards // compatibility. The name matching was case sensitive and we // preserve that as well. if (!BindToMethodName(target, (RuntimeType)target.GetType(), method, DelegateBindingFlags.InstanceMethodOnly | DelegateBindingFlags.ClosedDelegateOnly)) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); } // This constructor is called from a class to generate a // delegate based upon a static method name and the Type object // for the class defining the method. [System.Security.SecuritySafeCritical] // auto-generated protected unsafe Delegate(Type target,String method) { if (target == null) throw new ArgumentNullException("target"); if (target.IsGenericType && target.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), "target"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeType rtTarget = target as RuntimeType; if (rtTarget == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "target"); // This API existed in v1/v1.1 and only expected to create open // static delegates. Constrain the call to BindToMethodName to such // and don't allow relaxed signature matching (which could make the // choice of target method ambiguous) for backwards compatibility. // The name matching was case insensitive (no idea why this is // different from the constructor above) and we preserve that as // well. BindToMethodName(null, rtTarget, method, DelegateBindingFlags.StaticMethodOnly | DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.CaselessMatching); } // Protect the default constructor so you can't build a delegate private Delegate() { } public Object DynamicInvoke(params Object[] args) { // Theoretically we should set up a LookForMyCaller stack mark here and pass that along. // But to maintain backward compatibility we can't switch to calling an // internal overload of DynamicInvokeImpl that takes a stack mark. // Fortunately the stack walker skips all the reflection invocation frames including this one. // So this method will never be returned by the stack walker as the caller. // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp. return DynamicInvokeImpl(args); } [System.Security.SecuritySafeCritical] // auto-generated protected virtual object DynamicInvokeImpl(object[] args) { RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod()); RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method); return invoke.UnsafeInvoke(this, BindingFlags.Default, null, args, null); } [System.Security.SecuritySafeCritical] // auto-generated public override bool Equals(Object obj) { if (obj == null || !InternalEqualTypes(this, obj)) return false; Delegate d = (Delegate) obj; // do an optimistic check first. This is hopefully cheap enough to be worth if (_target == d._target && _methodPtr == d._methodPtr && _methodPtrAux == d._methodPtrAux) return true; // even though the fields were not all equals the delegates may still match // When target carries the delegate itself the 2 targets (delegates) may be different instances // but the delegates are logically the same // It may also happen that the method pointer was not jitted when creating one delegate and jitted in the other // if that's the case the delegates may still be equals but we need to make a more complicated check if (_methodPtrAux.IsNull()) { if (!d._methodPtrAux.IsNull()) return false; // different delegate kind // they are both closed over the first arg if (_target != d._target) return false; // fall through method handle check } else { if (d._methodPtrAux.IsNull()) return false; // different delegate kind // Ignore the target as it will be the delegate instance, though it may be a different one /* if (_methodPtr != d._methodPtr) return false; */ if (_methodPtrAux == d._methodPtrAux) return true; // fall through method handle check } // method ptrs don't match, go down long path // if (_methodBase == null || d._methodBase == null || !(_methodBase is MethodInfo) || !(d._methodBase is MethodInfo)) return Delegate.InternalEqualMethodHandles(this, d); else return _methodBase.Equals(d._methodBase); } public override int GetHashCode() { // // this is not right in the face of a method being jitted in one delegate and not in another // in that case the delegate is the same and Equals will return true but GetHashCode returns a // different hashcode which is not true. /* if (_methodPtrAux.IsNull()) return unchecked((int)((long)this._methodPtr)); else return unchecked((int)((long)this._methodPtrAux)); */ return GetType().GetHashCode(); } public static Delegate Combine(Delegate a, Delegate b) { if ((Object)a == null) // cast to object for a more efficient test return b; return a.CombineImpl(b); } [System.Runtime.InteropServices.ComVisible(true)] public static Delegate Combine(params Delegate[] delegates) { if (delegates == null || delegates.Length == 0) return null; Delegate d = delegates[0]; for (int i = 1; i < delegates.Length; i++) d = Combine(d,delegates[i]); return d; } public virtual Delegate[] GetInvocationList() { Delegate[] d = new Delegate[1]; d[0] = this; return d; } // This routine will return the method public MethodInfo Method { get { return GetMethodImpl(); } } [System.Security.SecuritySafeCritical] // auto-generated protected virtual MethodInfo GetMethodImpl() { if ((_methodBase == null) || !(_methodBase is MethodInfo)) { IRuntimeMethodInfo method = FindMethodHandle(); RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method); // need a proper declaring type instance method on a generic type if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType)) { bool isStatic = (RuntimeMethodHandle.GetAttributes(method) & MethodAttributes.Static) != (MethodAttributes)0; if (!isStatic) { if (_methodPtrAux == (IntPtr)0) { // The target may be of a derived type that doesn't have visibility onto the // target method. We don't want to call RuntimeType.GetMethodBase below with that // or reflection can end up generating a MethodInfo where the ReflectedType cannot // see the MethodInfo itself and that breaks an important invariant. But the // target type could include important generic type information we need in order // to work out what the exact instantiation of the method's declaring type is. So // we'll walk up the inheritance chain (which will yield exactly instantiated // types at each step) until we find the declaring type. Since the declaring type // we get from the method is probably shared and those in the hierarchy we're // walking won't be we compare using the generic type definition forms instead. Type currentType = _target.GetType(); Type targetType = declaringType.GetGenericTypeDefinition(); while (currentType != null) { if (currentType.IsGenericType && currentType.GetGenericTypeDefinition() == targetType) { declaringType = currentType as RuntimeType; break; } currentType = currentType.BaseType; } // RCWs don't need to be "strongly-typed" in which case we don't find a base type // that matches the declaring type of the method. This is fine because interop needs // to work with exact methods anyway so declaringType is never shared at this point. BCLDebug.Assert(currentType != null || _target.GetType().IsCOMObject, "The class hierarchy should declare the method"); } else { // it's an open one, need to fetch the first arg of the instantiation MethodInfo invoke = this.GetType().GetMethod("Invoke"); declaringType = (RuntimeType)invoke.GetParameters()[0].ParameterType; } } } _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method); } return (MethodInfo)_methodBase; } public Object Target { get { return GetTarget(); } } [System.Security.SecuritySafeCritical] // auto-generated public static Delegate Remove(Delegate source, Delegate value) { if (source == null) return null; if (value == null) return source; if (!InternalEqualTypes(source, value)) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTypeMis")); return source.RemoveImpl(value); } public static Delegate RemoveAll(Delegate source, Delegate value) { Delegate newDelegate = null; do { newDelegate = source; source = Remove(source, value); } while (newDelegate != source); return newDelegate; } protected virtual Delegate CombineImpl(Delegate d) { throw new MulticastNotSupportedException(Environment.GetResourceString("Multicast_Combine")); } protected virtual Delegate RemoveImpl(Delegate d) { return (d.Equals(this)) ? null : this; } public virtual Object Clone() { return MemberwiseClone(); } // V1 API. public static Delegate CreateDelegate(Type type, Object target, String method) { return CreateDelegate(type, target, method, false, true); } // V1 API. public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase) { return CreateDelegate(type, target, method, ignoreCase, true); } // V1 API. [System.Security.SecuritySafeCritical] // auto-generated public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase, bool throwOnBindFailure) { if (type == null) throw new ArgumentNullException("type"); if (target == null) throw new ArgumentNullException("target"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type"); Delegate d = InternalAlloc(rtType); // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodName to such // and don't allow relaxed signature matching (which could make the // choice of target method ambiguous) for backwards compatibility. // We never generate a closed over null delegate and this is // actually enforced via the check on target above, but we pass // NeverCloseOverNull anyway just for clarity. if (!d.BindToMethodName(target, (RuntimeType)target.GetType(), method, DelegateBindingFlags.InstanceMethodOnly | DelegateBindingFlags.ClosedDelegateOnly | DelegateBindingFlags.NeverCloseOverNull | (ignoreCase ? DelegateBindingFlags.CaselessMatching : 0))) { if (throwOnBindFailure) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); d = null; } return d; } // V1 API. public static Delegate CreateDelegate(Type type, Type target, String method) { return CreateDelegate(type, target, method, false, true); } // V1 API. public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase) { return CreateDelegate(type, target, method, ignoreCase, true); } // V1 API. [System.Security.SecuritySafeCritical] // auto-generated public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase, bool throwOnBindFailure) { if (type == null) throw new ArgumentNullException("type"); if (target == null) throw new ArgumentNullException("target"); if (target.IsGenericType && target.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), "target"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; RuntimeType rtTarget = target as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type"); if (rtTarget == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "target"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type"); Delegate d = InternalAlloc(rtType); // This API existed in v1/v1.1 and only expected to create open // static delegates. Constrain the call to BindToMethodName to such // and don't allow relaxed signature matching (which could make the // choice of target method ambiguous) for backwards compatibility. if (!d.BindToMethodName(null, rtTarget, method, DelegateBindingFlags.StaticMethodOnly | DelegateBindingFlags.OpenDelegateOnly | (ignoreCase ? DelegateBindingFlags.CaselessMatching : 0))) { if (throwOnBindFailure) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); d = null; } return d; } // V1 API. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure) { // Validate the parameters. if (type == null) throw new ArgumentNullException("type"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type"); RuntimeMethodInfo rmi = method as RuntimeMethodInfo; if (rmi == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "method"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "type"); // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodInfo to // open delegates only for backwards compatibility. But we'll allow // relaxed signature checking and open static delegates because // there's no ambiguity there (the caller would have to explicitly // pass us a static method or a method with a non-exact signature // and the only change in behavior from v1.1 there is that we won't // fail the call). StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; Delegate d = CreateDelegateInternal( rtType, rmi, null, DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature, ref stackMark); if (d == null && throwOnBindFailure) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); return d; } // V2 API. public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method) { return CreateDelegate(type, firstArgument, method, true); } // V2 API. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure) { // Validate the parameters. if (type == null) throw new ArgumentNullException("type"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type"); RuntimeMethodInfo rmi = method as RuntimeMethodInfo; if (rmi == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "method"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "type"); // This API is new in Whidbey and allows the full range of delegate // flexability (open or closed delegates binding to static or // instance methods with relaxed signature checking. The delegate // can also be closed over null. There's no ambiguity with all these // options since the caller is providing us a specific MethodInfo. StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; Delegate d = CreateDelegateInternal( rtType, rmi, firstArgument, DelegateBindingFlags.RelaxedSignature, ref stackMark); if (d == null && throwOnBindFailure) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); return d; } public static bool operator ==(Delegate d1, Delegate d2) { if ((Object)d1 == null) return (Object)d2 == null; return d1.Equals(d2); } public static bool operator != (Delegate d1, Delegate d2) { if ((Object)d1 == null) return (Object)d2 != null; return !d1.Equals(d2); } // // Implementation of ISerializable // [System.Security.SecurityCritical] public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(); } // // internal implementation details (FCALLS and utilities) // // V2 internal API. // This is Critical because it skips the security check when creating the delegate. [System.Security.SecurityCritical] // auto-generated internal unsafe static Delegate CreateDelegateNoSecurityCheck(Type type, Object target, RuntimeMethodHandle method) { // Validate the parameters. if (type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); if (method.IsNullHandle()) throw new ArgumentNullException("method"); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type"); // Initialize the method... Delegate d = InternalAlloc(rtType); // This is a new internal API added in Whidbey. Currently it's only // used by the dynamic method code to generate a wrapper delegate. // Allow flexible binding options since the target method is // unambiguously provided to us. if (!d.BindToMethodInfo(target, method.GetMethodInfo(), RuntimeMethodHandle.GetDeclaringType(method.GetMethodInfo()), DelegateBindingFlags.RelaxedSignature | DelegateBindingFlags.SkipSecurityChecks)) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); return d; } // Caution: this method is intended for deserialization only, no security checks are performed. [System.Security.SecurityCritical] // auto-generated internal static Delegate CreateDelegateNoSecurityCheck(RuntimeType type, Object firstArgument, MethodInfo method) { // Validate the parameters. if (type == null) throw new ArgumentNullException("type"); if (method == null) throw new ArgumentNullException("method"); Contract.EndContractBlock(); RuntimeMethodInfo rtMethod = method as RuntimeMethodInfo; if (rtMethod == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "method"); if (!type.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type"); // This API is used by the formatters when deserializing a delegate. // They pass us the specific target method (that was already the // target in a valid delegate) so we should bind with the most // relaxed rules available (the result will never be ambiguous, it // just increases the chance of success with minor (compatible) // signature changes). We explicitly skip security checks here -- // we're not really constructing a delegate, we're cloning an // existing instance which already passed its checks. Delegate d = UnsafeCreateDelegate(type, rtMethod, firstArgument, DelegateBindingFlags.SkipSecurityChecks | DelegateBindingFlags.RelaxedSignature); if (d == null) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); return d; } // V1 API. public static Delegate CreateDelegate(Type type, MethodInfo method) { return CreateDelegate(type, method, true); } [System.Security.SecuritySafeCritical] internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags, ref StackCrawlMark stackMark) { Contract.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0); #if FEATURE_APPX bool nonW8PMethod = (rtMethod.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0; bool nonW8PType = (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0; if (nonW8PMethod || nonW8PType) { RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException( Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", nonW8PMethod ? rtMethod.FullName : rtType.FullName)); } #endif return UnsafeCreateDelegate(rtType, rtMethod, firstArgument, flags); } [System.Security.SecurityCritical] internal static Delegate UnsafeCreateDelegate(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags) { Delegate d = InternalAlloc(rtType); if (d.BindToMethodInfo(firstArgument, rtMethod, rtMethod.GetDeclaringTypeInternal(), flags)) return d; else return null; } // // internal implementation details (FCALLS and utilities) // [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool BindToMethodName(Object target, RuntimeType methodType, String method, DelegateBindingFlags flags); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static MulticastDelegate InternalAlloc(RuntimeType type); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static MulticastDelegate InternalAllocLike(Delegate d); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool InternalEqualTypes(object a, object b); // Used by the ctor. Do not call directly. // The name of this function will appear in managed stacktraces as delegate constructor. [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern void DelegateConstruct(Object target, IntPtr slot); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern IntPtr GetMulticastInvoke(); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern IntPtr GetInvokeMethod(); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern IRuntimeMethodInfo FindMethodHandle(); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool InternalEqualMethodHandles(Delegate left, Delegate right); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern IntPtr AdjustTarget(Object target, IntPtr methodPtr); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern IntPtr GetCallStub(IntPtr methodPtr); [System.Security.SecuritySafeCritical] internal virtual Object GetTarget() { return (_methodPtrAux.IsNull()) ? _target : null; } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool CompareUnmanagedFunctionPtrs (Delegate d1, Delegate d2); } // These flags effect the way BindToMethodInfo and BindToMethodName are allowed to bind a delegate to a target method. Their // values must be kept in sync with the definition in vm\comdelegate.h. internal enum DelegateBindingFlags { StaticMethodOnly = 0x00000001, // Can only bind to static target methods InstanceMethodOnly = 0x00000002, // Can only bind to instance (including virtual) methods OpenDelegateOnly = 0x00000004, // Only allow the creation of delegates open over the 1st argument ClosedDelegateOnly = 0x00000008, // Only allow the creation of delegates closed over the 1st argument NeverCloseOverNull = 0x00000010, // A null target will never been considered as a possible null 1st argument CaselessMatching = 0x00000020, // Use case insensitive lookup for methods matched by name SkipSecurityChecks = 0x00000040, // Skip security checks (visibility, link demand etc.) RelaxedSignature = 0x00000080, // Allow relaxed signature matching (co/contra variance) } }
/* * 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; using System.Collections.Generic; using System.Reflection; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Interfaces; using log4net; 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.Yengine { /// <summary> /// Prepares events so they can be directly executed upon a script by EventQueueManager, then queues it. /// </summary> public partial class Yengine { public static readonly object[] zeroObjectArray = new object[0]; public static readonly object[] oneObjectArrayOne = new object[1] { 1 }; private void InitEvents() { m_log.Info("[YEngine] Hooking up to server events"); this.World.EventManager.OnAttach += attach; this.World.EventManager.OnObjectGrab += touch_start; this.World.EventManager.OnObjectGrabbing += touch; this.World.EventManager.OnObjectDeGrab += touch_end; this.World.EventManager.OnScriptChangedEvent += changed; this.World.EventManager.OnScriptAtTargetEvent += at_target; this.World.EventManager.OnScriptNotAtTargetEvent += not_at_target; this.World.EventManager.OnScriptAtRotTargetEvent += at_rot_target; this.World.EventManager.OnScriptNotAtRotTargetEvent += not_at_rot_target; this.World.EventManager.OnScriptMovingStartEvent += moving_start; this.World.EventManager.OnScriptMovingEndEvent += moving_end; this.World.EventManager.OnScriptControlEvent += control; this.World.EventManager.OnScriptColliderStart += collision_start; this.World.EventManager.OnScriptColliding += collision; this.World.EventManager.OnScriptCollidingEnd += collision_end; this.World.EventManager.OnScriptLandColliderStart += land_collision_start; this.World.EventManager.OnScriptLandColliding += land_collision; this.World.EventManager.OnScriptLandColliderEnd += land_collision_end; IMoneyModule money = this.World.RequestModuleInterface<IMoneyModule>(); if(money != null) { money.OnObjectPaid += HandleObjectPaid; } } /// <summary> /// When an object gets paid by an avatar and generates the paid event, /// this will pipe it to the script engine /// </summary> /// <param name="objectID">Object ID that got paid</param> /// <param name="agentID">Agent Id that did the paying</param> /// <param name="amount">Amount paid</param> private void HandleObjectPaid(UUID objectID, UUID agentID, int amount) { // Add to queue for all scripts in ObjectID object DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = agentID; det[0].Populate(this.World); // Since this is an event from a shared module, all scenes will // get it. But only one has the object in question. The others // just ignore it. // SceneObjectPart part = this.World.GetSceneObjectPart(objectID); if(part == null) return; if((part.ScriptEvents & scriptEvents.money) == 0) part = part.ParentGroup.RootPart; Verbose("Paid: " + objectID + " from " + agentID + ", amount " + amount); if(part != null) { money(part.LocalId, agentID, amount, det); } } /// <summary> /// Handles piping the proper stuff to The script engine for touching /// Including DetectedParams /// </summary> /// <param name="localID"></param> /// <param name="originalID"></param> /// <param name="offsetPos"></param> /// <param name="remoteClient"></param> /// <param name="surfaceArgs"></param> public void touch_start(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { touches(localID, originalID, offsetPos, remoteClient, surfaceArgs, "touch_start"); } public void touch(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { touches(localID, originalID, offsetPos, remoteClient, surfaceArgs, "touch"); } private static Vector3 zeroVec3 = new Vector3(0, 0, 0); public void touch_end(uint localID, uint originalID, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { touches(localID, originalID, zeroVec3, remoteClient, surfaceArgs, "touch_end"); } private void touches(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs, string eventname) { SceneObjectPart part; if(originalID == 0) { part = this.World.GetSceneObjectPart(localID); if(part == null) return; } else { part = this.World.GetSceneObjectPart(originalID); } DetectParams det = new DetectParams(); det.Key = remoteClient.AgentId; det.Populate(this.World); det.OffsetPos = new LSL_Vector(offsetPos.X, offsetPos.Y, offsetPos.Z); det.LinkNum = part.LinkNum; if(surfaceArgs != null) { det.SurfaceTouchArgs = surfaceArgs; } // Add to queue for all scripts in ObjectID object this.PostObjectEvent(localID, new EventParams( eventname, oneObjectArrayOne, new DetectParams[] { det })); } public void changed(uint localID, uint change) { int ch = (int)change; // Add to queue for all scripts in localID, Object pass change. this.PostObjectEvent(localID, new EventParams( "changed", new object[] { ch }, zeroDetectParams)); } // state_entry: not processed here // state_exit: not processed here public void money(uint localID, UUID agentID, int amount, DetectParams[] det) { this.PostObjectEvent(localID, new EventParams( "money", new object[] { agentID.ToString(), amount }, det)); } public void collision_start(uint localID, ColliderArgs col) { collisions(localID, col, "collision_start"); } public void collision(uint localID, ColliderArgs col) { collisions(localID, col, "collision"); } public void collision_end(uint localID, ColliderArgs col) { collisions(localID, col, "collision_end"); } private void collisions(uint localID, ColliderArgs col, string eventname) { int dc = col.Colliders.Count; if(dc > 0) { DetectParams[] det = new DetectParams[dc]; int i = 0; foreach(DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); det[i++] = d; d.Key = detobj.keyUUID; d.Populate(this.World); /* not done by XEngine... d.Position = detobj.posVector; d.Rotation = detobj.rotQuat; d.Velocity = detobj.velVector; ... */ } this.PostObjectEvent(localID, new EventParams( eventname, new Object[] { dc }, det)); } } public void land_collision_start(uint localID, ColliderArgs col) { land_collisions(localID, col, "land_collision_start"); } public void land_collision(uint localID, ColliderArgs col) { land_collisions(localID, col, "land_collision"); } public void land_collision_end(uint localID, ColliderArgs col) { land_collisions(localID, col, "land_collision_end"); } private void land_collisions(uint localID, ColliderArgs col, string eventname) { foreach(DetectedObject detobj in col.Colliders) { LSL_Vector vec = new LSL_Vector(detobj.posVector.X, detobj.posVector.Y, detobj.posVector.Z); EventParams eps = new EventParams(eventname, new Object[] { vec }, zeroDetectParams); this.PostObjectEvent(localID, eps); } } // timer: not handled here // listen: not handled here public void control(UUID itemID, UUID agentID, uint held, uint change) { this.PostScriptEvent(itemID, new EventParams( "control", new object[] { agentID.ToString(), (int)held, (int)change}, zeroDetectParams)); } public void email(uint localID, UUID itemID, string timeSent, string address, string subject, string message, int numLeft) { this.PostObjectEvent(localID, new EventParams( "email", new object[] { timeSent, address, subject, message, numLeft}, zeroDetectParams)); } public void at_target(uint localID, uint handle, Vector3 targetpos, Vector3 atpos) { this.PostObjectEvent(localID, new EventParams( "at_target", new object[] { (int)handle, new LSL_Vector(targetpos.X,targetpos.Y,targetpos.Z), new LSL_Vector(atpos.X,atpos.Y,atpos.Z) }, zeroDetectParams)); } public void not_at_target(uint localID) { this.PostObjectEvent(localID, new EventParams( "not_at_target", zeroObjectArray, zeroDetectParams)); } public void at_rot_target(uint localID, uint handle, OpenMetaverse.Quaternion targetrot, OpenMetaverse.Quaternion atrot) { this.PostObjectEvent( localID, new EventParams( "at_rot_target", new object[] { new LSL_Integer(handle), new LSL_Rotation(targetrot.X, targetrot.Y, targetrot.Z, targetrot.W), new LSL_Rotation(atrot.X, atrot.Y, atrot.Z, atrot.W) }, zeroDetectParams ) ); } public void not_at_rot_target(uint localID) { this.PostObjectEvent(localID, new EventParams( "not_at_rot_target", zeroObjectArray, zeroDetectParams)); } // run_time_permissions: not handled here public void attach(uint localID, UUID itemID, UUID avatar) { this.PostObjectEvent(localID, new EventParams( "attach", new object[] { avatar.ToString() }, zeroDetectParams)); } // dataserver: not handled here // link_message: not handled here public void moving_start(uint localID) { this.PostObjectEvent(localID, new EventParams( "moving_start", zeroObjectArray, zeroDetectParams)); } public void moving_end(uint localID) { this.PostObjectEvent(localID, new EventParams( "moving_end", zeroObjectArray, zeroDetectParams)); } // object_rez: not handled here // remote_data: not handled here // http_response: not handled here } }
// 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.Xml; using System.ServiceModel.Channels; using System.Collections.Generic; using System.Collections.ObjectModel; namespace System.ServiceModel.Security { public class MessagePartSpecification { private List<XmlQualifiedName> _headerTypes; private bool _isBodyIncluded; private bool _isReadOnly; private static MessagePartSpecification s_noParts; public ICollection<XmlQualifiedName> HeaderTypes { get { if (_headerTypes == null) { _headerTypes = new List<XmlQualifiedName>(); } if (_isReadOnly) { return new ReadOnlyCollection<XmlQualifiedName>(_headerTypes); } else { return _headerTypes; } } } internal bool HasHeaders { get { return _headerTypes != null && _headerTypes.Count > 0; } } public bool IsBodyIncluded { get { return _isBodyIncluded; } set { if (_isReadOnly) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly)); _isBodyIncluded = value; } } public bool IsReadOnly { get { return _isReadOnly; } } static public MessagePartSpecification NoParts { get { if (s_noParts == null) { MessagePartSpecification parts = new MessagePartSpecification(); parts.MakeReadOnly(); s_noParts = parts; } return s_noParts; } } public void Clear() { if (_isReadOnly) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly)); if (_headerTypes != null) _headerTypes.Clear(); _isBodyIncluded = false; } public void Union(MessagePartSpecification specification) { if (_isReadOnly) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly)); if (specification == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("specification"); _isBodyIncluded |= specification.IsBodyIncluded; List<XmlQualifiedName> headerTypes = specification._headerTypes; if (headerTypes != null && headerTypes.Count > 0) { if (_headerTypes == null) { _headerTypes = new List<XmlQualifiedName>(headerTypes.Count); } for (int i = 0; i < headerTypes.Count; i++) { XmlQualifiedName qname = headerTypes[i]; _headerTypes.Add(qname); } } } public void MakeReadOnly() { if (_isReadOnly) return; if (_headerTypes != null) { List<XmlQualifiedName> noDuplicates = new List<XmlQualifiedName>(_headerTypes.Count); for (int i = 0; i < _headerTypes.Count; i++) { XmlQualifiedName qname = _headerTypes[i]; if (qname != null) { bool include = true; for (int j = 0; j < noDuplicates.Count; j++) { XmlQualifiedName qname1 = noDuplicates[j]; if (qname.Name == qname1.Name && qname.Namespace == qname1.Namespace) { include = false; break; } } if (include) noDuplicates.Add(qname); } } _headerTypes = noDuplicates; } _isReadOnly = true; } public MessagePartSpecification() { // empty } public MessagePartSpecification(bool isBodyIncluded) { _isBodyIncluded = isBodyIncluded; } public MessagePartSpecification(params XmlQualifiedName[] headerTypes) : this(false, headerTypes) { // empty } public MessagePartSpecification(bool isBodyIncluded, params XmlQualifiedName[] headerTypes) { _isBodyIncluded = isBodyIncluded; if (headerTypes != null && headerTypes.Length > 0) { _headerTypes = new List<XmlQualifiedName>(headerTypes.Length); for (int i = 0; i < headerTypes.Length; i++) { _headerTypes.Add(headerTypes[i]); } } } internal bool IsHeaderIncluded(MessageHeader header) { if (header == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("header"); return IsHeaderIncluded(header.Name, header.Namespace); } internal bool IsHeaderIncluded(string name, string ns) { if (name == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name"); if (ns == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns"); if (_headerTypes != null) { for (int i = 0; i < _headerTypes.Count; i++) { XmlQualifiedName qname = _headerTypes[i]; // Name is an optional attribute. If not present, compare with only the namespace. if (String.IsNullOrEmpty(qname.Name)) { if (qname.Namespace == ns) { return true; } } else { if (qname.Name == name && qname.Namespace == ns) { return true; } } } } return false; } internal bool IsEmpty() { if (_headerTypes != null && _headerTypes.Count > 0) return false; return !this.IsBodyIncluded; } } }
namespace PCLMock.CodeGeneration.Plugins { using System; using Logging; using Microsoft.CodeAnalysis; /// <summary> /// A plugin that generates appropriate default return values for any member that returns a collection. /// </summary> /// <remarks> /// <para> /// This plugin generates return specifications for any member returning a standard collection type. That is, /// it returns <c>IEnumerable&lt;T&gt;</c>, <c>ICollection&lt;T&gt;</c>, <c>IReadOnlyCollection&lt;T&gt;</c>, /// <c>IList&lt;T&gt;</c>, <c>IReadOnlyList&lt;T&gt;</c>, <c>IDictionary&lt;TKey, TValue&gt;</c>, /// <c>IReadOnlyDictionary&lt;TKey, TValue&gt;</c>, <c>ISet&lt;T&gt;</c> <c>IImmutableList&lt;T&gt;</c>, /// <c>IImmutableDictionary&lt;TKey, TValue&gt;</c>, <c>IImmutableQueue&lt;T&gt;</c>, /// <c>IImmutableSet&lt;T&gt;</c>, or <c>IImmutableStack&lt;T&gt;</c>. /// </para> /// <para> /// The generated specification simply returns a default instance of an appropriate type. This has the /// (usually desirable) effect of ensuring any collection-like member returns an empty collection by default /// rather than <see langword="null"/>. /// </para> /// <para> /// Members for which specifications cannot be generated are ignored. This of course includes members that do not /// return collections, but also set-only properties, generic methods, and any members that return custom /// collection subtypes. /// </para> /// </remarks> public sealed class Collections : IPlugin { public string Name => "Collections"; /// <inheritdoc /> public Compilation InitializeCompilation(ILogSink logSink, Compilation compilation) => compilation; /// <inheritdoc /> public SyntaxNode GetDefaultValueSyntax( Context context, ISymbol symbol, ITypeSymbol typeSymbol) { context = context .WithLogSink( context .LogSink .WithSource(typeof(Collections))); if (!(typeSymbol is INamedTypeSymbol namedTypeSymbol)) { context .LogSink .Debug("Ignoring type '{0}' because it is not a named type symbol.", typeSymbol); return null; } if (!namedTypeSymbol.IsGenericType) { context .LogSink .Debug("Ignoring type '{0}' because its return type is not a generic type, so it cannot be one of the supported collection types.", namedTypeSymbol); return null; } SyntaxNode returnValueSyntax; if (!TryGetReturnValueSyntaxForEnumerableReturnType(context, namedTypeSymbol, out returnValueSyntax) && !TryGetReturnValueSyntaxForCollectionReturnType(context, namedTypeSymbol, out returnValueSyntax) && !TryGetReturnValueSyntaxForDictionaryReturnType(context, namedTypeSymbol, out returnValueSyntax) && !TryGetReturnValueSyntaxForSetReturnType(context, namedTypeSymbol, out returnValueSyntax) && !TryGetReturnValueSyntaxForImmutableListReturnType(context, namedTypeSymbol, out returnValueSyntax) && !TryGetReturnValueSyntaxForImmutableDictionaryReturnType(context, namedTypeSymbol, out returnValueSyntax) && !TryGetReturnValueSyntaxForImmutableQueueReturnType(context, namedTypeSymbol, out returnValueSyntax) && !TryGetReturnValueSyntaxForImmutableSetReturnType(context, namedTypeSymbol, out returnValueSyntax) && !TryGetReturnValueSyntaxForImmutableStackReturnType(context, namedTypeSymbol, out returnValueSyntax)) { context .LogSink .Debug("Type '{0}' is not a supported collection type.", namedTypeSymbol); return null; } context .LogSink .Debug("Generated a default value for type '{0}'.", namedTypeSymbol); return returnValueSyntax; } private static bool TryGetReturnValueSyntaxForEnumerableReturnType( Context context, INamedTypeSymbol typeSymbol, out SyntaxNode returnValueSyntax) { var isEnumerable = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Generic.IEnumerable<T>"; if (!isEnumerable) { returnValueSyntax = null; return false; } var enumerableType = context .SemanticModel .Compilation .GetPreferredTypeByMetadataName("System.Linq.Enumerable", preferredAssemblyNames: new[] { "System.Linq" }); if (enumerableType == null) { context .LogSink .Warn("The Enumerable type could not be resolved (probably a missing reference to System.Linq)."); returnValueSyntax = null; return false; } returnValueSyntax = context .SyntaxGenerator .InvocationExpression( context .SyntaxGenerator .WithTypeArguments( context .SyntaxGenerator .MemberAccessExpression( context .SyntaxGenerator .TypeExpression(enumerableType), "Empty"), context .SyntaxGenerator .TypeExpression(typeSymbol.TypeArguments[0]))); return true; } private static bool TryGetReturnValueSyntaxForCollectionReturnType( Context context, INamedTypeSymbol typeSymbol, out SyntaxNode returnValueSyntax) { var isCollection = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Generic.ICollection<T>"; var isReadOnlyCollection = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Generic.IReadOnlyCollection<T>"; var isList = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Generic.IList<T>"; var isReadOnlyList = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Generic.IReadOnlyList<T>"; if (!(isCollection || isReadOnlyCollection || isList || isReadOnlyList)) { returnValueSyntax = null; return false; } var listType = context .SemanticModel .Compilation .GetPreferredTypeByMetadataName("System.Collections.Generic.List`1", preferredAssemblyNames: new[] { "System.Collections" }); if (listType == null) { context .LogSink .Warn("The List type could not be resolved (probably a missing reference to System.Collections)."); returnValueSyntax = null; return false; } returnValueSyntax = context .SyntaxGenerator .ObjectCreationExpression( listType.Construct(typeSymbol.TypeArguments[0])).NormalizeWhitespace(); return true; } private static bool TryGetReturnValueSyntaxForDictionaryReturnType( Context context, INamedTypeSymbol typeSymbol, out SyntaxNode returnValueSyntax) { var isDictionary = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Generic.IDictionary<TKey, TValue>"; var isReadOnlyDictionary = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>"; if (!(isDictionary || isReadOnlyDictionary)) { returnValueSyntax = null; return false; } var dictionaryType = context .SemanticModel .Compilation .GetPreferredTypeByMetadataName("System.Collections.Generic.Dictionary`2", preferredAssemblyNames: new[] { "System.Collections" }); if (dictionaryType == null) { context .LogSink .Warn("The Dictionary type could not be resolved (probably a missing reference to System.Collections)."); returnValueSyntax = null; return false; } returnValueSyntax = context .SyntaxGenerator .ObjectCreationExpression( dictionaryType.Construct(typeSymbol.TypeArguments[0], typeSymbol.TypeArguments[1])).NormalizeWhitespace(); return true; } private static bool TryGetReturnValueSyntaxForSetReturnType( Context context, INamedTypeSymbol typeSymbol, out SyntaxNode returnValueSyntax) { var isSet = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Generic.ISet<T>"; if (!isSet) { returnValueSyntax = null; return false; } var hashSetType = context .SemanticModel .Compilation .GetPreferredTypeByMetadataName("System.Collections.Generic.HashSet`1", preferredAssemblyNames: new[] { "System.Collections" }); if (hashSetType == null) { context .LogSink .Warn("The HashSet type could not be resolved (probably a missing reference to System.Collections)."); returnValueSyntax = null; return false; } returnValueSyntax = context .SyntaxGenerator .ObjectCreationExpression( hashSetType.Construct(typeSymbol.TypeArguments[0])).NormalizeWhitespace(); return true; } private static bool TryGetReturnValueSyntaxForImmutableListReturnType( Context context, INamedTypeSymbol typeSymbol, out SyntaxNode returnValueSyntax) { var isImmutableList = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Immutable.IImmutableList<T>"; if (!isImmutableList) { returnValueSyntax = null; return false; } var immutableListType = context .SemanticModel .Compilation .GetPreferredTypeByMetadataName("System.Collections.Immutable.ImmutableList", preferredAssemblyNames: new[] { "System.Collections.Immutable" }); if (immutableListType == null) { context .LogSink .Warn("The ImmutableList type could not be resolved (probably a missing reference to System.Collections.Immutable)."); returnValueSyntax = null; return false; } returnValueSyntax = context .SyntaxGenerator .MemberAccessExpression( context .SyntaxGenerator .WithTypeArguments( context .SyntaxGenerator .TypeExpression(immutableListType), context .SyntaxGenerator .TypeExpression(typeSymbol.TypeArguments[0])), "Empty"); return true; } private static bool TryGetReturnValueSyntaxForImmutableDictionaryReturnType( Context context, INamedTypeSymbol typeSymbol, out SyntaxNode returnValueSyntax) { var isImmutableDictionary = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Immutable.IImmutableDictionary<TKey, TValue>"; if (!isImmutableDictionary) { returnValueSyntax = null; return false; } var immutableDictionaryType = context .SemanticModel .Compilation .GetPreferredTypeByMetadataName("System.Collections.Immutable.ImmutableDictionary", preferredAssemblyNames: new[] { "System.Collections.Immutable" }); if (immutableDictionaryType == null) { context .LogSink .Warn("The ImmutableDictionary type could not be resolved (probably a missing reference to System.Collections.Immutable)."); returnValueSyntax = null; return false; } returnValueSyntax = context .SyntaxGenerator .MemberAccessExpression( context .SyntaxGenerator .WithTypeArguments( context .SyntaxGenerator .TypeExpression(immutableDictionaryType), context .SyntaxGenerator .TypeExpression(typeSymbol.TypeArguments[0]), context .SyntaxGenerator .TypeExpression(typeSymbol.TypeArguments[1])), "Empty"); return true; } private static bool TryGetReturnValueSyntaxForImmutableQueueReturnType( Context context, INamedTypeSymbol typeSymbol, out SyntaxNode returnValueSyntax) { var isImmutableQueue = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Immutable.IImmutableQueue<T>"; if (!isImmutableQueue) { returnValueSyntax = null; return false; } var immutableQueueType = context .SemanticModel .Compilation .GetPreferredTypeByMetadataName("System.Collections.Immutable.ImmutableQueue", preferredAssemblyNames: new[] { "System.Collections.Immutable" }); if (immutableQueueType == null) { context .LogSink .Warn("The ImmutableDictionary type could not be resolved (probably a missing reference to System.Collections.Immutable)."); returnValueSyntax = null; return false; } returnValueSyntax = context .SyntaxGenerator .MemberAccessExpression( context .SyntaxGenerator .WithTypeArguments( context .SyntaxGenerator .TypeExpression(immutableQueueType), context .SyntaxGenerator .TypeExpression(typeSymbol.TypeArguments[0])), "Empty"); return true; } private static bool TryGetReturnValueSyntaxForImmutableSetReturnType( Context context, INamedTypeSymbol typeSymbol, out SyntaxNode returnValueSyntax) { var isImmutableSet = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Immutable.IImmutableSet<T>"; if (!isImmutableSet) { returnValueSyntax = null; return false; } var immutableHashSetType = context .SemanticModel .Compilation .GetPreferredTypeByMetadataName("System.Collections.Immutable.ImmutableHashSet", preferredAssemblyNames: new[] { "System.Collections.Immutable" }); if (immutableHashSetType == null) { context .LogSink .Warn("The ImmutableHashSet type could not be resolved (probably a missing reference to System.Collections.Immutable)."); returnValueSyntax = null; return false; } returnValueSyntax = context .SyntaxGenerator .MemberAccessExpression( context .SyntaxGenerator .WithTypeArguments( context .SyntaxGenerator .TypeExpression(immutableHashSetType), context .SyntaxGenerator .TypeExpression(typeSymbol.TypeArguments[0])), "Empty"); return true; } private static bool TryGetReturnValueSyntaxForImmutableStackReturnType( Context context, INamedTypeSymbol typeSymbol, out SyntaxNode returnValueSyntax) { var isImmutableStack = typeSymbol.ConstructedFrom?.ToDisplayString() == "System.Collections.Immutable.IImmutableStack<T>"; if (!isImmutableStack) { returnValueSyntax = null; return false; } var immutableStackType = context .SemanticModel .Compilation .GetPreferredTypeByMetadataName("System.Collections.Immutable.ImmutableStack", preferredAssemblyNames: new[] { "System.Collections.Immutable" }); if (immutableStackType == null) { context .LogSink .Warn("The ImmutableStack type could not be resolved (probably a missing reference to System.Collections.Immutable)."); returnValueSyntax = null; return false; } returnValueSyntax = context .SyntaxGenerator .MemberAccessExpression( context .SyntaxGenerator .WithTypeArguments( context .SyntaxGenerator .TypeExpression(immutableStackType), context .SyntaxGenerator .TypeExpression(typeSymbol.TypeArguments[0])), "Empty"); return true; } } }
// 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.Runtime; using System.Runtime.Serialization; using System.Reflection; using System.Xml; namespace System.Runtime.Serialization.Json { internal class JsonDataContract { private JsonDataContractCriticalHelper _helper; protected JsonDataContract(DataContract traditionalDataContract) { _helper = new JsonDataContractCriticalHelper(traditionalDataContract); } protected JsonDataContract(JsonDataContractCriticalHelper helper) { _helper = helper; } internal virtual string TypeName => null; protected JsonDataContractCriticalHelper Helper => _helper; protected DataContract TraditionalDataContract => _helper.TraditionalDataContract; private Dictionary<XmlQualifiedName, DataContract> KnownDataContracts => _helper.KnownDataContracts; public static JsonReadWriteDelegates GetGeneratedReadWriteDelegates(DataContract c) { // this method used to be rewritten by an IL transform // with the restructuring for multi-file, this is no longer true - instead // this has become a normal method JsonReadWriteDelegates result; #if uapaot // The c passed in could be a clone which is different from the original key, // We'll need to get the original key data contract from generated assembly. DataContract keyDc = (c?.UnderlyingType != null) ? DataContract.GetDataContractFromGeneratedAssembly(c.UnderlyingType) : null; return (keyDc != null && JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(keyDc, out result)) ? result : null; #else return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null; #endif } internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c); if (result == null) { throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType.ToString())); } else { return result; } } internal static JsonReadWriteDelegates TryGetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c); return result; } public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract); } public object ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { PushKnownDataContracts(context); object deserializedObject = ReadJsonValueCore(jsonReader, context); PopKnownDataContracts(context); return deserializedObject; } public virtual object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { return TraditionalDataContract.ReadXmlValue(jsonReader, context); } public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { PushKnownDataContracts(context); WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle); PopKnownDataContracts(context); } public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context); } protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context) { context.AddNewObject(obj); return obj; } protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader) { if (reader.MoveToAttribute(JsonGlobals.typeString) && (reader.Value == JsonGlobals.nullString)) { reader.Skip(); reader.MoveToElement(); return true; } reader.MoveToElement(); return false; } protected void PopKnownDataContracts(XmlObjectSerializerContext context) { if (KnownDataContracts != null) { context.scopedKnownTypes.Pop(); } } protected void PushKnownDataContracts(XmlObjectSerializerContext context) { if (KnownDataContracts != null) { context.scopedKnownTypes.Push(KnownDataContracts); } } internal class JsonDataContractCriticalHelper { private static object s_cacheLock = new object(); private static object s_createDataContractLock = new object(); private static JsonDataContract[] s_dataContractCache = new JsonDataContract[32]; private static int s_dataContractID = 0; private static TypeHandleRef s_typeHandleRef = new TypeHandleRef(); private static Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer()); private Dictionary<XmlQualifiedName, DataContract> _knownDataContracts; private DataContract _traditionalDataContract; private string _typeName; internal JsonDataContractCriticalHelper(DataContract traditionalDataContract) { _traditionalDataContract = traditionalDataContract; AddCollectionItemContractsToKnownDataContracts(); _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value)); } internal Dictionary<XmlQualifiedName, DataContract> KnownDataContracts => _knownDataContracts; internal DataContract TraditionalDataContract => _traditionalDataContract; internal virtual string TypeName => _typeName; public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle); JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { dataContract = CreateJsonDataContract(id, traditionalDataContract); s_dataContractCache[id] = dataContract; } return dataContract; } internal static int GetId(RuntimeTypeHandle typeHandle) { lock (s_cacheLock) { IntRef id; s_typeHandleRef.Value = typeHandle; if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id)) { int value = s_dataContractID++; if (value >= s_dataContractCache.Length) { int newSize = (value < int.MaxValue / 2) ? value * 2 : int.MaxValue; if (newSize <= value) { Fx.Assert("DataContract cache overflow"); throw new SerializationException(SR.DataContractCacheOverflow); } Array.Resize<JsonDataContract>(ref s_dataContractCache, newSize); } id = new IntRef(value); try { s_typeToIDCache.Add(new TypeHandleRef(typeHandle), id); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } return id.Value; } } private static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract) { lock (s_createDataContractLock) { JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { Type traditionalDataContractType = traditionalDataContract.GetType(); if (traditionalDataContractType == typeof(ObjectDataContract)) { dataContract = new JsonObjectDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(StringDataContract)) { dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(UriDataContract)) { dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(QNameDataContract)) { dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(ByteArrayDataContract)) { dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract); } else if (traditionalDataContract.IsPrimitive || traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(ClassDataContract)) { dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(EnumDataContract)) { dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract); } else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) || (traditionalDataContractType == typeof(SpecialTypeDataContract))) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(CollectionDataContract)) { dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(XmlDataContract)) { dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract); } else { throw new ArgumentException(SR.Format(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType), nameof(traditionalDataContract)); } } return dataContract; } } private void AddCollectionItemContractsToKnownDataContracts() { if (_traditionalDataContract.KnownDataContracts != null) { foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in _traditionalDataContract.KnownDataContracts) { if (!object.ReferenceEquals(knownDataContract, null)) { CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract; while (collectionDataContract != null) { DataContract itemContract = collectionDataContract.ItemContract; if (_knownDataContracts == null) { _knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>(); } _knownDataContracts.TryAdd(itemContract.StableName, itemContract); if (collectionDataContract.ItemType.IsGenericType && collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>)) { DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GenericTypeArguments)); _knownDataContracts.TryAdd(itemDataContract.StableName, itemDataContract); } if (!(itemContract is CollectionDataContract)) { break; } collectionDataContract = itemContract as CollectionDataContract; } } } } } } } #if uapaot public class JsonReadWriteDelegates #else internal class JsonReadWriteDelegates #endif { // this is the global dictionary for JSON delegates introduced for multi-file private static Dictionary<DataContract, JsonReadWriteDelegates> s_jsonDelegates = new Dictionary<DataContract, JsonReadWriteDelegates>(); public static Dictionary<DataContract, JsonReadWriteDelegates> GetJsonDelegates() { return s_jsonDelegates; } public JsonFormatClassWriterDelegate ClassWriterDelegate { get; set; } public JsonFormatClassReaderDelegate ClassReaderDelegate { get; set; } public JsonFormatCollectionWriterDelegate CollectionWriterDelegate { get; set; } public JsonFormatCollectionReaderDelegate CollectionReaderDelegate { get; set; } public JsonFormatGetOnlyCollectionReaderDelegate GetOnlyCollectionReaderDelegate { get; set; } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeFixes.Async; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Async { public partial class AddAsyncTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task AwaitInVoidMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async void Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task AwaitInTaskMethodNoModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task AwaitInTaskMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public/*Comment*/static/*Comment*/Task/*Comment*/Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public/*Comment*/static/*Comment*/async Task/*Comment*/Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task AwaitInLambdaFunction() { var initial = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => Console.WriteLine(); Func<Task> b = () => [|await Task.Run(a);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => Console.WriteLine(); Func<Task> b = async () => await Task.Run(a); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task AwaitInLambdaAction() { var initial = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = async () => await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task BadAwaitInNonAsyncMethod() { var initial = @"using System.Threading.Tasks; class Program { void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async void Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task BadAwaitInNonAsyncMethod2() { var initial = @"using System.Threading.Tasks; class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task BadAwaitInNonAsyncMethod3() { var initial = @"using System.Threading.Tasks; class Program { Task<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task BadAwaitInNonAsyncMethod4() { var initial = @"using System.Threading.Tasks; class Program { int Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task BadAwaitInNonAsyncMethod5() { var initial = @"class Program { void Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async void Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task BadAwaitInNonAsyncMethod6() { var initial = @"class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async Task Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task BadAwaitInNonAsyncMethod7() { var initial = @"class Program { Task<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async Task<int> Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task BadAwaitInNonAsyncMethod8() { var initial = @"class Program { int Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async System.Threading.Tasks.Task<int> Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task BadAwaitInNonAsyncMethod9() { var initial = @"class Program { Program Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async System.Threading.Tasks.Task<Program> Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task BadAwaitInNonAsyncMethod10() { var initial = @"class Program { asdf Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async System.Threading.Tasks.Task<asdf> Test() { await Task.Delay(1); } }"; await TestAsync(initial, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task AwaitInMember() { var code = @"using System.Threading.Tasks; class Program { var x = [|await Task.Delay(3)|]; }"; await TestMissingAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task AddAsyncInDelegate() { await TestAsync( @"using System ; using System . Threading . Tasks ; class Program { private async void method ( ) { string content = await Task < String > . Run ( delegate ( ) { [|await Task . Delay ( 1000 )|] ; return ""Test"" ; } ) ; } } ", @"using System ; using System . Threading . Tasks ; class Program { private async void method ( ) { string content = await Task < String > . Run ( async delegate ( ) { await Task . Delay ( 1000 ) ; return ""Test"" ; } ) ; } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task AddAsyncInDelegate2() { await TestAsync( @"using System ; using System . Threading . Tasks ; class Program { private void method ( ) { string content = await Task < String > . Run ( delegate ( ) { [|await Task . Delay ( 1000 )|] ; return ""Test"" ; } ) ; } } ", @"using System ; using System . Threading . Tasks ; class Program { private void method ( ) { string content = await Task < String > . Run ( async delegate ( ) { await Task . Delay ( 1000 ) ; return ""Test"" ; } ) ; } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task AddAsyncInDelegate3() { await TestAsync( @"using System ; using System . Threading . Tasks ; class Program { private void method ( ) { string content = await Task < String > . Run ( delegate ( ) { [|await Task . Delay ( 1000 )|] ; return ""Test"" ; } ) ; } } ", @"using System ; using System . Threading . Tasks ; class Program { private void method ( ) { string content = await Task < String > . Run ( async delegate ( ) { await Task . Delay ( 1000 ) ; return ""Test"" ; } ) ; } } "); } [WorkItem(6477, @"https://github.com/dotnet/roslyn/issues/6477")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAsync)] public async Task NullNodeCrash() { await TestMissingAsync( @"using System.Threading.Tasks; class C { static async void Main() { try { [|await|] await Task.Delay(100); } finally { } } }"); } internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(null, new CSharpAddAsyncCodeFixProvider()); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using Lucene.Net.Store; using Lucene.Net.Index; using Lucene.Net.Analysis; using Lucene.Net.Documents; using Lucene.Net.Search; using Lucene.Net.Util; using Lucene.Net.Search.Spans; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search { [TestFixture] public class TestCachingWrapperFilter : LuceneTestCase { [Test] public virtual void TestCachingWorks() { Directory dir = new RAMDirectory(); IndexWriter writer = new IndexWriter(dir, new KeywordAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); writer.Close(); IndexReader reader = IndexReader.Open(dir, true); MockFilter filter = new MockFilter(); CachingWrapperFilter cacher = new CachingWrapperFilter(filter); // first time, nested filter is called cacher.GetDocIdSet(reader); Assert.IsTrue(filter.WasCalled(), "first time"); // make sure no exception if cache is holding the wrong DocIdSet cacher.GetDocIdSet(reader); // second time, nested filter should not be called filter.Clear(); cacher.GetDocIdSet(reader); Assert.IsFalse(filter.WasCalled(), "second time"); reader.Close(); } [Test] public void TestNullDocIdSet() { Directory dir = new RAMDirectory(); IndexWriter writer = new IndexWriter(dir, new KeywordAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); writer.Close(); IndexReader reader = IndexReader.Open(dir, true); Filter filter = new AnonymousFilter(); CachingWrapperFilter cacher = new CachingWrapperFilter(filter); // the caching filter should return the empty set constant Assert.AreSame(DocIdSet.EMPTY_DOCIDSET, cacher.GetDocIdSet(reader)); reader.Close(); } class AnonymousFilter : Filter { public override DocIdSet GetDocIdSet(IndexReader reader) { return null; } } [Test] public void TestNullDocIdSetIterator() { Directory dir = new RAMDirectory(); IndexWriter writer = new IndexWriter(dir, new KeywordAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); writer.Close(); IndexReader reader = IndexReader.Open(dir, true); Filter filter = new AnonymousFilter2(); CachingWrapperFilter cacher = new CachingWrapperFilter(filter); // the caching filter should return the empty set constant Assert.AreSame(DocIdSet.EMPTY_DOCIDSET, cacher.GetDocIdSet(reader)); reader.Close(); } class AnonymousFilter2 : Filter { class AnonymousDocIdSet : DocIdSet { public override DocIdSetIterator Iterator() { return null; } } public override DocIdSet GetDocIdSet(IndexReader reader) { return new AnonymousDocIdSet();// base.GetDocIdSet(reader); } } private static void assertDocIdSetCacheable(IndexReader reader, Filter filter, bool shouldCacheable) { CachingWrapperFilter cacher = new CachingWrapperFilter(filter); DocIdSet originalSet = filter.GetDocIdSet(reader); DocIdSet cachedSet = cacher.GetDocIdSet(reader); Assert.IsTrue(cachedSet.IsCacheable); Assert.AreEqual(shouldCacheable, originalSet.IsCacheable); //System.out.println("Original: "+originalSet.getClass().getName()+" -- cached: "+cachedSet.getClass().getName()); if (originalSet.IsCacheable) { Assert.AreEqual(originalSet.GetType(), cachedSet.GetType(), "Cached DocIdSet must be of same class like uncached, if cacheable"); } else { Assert.IsTrue(cachedSet is OpenBitSetDISI, "Cached DocIdSet must be an OpenBitSet if the original one was not cacheable"); } } [Test] public void TestIsCacheable() { Directory dir = new RAMDirectory(); IndexWriter writer = new IndexWriter(dir, new KeywordAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); writer.Close(); IndexReader reader = IndexReader.Open(dir, true); // not cacheable: assertDocIdSetCacheable(reader, new QueryWrapperFilter(new TermQuery(new Term("test", "value"))), false); // returns default empty docidset, always cacheable: assertDocIdSetCacheable(reader, NumericRangeFilter.NewIntRange("test", 10000, -10000, true, true), true); // is cacheable: assertDocIdSetCacheable(reader, FieldCacheRangeFilter.NewIntRange("test", 10, 20, true, true), true); // a openbitset filter is always cacheable assertDocIdSetCacheable(reader, new AnonymousFilter3(), true); reader.Close(); } class AnonymousFilter3 : Filter { public override DocIdSet GetDocIdSet(IndexReader reader) { return new OpenBitSet(); } } [Test] public void TestEnforceDeletions() { Directory dir = new MockRAMDirectory(); IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED); IndexReader reader = writer.GetReader(); IndexSearcher searcher = new IndexSearcher(reader); // add a doc, refresh the reader, and check that its there Document doc = new Document(); doc.Add(new Field("id", "1", Field.Store.YES, Field.Index.NOT_ANALYZED)); writer.AddDocument(doc); reader = RefreshReader(reader); searcher = new IndexSearcher(reader); TopDocs docs = searcher.Search(new MatchAllDocsQuery(), 1); Assert.AreEqual(1, docs.TotalHits, "Should find a hit..."); Filter startFilter = new QueryWrapperFilter(new TermQuery(new Term("id", "1"))); // ignore deletions CachingWrapperFilter filter = new CachingWrapperFilter(startFilter, CachingWrapperFilter.DeletesMode.IGNORE); docs = searcher.Search(new MatchAllDocsQuery(), filter, 1); Assert.AreEqual(1, docs.TotalHits, "[query + filter] Should find a hit..."); ConstantScoreQuery constantScore = new ConstantScoreQuery(filter); docs = searcher.Search(constantScore, 1); Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit..."); // now delete the doc, refresh the reader, and see that it's not there writer.DeleteDocuments(new Term("id", "1")); reader = RefreshReader(reader); searcher = new IndexSearcher(reader); docs = searcher.Search(new MatchAllDocsQuery(), filter, 1); Assert.AreEqual(0, docs.TotalHits, "[query + filter] Should *not* find a hit..."); docs = searcher.Search(constantScore, 1); Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit..."); // force cache to regenerate: filter = new CachingWrapperFilter(startFilter, CachingWrapperFilter.DeletesMode.RECACHE); writer.AddDocument(doc); reader = RefreshReader(reader); searcher = new IndexSearcher(reader); docs = searcher.Search(new MatchAllDocsQuery(), filter, 1); Assert.AreEqual(1, docs.TotalHits, "[query + filter] Should find a hit..."); constantScore = new ConstantScoreQuery(filter); docs = searcher.Search(constantScore, 1); Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit..."); // make sure we get a cache hit when we reopen reader // that had no change to deletions IndexReader newReader = RefreshReader(reader); Assert.IsTrue(reader != newReader); reader = newReader; searcher = new IndexSearcher(reader); int missCount = filter.missCount; docs = searcher.Search(constantScore, 1); Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit..."); Assert.AreEqual(missCount, filter.missCount); // now delete the doc, refresh the reader, and see that it's not there writer.DeleteDocuments(new Term("id", "1")); reader = RefreshReader(reader); searcher = new IndexSearcher(reader); missCount = filter.missCount; docs = searcher.Search(new MatchAllDocsQuery(), filter, 1); Assert.AreEqual(missCount + 1, filter.missCount); Assert.AreEqual(0, docs.TotalHits, "[query + filter] Should *not* find a hit..."); docs = searcher.Search(constantScore, 1); Assert.AreEqual(0, docs.TotalHits, "[just filter] Should *not* find a hit..."); // apply deletions dynamically filter = new CachingWrapperFilter(startFilter, CachingWrapperFilter.DeletesMode.DYNAMIC); writer.AddDocument(doc); reader = RefreshReader(reader); searcher = new IndexSearcher(reader); docs = searcher.Search(new MatchAllDocsQuery(), filter, 1); Assert.AreEqual(1, docs.TotalHits, "[query + filter] Should find a hit..."); constantScore = new ConstantScoreQuery(filter); docs = searcher.Search(constantScore, 1); Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit..."); // now delete the doc, refresh the reader, and see that it's not there writer.DeleteDocuments(new Term("id", "1")); reader = RefreshReader(reader); searcher = new IndexSearcher(reader); docs = searcher.Search(new MatchAllDocsQuery(), filter, 1); Assert.AreEqual(0, docs.TotalHits, "[query + filter] Should *not* find a hit..."); missCount = filter.missCount; docs = searcher.Search(constantScore, 1); Assert.AreEqual(0, docs.TotalHits, "[just filter] Should *not* find a hit..."); // doesn't count as a miss Assert.AreEqual(missCount, filter.missCount); } private static IndexReader RefreshReader(IndexReader reader) { IndexReader oldReader = reader; reader = reader.Reopen(); if (reader != oldReader) { oldReader.Close(); } return reader; } } }
#region License /* The MIT License * * Copyright (c) 2011 Red Badger Consulting * * 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 //------------------------------------------------------------------------------------------------- // <auto-generated> // Marked as auto-generated so StyleCop will ignore BDD style tests // </auto-generated> //------------------------------------------------------------------------------------------------- #pragma warning disable 169 // ReSharper disable InconsistentNaming // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local namespace RedBadger.Xpf.Specs.Controls.GridSpecs { using Machine.Specifications; using Moq; using Moq.Protected; using RedBadger.Xpf.Controls; using RedBadger.Xpf.Internal; using It = Machine.Specifications.It; [Subject(typeof(Grid), "Measure")] public class when_a_column_index_is_specified_greater_than_the_number_of_columns_available : a_Grid { private const double Column2Width = 20d; private static Mock<UIElement> child; private Establish context = () => { Subject.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(10d) }); Subject.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(Column2Width) }); child = new Mock<UIElement> { CallBase = true }; Grid.SetColumn(child.Object, 2); Subject.Children.Add(child.Object); }; private Because of = () => Subject.Measure(AvailableSize); private It should_put_it_in_the_last_column = () => child.Protected().Verify( MeasureOverride, Times.Once(), ItExpr.Is<Size>(size => size.Width.Equals(Column2Width))); } [Subject(typeof(Grid), "Measure")] public class when_a_row_index_is_specified_greater_than_the_number_of_rows_available : a_Grid { private const double Row2Height = 20d; private static Mock<UIElement> child; private Establish context = () => { Subject.RowDefinitions.Add(new RowDefinition { Height = new GridLength(10d) }); Subject.RowDefinitions.Add(new RowDefinition { Height = new GridLength(Row2Height) }); child = new Mock<UIElement> { CallBase = true }; Grid.SetRow(child.Object, 2); Subject.Children.Add(child.Object); }; private Because of = () => Subject.Measure(AvailableSize); private It should_put_it_in_the_last_row = () => child.Protected().Verify( MeasureOverride, Times.Once(), ItExpr.Is<Size>(size => size.Height.Equals(Row2Height))); } [Subject(typeof(Grid), "Measure - Pixel/Auto/Star")] public class when_measuring_a_grid_that_has_columns_of_mixed_pixel_auto_and_star : a_Grid { private const int Column1PixelWidth = 30; private const int Column2ChildWidth = 20; private static readonly Mock<UIElement>[] children = new Mock<UIElement>[4]; private static readonly double expectedProportionalWidth = (AvailableSize.Width - Column1PixelWidth - Column2ChildWidth) / 2; private Establish context = () => { Subject.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(Column1PixelWidth) }); Subject.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) }); Subject.ColumnDefinitions.Add(new ColumnDefinition()); Subject.ColumnDefinitions.Add(new ColumnDefinition()); children[0] = new Mock<UIElement> { CallBase = true }; children[1] = new Mock<UIElement> { CallBase = true }; children[2] = new Mock<UIElement> { CallBase = true }; children[3] = new Mock<UIElement> { CallBase = true }; Grid.SetColumn(children[0].Object, 0); Grid.SetColumn(children[1].Object, 1); Grid.SetColumn(children[2].Object, 2); Grid.SetColumn(children[3].Object, 3); children[1].Object.Width = Column2ChildWidth; Subject.Children.Add(children[0].Object); Subject.Children.Add(children[1].Object); Subject.Children.Add(children[2].Object); Subject.Children.Add(children[3].Object); }; private Because of = () => Subject.Measure(AvailableSize); private It should_give_column_1_the_correct_amount_of_space = () => children[0].Protected().Verify( MeasureOverride, Times.Once(), ItExpr.Is<Size>(size => size.Width.Equals(Column1PixelWidth))); private It should_give_column_2_the_correct_amount_of_space = () => children[1].Protected().Verify( MeasureOverride, Times.Once(), ItExpr.Is<Size>(size => size.Width.Equals(Column2ChildWidth))); private It should_give_column_3_the_correct_amount_of_space = () => children[2].Protected().Verify( MeasureOverride, Times.Once(), ItExpr.Is<Size>(size => size.Width.IsCloseTo(expectedProportionalWidth))); private It should_give_column_4_the_correct_amount_of_space = () => children[3].Protected().Verify( MeasureOverride, Times.Once(), ItExpr.Is<Size>(size => size.Width.IsCloseTo(expectedProportionalWidth))); } [Subject(typeof(Grid), "Measure - Pixel/Auto/Star")] public class when_measuring_a_grid_that_has_rows_of_mixed_pixel_auto_and_star : a_Grid { private const int Row1PixelHeight = 30; private const int Row2ChildHeight = 20; private static readonly Mock<UIElement>[] children = new Mock<UIElement>[4]; private static readonly double expectedProportionalHeight = (AvailableSize.Height - Row1PixelHeight - Row2ChildHeight) / 2; private Establish context = () => { Subject.RowDefinitions.Add(new RowDefinition { Height = new GridLength(Row1PixelHeight) }); Subject.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) }); Subject.RowDefinitions.Add(new RowDefinition()); Subject.RowDefinitions.Add(new RowDefinition()); children[0] = new Mock<UIElement> { CallBase = true }; children[1] = new Mock<UIElement> { CallBase = true }; children[2] = new Mock<UIElement> { CallBase = true }; children[3] = new Mock<UIElement> { CallBase = true }; Grid.SetRow(children[0].Object, 0); Grid.SetRow(children[1].Object, 1); Grid.SetRow(children[2].Object, 2); Grid.SetRow(children[3].Object, 3); children[1].Object.Height = Row2ChildHeight; Subject.Children.Add(children[0].Object); Subject.Children.Add(children[1].Object); Subject.Children.Add(children[2].Object); Subject.Children.Add(children[3].Object); }; private Because of = () => Subject.Measure(AvailableSize); private It should_give_row_1_the_correct_amount_of_space = () => children[0].Protected().Verify( MeasureOverride, Times.Once(), ItExpr.Is<Size>(size => size.Height.Equals(Row1PixelHeight))); private It should_give_row_2_the_correct_amount_of_space = () => children[1].Protected().Verify( MeasureOverride, Times.Once(), ItExpr.Is<Size>(size => size.Height.Equals(Row2ChildHeight))); private It should_give_row_3_the_correct_amount_of_space = () => children[2].Protected().Verify( MeasureOverride, Times.Once(), ItExpr.Is<Size>(size => size.Height.Equals(expectedProportionalHeight))); private It should_give_row_4_the_correct_amount_of_space = () => children[3].Protected().Verify( MeasureOverride, Times.Once(), ItExpr.Is<Size>(size => size.Height.Equals(expectedProportionalHeight))); } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using FluentMigrator.Expressions; using FluentMigrator.Model; using FluentMigrator.Runner.Versioning; using FluentMigrator.VersionTableInfo; using FluentMigrator.Infrastructure; using FluentMigrator.Runner.Initialization; namespace FluentMigrator.Runner { public class VersionLoader : IVersionLoader { private bool _versionSchemaMigrationAlreadyRun; private bool _versionMigrationAlreadyRun; private bool _versionUniqueMigrationAlreadyRun; private bool _versionDescriptionMigrationAlreadyRun; private IVersionInfo _versionInfo; private IMigrationConventions Conventions { get; set; } private IMigrationProcessor Processor { get; set; } protected IAssemblyCollection Assemblies { get; set; } public IVersionTableMetaData VersionTableMetaData { get; private set; } public IMigrationRunner Runner { get; set; } public VersionSchemaMigration VersionSchemaMigration { get; private set; } public IMigration VersionMigration { get; private set; } public IMigration VersionUniqueMigration { get; private set; } public IMigration VersionDescriptionMigration { get; private set; } public VersionLoader(IMigrationRunner runner, Assembly assembly, IMigrationConventions conventions) : this(runner, new SingleAssembly(assembly), conventions) { } public VersionLoader(IMigrationRunner runner, IAssemblyCollection assemblies, IMigrationConventions conventions) { Runner = runner; Processor = runner.Processor; Assemblies = assemblies; Conventions = conventions; VersionTableMetaData = GetVersionTableMetaData(); VersionMigration = new VersionMigration(VersionTableMetaData); VersionSchemaMigration = new VersionSchemaMigration(VersionTableMetaData); VersionUniqueMigration = new VersionUniqueMigration(VersionTableMetaData); VersionDescriptionMigration = new VersionDescriptionMigration(VersionTableMetaData); LoadVersionInfo(); } public void UpdateVersionInfo(long version) { UpdateVersionInfo(version, null); } public void UpdateVersionInfo(long version, string description) { var dataExpression = new InsertDataExpression(); dataExpression.Rows.Add(CreateVersionInfoInsertionData(version, description)); dataExpression.TableName = VersionTableMetaData.TableName; dataExpression.SchemaName = VersionTableMetaData.SchemaName; dataExpression.ExecuteWith(Processor); } public IVersionTableMetaData GetVersionTableMetaData() { Type matchedType = Assemblies.GetExportedTypes() .FilterByNamespace(Runner.RunnerContext.Namespace, Runner.RunnerContext.NestedNamespaces) .FirstOrDefault(t => Conventions.TypeIsVersionTableMetaData(t)); if (matchedType == null) { return new DefaultVersionTableMetaData(); } var versionTableMetaData = (IVersionTableMetaData)Activator.CreateInstance(matchedType); versionTableMetaData.ApplicationContext = Runner.RunnerContext.ApplicationContext; return versionTableMetaData; } protected virtual InsertionDataDefinition CreateVersionInfoInsertionData(long version, string description) { return new InsertionDataDefinition { new KeyValuePair<string, object>(VersionTableMetaData.ColumnName, version), new KeyValuePair<string, object>(VersionTableMetaData.AppliedOnColumnName, DateTime.UtcNow), new KeyValuePair<string, object>(VersionTableMetaData.DescriptionColumnName, description), }; } public IVersionInfo VersionInfo { get { return _versionInfo; } set { if (value == null) throw new ArgumentException("Cannot set VersionInfo to null"); _versionInfo = value; } } public bool AlreadyCreatedVersionSchema { get { return string.IsNullOrEmpty(VersionTableMetaData.SchemaName) || Processor.SchemaExists(VersionTableMetaData.SchemaName); } } public bool AlreadyCreatedVersionTable { get { return Processor.TableExists(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName); } } public bool AlreadyMadeVersionUnique { get { return Processor.ColumnExists(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName, VersionTableMetaData.AppliedOnColumnName); } } public bool AlreadyMadeVersionDescription { get { return Processor.ColumnExists(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName, VersionTableMetaData.DescriptionColumnName); } } public bool OwnsVersionSchema { get { return VersionTableMetaData.OwnsSchema; } } public void LoadVersionInfo() { if (!AlreadyCreatedVersionSchema && !_versionSchemaMigrationAlreadyRun) { Runner.Up(VersionSchemaMigration); _versionSchemaMigrationAlreadyRun = true; } if (!AlreadyCreatedVersionTable && !_versionMigrationAlreadyRun) { Runner.Up(VersionMigration); _versionMigrationAlreadyRun = true; } if (!AlreadyMadeVersionUnique && !_versionUniqueMigrationAlreadyRun) { Runner.Up(VersionUniqueMigration); _versionUniqueMigrationAlreadyRun = true; } if (!AlreadyMadeVersionDescription && !_versionDescriptionMigrationAlreadyRun) { Runner.Up(VersionDescriptionMigration); _versionDescriptionMigrationAlreadyRun = true; } _versionInfo = new VersionInfo(); if (!AlreadyCreatedVersionTable) return; var dataSet = Processor.ReadTableData(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName); foreach (DataRow row in dataSet.Tables[0].Rows) { _versionInfo.AddAppliedMigration(long.Parse(row[VersionTableMetaData.ColumnName].ToString())); } } public void RemoveVersionTable() { var expression = new DeleteTableExpression { TableName = VersionTableMetaData.TableName, SchemaName = VersionTableMetaData.SchemaName }; expression.ExecuteWith(Processor); if (OwnsVersionSchema && !string.IsNullOrEmpty(VersionTableMetaData.SchemaName)) { var schemaExpression = new DeleteSchemaExpression { SchemaName = VersionTableMetaData.SchemaName }; schemaExpression.ExecuteWith(Processor); } } public void DeleteVersion(long version) { var expression = new DeleteDataExpression { TableName = VersionTableMetaData.TableName, SchemaName = VersionTableMetaData.SchemaName }; expression.Rows.Add(new DeletionDataDefinition { new KeyValuePair<string, object>(VersionTableMetaData.ColumnName, version) }); expression.ExecuteWith(Processor); } } }
//#define ProfileAstar using UnityEngine; using System.Text; using Pathfinding; [AddComponentMenu("Pathfinding/Debugger")] [ExecuteInEditMode] /** Debugger for the A* Pathfinding Project. * This class can be used to profile different parts of the pathfinding system * and the whole game as well to some extent. * * Clarification of the labels shown when enabled. * All memory related things profiles <b>the whole game</b> not just the A* Pathfinding System.\n * - Currently allocated: memory the GC (garbage collector) says the application has allocated right now. * - Peak allocated: maximum measured value of the above. * - Last collect peak: the last peak of 'currently allocated'. * - Allocation rate: how much the 'currently allocated' value increases per second. This value is not as reliable as you can think * it is often very random probably depending on how the GC thinks this application is using memory. * - Collection frequency: how often the GC is called. Again, the GC might decide it is better with many small collections * or with a few large collections. So you cannot really trust this variable much. * - Last collect fps: FPS during the last garbage collection, the GC will lower the fps a lot. * * - FPS: current FPS (not updated every frame for readability) * - Lowest FPS (last x): As the label says, the lowest fps of the last x frames. * * - Size: Size of the path pool. * - Total created: Number of paths of that type which has been created. Pooled paths are not counted twice. * If this value just keeps on growing and growing without an apparent stop, you are are either not pooling any paths * or you have missed to pool some path somewhere in your code. * * \see pooling * * \todo Add field showing how many graph updates are being done right now */ public class AstarDebugger : MonoBehaviour { public int yOffset = 5; public bool show = true; public bool showInEditor = false; public bool showFPS = false; public bool showPathProfile = false; public bool showMemProfile = false; public bool showGraph = false; public int graphBufferSize = 200; /** Font to use. * A monospaced font is the best */ public Font font = null; public int fontSize = 12; StringBuilder text = new StringBuilder (); string cachedText; float lastUpdate = -999; private GraphPoint[] graph; struct GraphPoint { public float fps, memory; public bool collectEvent; } private float delayedDeltaTime = 1; private float lastCollect = 0; private float lastCollectNum = 0; private float delta = 0; private float lastDeltaTime = 0; private int allocRate = 0; private int lastAllocMemory = 0; private float lastAllocSet = -9999; private int allocMem = 0; private int collectAlloc = 0; private int peakAlloc = 0; private int fpsDropCounterSize = 200; private float[] fpsDrops; private Rect boxRect; private GUIStyle style; private Camera cam; private LineRenderer lineRend; float graphWidth = 100; float graphHeight = 100; float graphOffset = 50; public void Start () { useGUILayout = false; fpsDrops = new float[fpsDropCounterSize]; if (GetComponent<Camera>() != null) { cam = GetComponent<Camera>(); } else { cam = Camera.main; } graph = new GraphPoint[graphBufferSize]; for (int i=0;i<fpsDrops.Length;i++) { fpsDrops[i] = 1F / Time.deltaTime; } } int maxVecPool = 0; int maxNodePool = 0; PathTypeDebug[] debugTypes = new PathTypeDebug[] { new PathTypeDebug ("ABPath", PathPool<ABPath>.GetSize, PathPool<ABPath>.GetTotalCreated) }; struct PathTypeDebug { string name; System.Func<int> getSize; System.Func<int> getTotalCreated; public PathTypeDebug (string name, System.Func<int> getSize, System.Func<int> getTotalCreated) { this.name = name; this.getSize = getSize; this.getTotalCreated = getTotalCreated; } public void Print (StringBuilder text) { int totCreated = getTotalCreated (); if (totCreated > 0) { text.Append("\n").Append ((" " + name).PadRight (25)).Append (getSize()).Append("/").Append(totCreated); } } } public void Update () { if (!show || (!Application.isPlaying && !showInEditor)) return; int collCount = System.GC.CollectionCount (0); if (lastCollectNum != collCount) { lastCollectNum = collCount; delta = Time.realtimeSinceStartup-lastCollect; lastCollect = Time.realtimeSinceStartup; lastDeltaTime = Time.deltaTime; collectAlloc = allocMem; } allocMem = (int)System.GC.GetTotalMemory (false); bool collectEvent = allocMem < peakAlloc; peakAlloc = !collectEvent ? allocMem : peakAlloc; if (Time.realtimeSinceStartup - lastAllocSet > 0.3F || !Application.isPlaying) { int diff = allocMem - lastAllocMemory; lastAllocMemory = allocMem; lastAllocSet = Time.realtimeSinceStartup; delayedDeltaTime = Time.deltaTime; if (diff >= 0) { allocRate = diff; } } if (Application.isPlaying) { fpsDrops[Time.frameCount % fpsDrops.Length] = Time.deltaTime != 0 ? 1F / Time.deltaTime : float.PositiveInfinity; int graphIndex = Time.frameCount % graph.Length; graph[graphIndex].fps = Time.deltaTime < Mathf.Epsilon ? 0 : 1F / Time.deltaTime; graph[graphIndex].collectEvent = collectEvent; graph[graphIndex].memory = allocMem; } if (Application.isPlaying && cam != null && showGraph) { graphWidth = cam.pixelWidth*0.8f; float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0; for (int i=0;i<graph.Length;i++) { minMem = Mathf.Min (graph[i].memory, minMem); maxMem = Mathf.Max (graph[i].memory, maxMem); minFPS = Mathf.Min (graph[i].fps, minFPS); maxFPS = Mathf.Max (graph[i].fps, maxFPS); } int currentGraphIndex = Time.frameCount % graph.Length; Matrix4x4 m = Matrix4x4.TRS (new Vector3 ((cam.pixelWidth - graphWidth)/2f, graphOffset,1), Quaternion.identity, new Vector3 (graphWidth, graphHeight, 1)); for (int i=0;i<graph.Length-1;i++) { if (i == currentGraphIndex) continue; //Debug.DrawLine (m.MultiplyPoint (new Vector3 (i/(float)graph.Length, Mathfx.MapTo (minMem, maxMem, graph[i].memory), -1)), // m.MultiplyPoint (new Vector3 ((i+1)/(float)graph.Length, Mathfx.MapTo (minMem, maxMem, graph[i+1].memory), -1)), Color.blue); //Debug.DrawLine (m.MultiplyPoint (Vector3.zero), m.MultiplyPoint (-Vector3.one), Color.red); //Debug.Log (Mathfx.MapTo (minMem, maxMem, graph[i].memory) + " " + graph[i].memory); DrawGraphLine (i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, AstarMath.MapTo (minMem, maxMem, graph[i].memory), AstarMath.MapTo (minMem, maxMem, graph[i+1].memory), Color.blue); DrawGraphLine (i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, AstarMath.MapTo (minFPS, maxFPS, graph[i].fps), AstarMath.MapTo (minFPS, maxFPS, graph[i+1].fps), Color.green); //Debug.DrawLine (m.MultiplyPoint (new Vector3 (i/(float)graph.Length, Mathfx.MapTo (minFPS, maxFPS, graph[i].fps), -1)), // m.MultiplyPoint (new Vector3 ((i+1)/(float)graph.Length, Mathfx.MapTo (minFPS, maxFPS, graph[i+1].fps), -1)), Color.green); } /*Cross (new Vector3(0,0,1)); Cross (new Vector3(1,1,1)); Cross (new Vector3(0,1,1)); Cross (new Vector3(1,0,1)); Cross (new Vector3(-1,0,1)); Debug.DrawLine (m.MultiplyPoint(Vector3.zero), m.MultiplyPoint(new Vector3(0,0,-5)),Color.blue);*/ } } public void DrawGraphLine (int index, Matrix4x4 m, float x1, float x2, float y1, float y2, Color col) { Debug.DrawLine (cam.ScreenToWorldPoint (m.MultiplyPoint3x4 (new Vector3 (x1,y1))), cam.ScreenToWorldPoint (m.MultiplyPoint3x4 (new Vector3 (x2,y2))), col); } public void Cross (Vector3 p) { p = cam.cameraToWorldMatrix.MultiplyPoint (p); Debug.DrawLine (p-Vector3.up*0.2f, p+Vector3.up*0.2f,Color.red); Debug.DrawLine (p-Vector3.right*0.2f, p+Vector3.right*0.2f,Color.red); } public void OnGUI () { if (!show || (!Application.isPlaying && !showInEditor)) return; if (style == null) { style = new GUIStyle(); style.normal.textColor = Color.white; style.padding = new RectOffset (5,5,5,5); } if (Time.realtimeSinceStartup - lastUpdate > 0.5f || cachedText == null || !Application.isPlaying) { lastUpdate = Time.realtimeSinceStartup; boxRect = new Rect (5,yOffset,310,40); text.Length = 0; text.AppendLine ("A* Pathfinding Project Debugger"); text.Append ("A* Version: ").Append (AstarPath.Version.ToString ()); if (showMemProfile) { boxRect.height += 200; text.AppendLine(); text.AppendLine(); text.Append ("Currently allocated".PadRight (25)); text.Append ((allocMem/1000000F).ToString ("0.0 MB")); text.AppendLine (); text.Append ("Peak allocated".PadRight (25)); text.Append ((peakAlloc/1000000F).ToString ("0.0 MB")).AppendLine(); text.Append ("Last collect peak".PadRight(25)); text.Append ((collectAlloc/1000000F).ToString ("0.0 MB")).AppendLine(); text.Append ("Allocation rate".PadRight (25)); text.Append ((allocRate/1000000F).ToString ("0.0 MB")).AppendLine(); text.Append ("Collection frequency".PadRight (25)); text.Append (delta.ToString ("0.00")); text.Append ("s\n"); text.Append ("Last collect fps".PadRight (25)); text.Append ((1F/lastDeltaTime).ToString ("0.0 fps")); text.Append (" ("); text.Append (lastDeltaTime.ToString ("0.000 s")); text.Append (")"); } if (showFPS) { text.AppendLine (); text.AppendLine(); text.Append ("FPS".PadRight (25)).Append((1F/delayedDeltaTime).ToString ("0.0 fps")); float minFps = Mathf.Infinity; for (int i=0;i<fpsDrops.Length;i++) if (fpsDrops[i] < minFps) minFps = fpsDrops[i]; text.AppendLine(); text.Append (("Lowest fps (last " + fpsDrops.Length + ")").PadRight(25)).Append(minFps.ToString ("0.0")); } if (showPathProfile) { AstarPath astar = AstarPath.active; text.AppendLine (); if (astar == null) { text.Append ("\nNo AstarPath Object In The Scene"); } else { if (Pathfinding.Util.ListPool<Vector3>.GetSize() > maxVecPool) maxVecPool = Pathfinding.Util.ListPool<Vector3>.GetSize(); if (Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize() > maxNodePool) maxNodePool = Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize(); text.Append ("\nPool Sizes (size/total created)"); for (int i=0;i<debugTypes.Length;i++) { debugTypes[i].Print (text); } } } cachedText = text.ToString(); } if (font != null) { style.font = font; style.fontSize = fontSize; } boxRect.height = style.CalcHeight (new GUIContent (cachedText),boxRect.width); GUI.Box (boxRect,""); GUI.Label (boxRect,cachedText,style); if (showGraph) { float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0; for (int i=0;i<graph.Length;i++) { minMem = Mathf.Min (graph[i].memory, minMem); maxMem = Mathf.Max (graph[i].memory, maxMem); minFPS = Mathf.Min (graph[i].fps, minFPS); maxFPS = Mathf.Max (graph[i].fps, maxFPS); } float line; GUI.color = Color.blue; //Round to nearest x.x MB line = Mathf.RoundToInt (maxMem/(100.0f*1000)); // *1000*100 GUI.Label (new Rect (5, Screen.height - AstarMath.MapTo (minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100,20), (line/10.0f).ToString("0.0 MB")); line = Mathf.Round (minMem/(100.0f*1000)); // *1000*100 GUI.Label (new Rect (5, Screen.height - AstarMath.MapTo (minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100,20), (line/10.0f).ToString("0.0 MB")); GUI.color = Color.green; //Round to nearest x.x MB line = Mathf.Round (maxFPS); // *1000*100 GUI.Label (new Rect (55, Screen.height - AstarMath.MapTo (minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100,20), (line).ToString("0 FPS")); line = Mathf.Round (minFPS); // *1000*100 GUI.Label (new Rect (55, Screen.height - AstarMath.MapTo (minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100,20), (line).ToString("0 FPS")); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sdb-2009-04-15.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.SimpleDB.Model; using Amazon.SimpleDB.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.SimpleDB { /// <summary> /// Implementation for accessing SimpleDB /// /// Amazon SimpleDB is a web service providing the core database functions of data indexing /// and querying in the cloud. By offloading the time and effort associated with building /// and operating a web-scale database, SimpleDB provides developers the freedom to focus /// on application development. /// <para> /// A traditional, clustered relational database requires a sizable upfront capital outlay, /// is complex to design, and often requires extensive and repetitive database administration. /// Amazon SimpleDB is dramatically simpler, requiring no schema, automatically indexing /// your data and providing a simple API for storage and access. This approach eliminates /// the administrative burden of data modeling, index maintenance, and performance tuning. /// Developers gain access to this functionality within Amazon's proven computing environment, /// are able to scale instantly, and pay only for what they use. /// </para> /// /// <para> /// Visit <a href="http://aws.amazon.com/simpledb/">http://aws.amazon.com/simpledb/</a> /// for more information. /// </para> /// </summary> public partial class AmazonSimpleDBClient : AmazonServiceClient, IAmazonSimpleDB { #region Constructors /// <summary> /// Constructs AmazonSimpleDBClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonSimpleDBClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonSimpleDBConfig()) { } /// <summary> /// Constructs AmazonSimpleDBClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonSimpleDBClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonSimpleDBConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonSimpleDBClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonSimpleDBClient Configuration Object</param> public AmazonSimpleDBClient(AmazonSimpleDBConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonSimpleDBClient(AWSCredentials credentials) : this(credentials, new AmazonSimpleDBConfig()) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonSimpleDBClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonSimpleDBConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Credentials and an /// AmazonSimpleDBClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonSimpleDBClient Configuration Object</param> public AmazonSimpleDBClient(AWSCredentials credentials, AmazonSimpleDBConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonSimpleDBConfig()) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonSimpleDBConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID, AWS Secret Key and an /// AmazonSimpleDBClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonSimpleDBClient Configuration Object</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonSimpleDBConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSimpleDBConfig()) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSimpleDBConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID, AWS Secret Key and an /// AmazonSimpleDBClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonSimpleDBClient Configuration Object</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonSimpleDBConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new QueryStringSigner(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region BatchDeleteAttributes /// <summary> /// Performs multiple DeleteAttributes operations in a single call, which reduces round /// trips and latencies. This enables Amazon SimpleDB to optimize requests, which generally /// yields better throughput. /// /// /// <para> /// The following limitations are enforced for this operation: <ul> <li>1 MB request /// size</li> <li>25 item limit per BatchDeleteAttributes operation</li> </ul> /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchDeleteAttributes service method.</param> /// /// <returns>The response from the BatchDeleteAttributes service method, as returned by SimpleDB.</returns> public BatchDeleteAttributesResponse BatchDeleteAttributes(BatchDeleteAttributesRequest request) { var marshaller = new BatchDeleteAttributesRequestMarshaller(); var unmarshaller = BatchDeleteAttributesResponseUnmarshaller.Instance; return Invoke<BatchDeleteAttributesRequest,BatchDeleteAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the BatchDeleteAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the BatchDeleteAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<BatchDeleteAttributesResponse> BatchDeleteAttributesAsync(BatchDeleteAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new BatchDeleteAttributesRequestMarshaller(); var unmarshaller = BatchDeleteAttributesResponseUnmarshaller.Instance; return InvokeAsync<BatchDeleteAttributesRequest,BatchDeleteAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region BatchPutAttributes /// <summary> /// The <code>BatchPutAttributes</code> operation creates or replaces attributes within /// one or more items. By using this operation, the client can perform multiple <a>PutAttribute</a> /// operation with a single call. This helps yield savings in round trips and latencies, /// enabling Amazon SimpleDB to optimize requests and generally produce better throughput. /// /// /// /// <para> /// The client may specify the item name with the <code>Item.X.ItemName</code> parameter. /// The client may specify new attributes using a combination of the <code>Item.X.Attribute.Y.Name</code> /// and <code>Item.X.Attribute.Y.Value</code> parameters. The client may specify the first /// attribute for the first item using the parameters <code>Item.0.Attribute.0.Name</code> /// and <code>Item.0.Attribute.0.Value</code>, and for the second attribute for the first /// item by the parameters <code>Item.0.Attribute.1.Name</code> and <code>Item.0.Attribute.1.Value</code>, /// and so on. /// </para> /// /// <para> /// Attributes are uniquely identified within an item by their name/value combination. /// For example, a single item can have the attributes <code>{ "first_name", "first_value" /// }</code> and <code>{ "first_name", "second_value" }</code>. However, it cannot have /// two attribute instances where both the <code>Item.X.Attribute.Y.Name</code> and <code>Item.X.Attribute.Y.Value</code> /// are the same. /// </para> /// /// <para> /// Optionally, the requester can supply the <code>Replace</code> parameter for each /// individual value. Setting this value to <code>true</code> will cause the new attribute /// values to replace the existing attribute values. For example, if an item <code>I</code> /// has the attributes <code>{ 'a', '1' }, { 'b', '2'}</code> and <code>{ 'b', '3' }</code> /// and the requester does a BatchPutAttributes of <code>{'I', 'b', '4' }</code> with /// the Replace parameter set to true, the final attributes of the item will be <code>{ /// 'a', '1' }</code> and <code>{ 'b', '4' }</code>, replacing the previous values of /// the 'b' attribute with the new value. /// </para> /// <important> This operation is vulnerable to exceeding the maximum URL size when making /// a REST request using the HTTP GET method. This operation does not support conditions /// using <code>Expected.X.Name</code>, <code>Expected.X.Value</code>, or <code>Expected.X.Exists</code>. /// </important> /// <para> /// You can execute multiple <code>BatchPutAttributes</code> operations and other operations /// in parallel. However, large numbers of concurrent <code>BatchPutAttributes</code> /// calls can result in Service Unavailable (503) responses. /// </para> /// /// <para> /// The following limitations are enforced for this operation: <ul> <li>256 attribute /// name-value pairs per item</li> <li>1 MB request size</li> <li>1 billion attributes /// per domain</li> <li>10 GB of total user data storage per domain</li> <li>25 item limit /// per <code>BatchPutAttributes</code> operation</li> </ul> /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchPutAttributes service method.</param> /// /// <returns>The response from the BatchPutAttributes service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.DuplicateItemNameException"> /// The item name was specified more than once. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberDomainAttributesExceededException"> /// Too many attributes in this domain. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberDomainBytesExceededException"> /// Too many bytes in this domain. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberItemAttributesExceededException"> /// Too many attributes in this item. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberSubmittedAttributesExceededException"> /// Too many attributes exist in a single call. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberSubmittedItemsExceededException"> /// Too many items exist in a single call. /// </exception> public BatchPutAttributesResponse BatchPutAttributes(BatchPutAttributesRequest request) { var marshaller = new BatchPutAttributesRequestMarshaller(); var unmarshaller = BatchPutAttributesResponseUnmarshaller.Instance; return Invoke<BatchPutAttributesRequest,BatchPutAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the BatchPutAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the BatchPutAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<BatchPutAttributesResponse> BatchPutAttributesAsync(BatchPutAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new BatchPutAttributesRequestMarshaller(); var unmarshaller = BatchPutAttributesResponseUnmarshaller.Instance; return InvokeAsync<BatchPutAttributesRequest,BatchPutAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateDomain /// <summary> /// The <code>CreateDomain</code> operation creates a new domain. The domain name should /// be unique among the domains associated with the Access Key ID provided in the request. /// The <code>CreateDomain</code> operation may take 10 or more seconds to complete. /// /// /// <para> /// The client can create up to 100 domains per account. /// </para> /// /// <para> /// If the client requires additional domains, go to <a href="http://aws.amazon.com/contact-us/simpledb-limit-request/"> /// http://aws.amazon.com/contact-us/simpledb-limit-request/</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDomain service method.</param> /// /// <returns>The response from the CreateDomain service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberDomainsExceededException"> /// Too many domains exist per this account. /// </exception> public CreateDomainResponse CreateDomain(CreateDomainRequest request) { var marshaller = new CreateDomainRequestMarshaller(); var unmarshaller = CreateDomainResponseUnmarshaller.Instance; return Invoke<CreateDomainRequest,CreateDomainResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateDomainResponse> CreateDomainAsync(CreateDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateDomainRequestMarshaller(); var unmarshaller = CreateDomainResponseUnmarshaller.Instance; return InvokeAsync<CreateDomainRequest,CreateDomainResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteAttributes /// <summary> /// Deletes one or more attributes associated with an item. If all attributes of the /// item are deleted, the item is deleted. /// /// /// <para> /// <code>DeleteAttributes</code> is an idempotent operation; running it multiple times /// on the same item or attribute does not result in an error response. /// </para> /// /// <para> /// Because Amazon SimpleDB makes multiple copies of item data and uses an eventual consistency /// update model, performing a <a>GetAttributes</a> or <a>Select</a> operation (read) /// immediately after a <code>DeleteAttributes</code> or <a>PutAttributes</a> operation /// (write) might not return updated item data. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteAttributes service method.</param> /// /// <returns>The response from the DeleteAttributes service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.AttributeDoesNotExistException"> /// The specified attribute does not exist. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> public DeleteAttributesResponse DeleteAttributes(DeleteAttributesRequest request) { var marshaller = new DeleteAttributesRequestMarshaller(); var unmarshaller = DeleteAttributesResponseUnmarshaller.Instance; return Invoke<DeleteAttributesRequest,DeleteAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteAttributesResponse> DeleteAttributesAsync(DeleteAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteAttributesRequestMarshaller(); var unmarshaller = DeleteAttributesResponseUnmarshaller.Instance; return InvokeAsync<DeleteAttributesRequest,DeleteAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteDomain /// <summary> /// The <code>DeleteDomain</code> operation deletes a domain. Any items (and their attributes) /// in the domain are deleted as well. The <code>DeleteDomain</code> operation might take /// 10 or more seconds to complete. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDomain service method.</param> /// /// <returns>The response from the DeleteDomain service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> public DeleteDomainResponse DeleteDomain(DeleteDomainRequest request) { var marshaller = new DeleteDomainRequestMarshaller(); var unmarshaller = DeleteDomainResponseUnmarshaller.Instance; return Invoke<DeleteDomainRequest,DeleteDomainResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteDomainResponse> DeleteDomainAsync(DeleteDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteDomainRequestMarshaller(); var unmarshaller = DeleteDomainResponseUnmarshaller.Instance; return InvokeAsync<DeleteDomainRequest,DeleteDomainResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DomainMetadata /// <summary> /// Returns information about the domain, including when the domain was created, the /// number of items and attributes in the domain, and the size of the attribute names /// and values. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DomainMetadata service method.</param> /// /// <returns>The response from the DomainMetadata service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> public DomainMetadataResponse DomainMetadata(DomainMetadataRequest request) { var marshaller = new DomainMetadataRequestMarshaller(); var unmarshaller = DomainMetadataResponseUnmarshaller.Instance; return Invoke<DomainMetadataRequest,DomainMetadataResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DomainMetadata operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DomainMetadata operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DomainMetadataResponse> DomainMetadataAsync(DomainMetadataRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DomainMetadataRequestMarshaller(); var unmarshaller = DomainMetadataResponseUnmarshaller.Instance; return InvokeAsync<DomainMetadataRequest,DomainMetadataResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetAttributes /// <summary> /// Returns all of the attributes associated with the specified item. Optionally, the /// attributes returned can be limited to one or more attributes by specifying an attribute /// name parameter. /// /// /// <para> /// If the item does not exist on the replica that was accessed for this operation, an /// empty set is returned. The system does not return an error as it cannot guarantee /// the item does not exist on other replicas. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetAttributes service method.</param> /// /// <returns>The response from the GetAttributes service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> public GetAttributesResponse GetAttributes(GetAttributesRequest request) { var marshaller = new GetAttributesRequestMarshaller(); var unmarshaller = GetAttributesResponseUnmarshaller.Instance; return Invoke<GetAttributesRequest,GetAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetAttributesResponse> GetAttributesAsync(GetAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetAttributesRequestMarshaller(); var unmarshaller = GetAttributesResponseUnmarshaller.Instance; return InvokeAsync<GetAttributesRequest,GetAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListDomains /// <summary> /// The <code>ListDomains</code> operation lists all domains associated with the Access /// Key ID. It returns domain names up to the limit set by <a href="#MaxNumberOfDomains">MaxNumberOfDomains</a>. /// A <a href="#NextToken">NextToken</a> is returned if there are more than <code>MaxNumberOfDomains</code> /// domains. Calling <code>ListDomains</code> successive times with the <code>NextToken</code> /// provided by the operation returns up to <code>MaxNumberOfDomains</code> more domain /// names with each successive operation call. /// </summary> /// /// <returns>The response from the ListDomains service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.InvalidNextTokenException"> /// The specified NextToken is not valid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public ListDomainsResponse ListDomains() { return ListDomains(new ListDomainsRequest()); } /// <summary> /// The <code>ListDomains</code> operation lists all domains associated with the Access /// Key ID. It returns domain names up to the limit set by <a href="#MaxNumberOfDomains">MaxNumberOfDomains</a>. /// A <a href="#NextToken">NextToken</a> is returned if there are more than <code>MaxNumberOfDomains</code> /// domains. Calling <code>ListDomains</code> successive times with the <code>NextToken</code> /// provided by the operation returns up to <code>MaxNumberOfDomains</code> more domain /// names with each successive operation call. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDomains service method.</param> /// /// <returns>The response from the ListDomains service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.InvalidNextTokenException"> /// The specified NextToken is not valid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public ListDomainsResponse ListDomains(ListDomainsRequest request) { var marshaller = new ListDomainsRequestMarshaller(); var unmarshaller = ListDomainsResponseUnmarshaller.Instance; return Invoke<ListDomainsRequest,ListDomainsResponse>(request, marshaller, unmarshaller); } /// <summary> /// The <code>ListDomains</code> operation lists all domains associated with the Access /// Key ID. It returns domain names up to the limit set by <a href="#MaxNumberOfDomains">MaxNumberOfDomains</a>. /// A <a href="#NextToken">NextToken</a> is returned if there are more than <code>MaxNumberOfDomains</code> /// domains. Calling <code>ListDomains</code> successive times with the <code>NextToken</code> /// provided by the operation returns up to <code>MaxNumberOfDomains</code> more domain /// names with each successive operation call. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListDomains service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.InvalidNextTokenException"> /// The specified NextToken is not valid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public Task<ListDomainsResponse> ListDomainsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return ListDomainsAsync(new ListDomainsRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the ListDomains operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDomains operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListDomainsResponse> ListDomainsAsync(ListDomainsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListDomainsRequestMarshaller(); var unmarshaller = ListDomainsResponseUnmarshaller.Instance; return InvokeAsync<ListDomainsRequest,ListDomainsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region PutAttributes /// <summary> /// The PutAttributes operation creates or replaces attributes in an item. The client /// may specify new attributes using a combination of the <code>Attribute.X.Name</code> /// and <code>Attribute.X.Value</code> parameters. The client specifies the first attribute /// by the parameters <code>Attribute.0.Name</code> and <code>Attribute.0.Value</code>, /// the second attribute by the parameters <code>Attribute.1.Name</code> and <code>Attribute.1.Value</code>, /// and so on. /// /// /// <para> /// Attributes are uniquely identified in an item by their name/value combination. For /// example, a single item can have the attributes <code>{ "first_name", "first_value" /// }</code> and <code>{ "first_name", second_value" }</code>. However, it cannot have /// two attribute instances where both the <code>Attribute.X.Name</code> and <code>Attribute.X.Value</code> /// are the same. /// </para> /// /// <para> /// Optionally, the requestor can supply the <code>Replace</code> parameter for each /// individual attribute. Setting this value to <code>true</code> causes the new attribute /// value to replace the existing attribute value(s). For example, if an item has the /// attributes <code>{ 'a', '1' }</code>, <code>{ 'b', '2'}</code> and <code>{ 'b', '3' /// }</code> and the requestor calls <code>PutAttributes</code> using the attributes <code>{ /// 'b', '4' }</code> with the <code>Replace</code> parameter set to true, the final attributes /// of the item are changed to <code>{ 'a', '1' }</code> and <code>{ 'b', '4' }</code>, /// which replaces the previous values of the 'b' attribute with the new value. /// </para> /// /// <para> /// You cannot specify an empty string as an attribute name. /// </para> /// /// <para> /// Because Amazon SimpleDB makes multiple copies of client data and uses an eventual /// consistency update model, an immediate <a>GetAttributes</a> or <a>Select</a> operation /// (read) immediately after a <a>PutAttributes</a> or <a>DeleteAttributes</a> operation /// (write) might not return the updated data. /// </para> /// /// <para> /// The following limitations are enforced for this operation: <ul> <li>256 total attribute /// name-value pairs per item</li> <li>One billion attributes per domain</li> <li>10 GB /// of total user data storage per domain</li> </ul> /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutAttributes service method.</param> /// /// <returns>The response from the PutAttributes service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.AttributeDoesNotExistException"> /// The specified attribute does not exist. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberDomainAttributesExceededException"> /// Too many attributes in this domain. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberDomainBytesExceededException"> /// Too many bytes in this domain. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberItemAttributesExceededException"> /// Too many attributes in this item. /// </exception> public PutAttributesResponse PutAttributes(PutAttributesRequest request) { var marshaller = new PutAttributesRequestMarshaller(); var unmarshaller = PutAttributesResponseUnmarshaller.Instance; return Invoke<PutAttributesRequest,PutAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<PutAttributesResponse> PutAttributesAsync(PutAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new PutAttributesRequestMarshaller(); var unmarshaller = PutAttributesResponseUnmarshaller.Instance; return InvokeAsync<PutAttributesRequest,PutAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region Select /// <summary> /// The <code>Select</code> operation returns a set of attributes for <code>ItemNames</code> /// that match the select expression. <code>Select</code> is similar to the standard SQL /// SELECT statement. /// /// /// <para> /// The total size of the response cannot exceed 1 MB in total size. Amazon SimpleDB /// automatically adjusts the number of items returned per page to enforce this limit. /// For example, if the client asks to retrieve 2500 items, but each individual item is /// 10 kB in size, the system returns 100 items and an appropriate <code>NextToken</code> /// so the client can access the next page of results. /// </para> /// /// <para> /// For information on how to construct select expressions, see Using Select to Create /// Amazon SimpleDB Queries in the Developer Guide. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the Select service method.</param> /// /// <returns>The response from the Select service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.InvalidNextTokenException"> /// The specified NextToken is not valid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidNumberPredicatesException"> /// Too many predicates exist in the query expression. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidNumberValueTestsException"> /// Too many predicates exist in the query expression. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidQueryExpressionException"> /// The specified query expression syntax is not valid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.RequestTimeoutException"> /// A timeout occurred when attempting to query the specified domain with specified query /// expression. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.TooManyRequestedAttributesException"> /// Too many attributes requested. /// </exception> public SelectResponse Select(SelectRequest request) { var marshaller = new SelectRequestMarshaller(); var unmarshaller = SelectResponseUnmarshaller.Instance; return Invoke<SelectRequest,SelectResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the Select operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Select operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<SelectResponse> SelectAsync(SelectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new SelectRequestMarshaller(); var unmarshaller = SelectResponseUnmarshaller.Instance; return InvokeAsync<SelectRequest,SelectResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
/* * Copyright 2012-2017 Scott MacDonald * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using DungeonCrawler.Actions; using Forge; using Forge.Actors; using Forge.Input; using Forge.GameObjects; using Forge.Graphics; using Forge.Content; using Forge.Tilemaps; using DungeonCrawler.WorldGeneration; using DungeonCrawler.Levels; using DungeonCrawler.Blueprints; namespace DungeonCrawler { /// <summary> /// This is the main class for Dungeon Crawler. It is responsible for running the game loop, /// responding to external events and managing content loading/unloading. /// </summary> public class DungeonCrawlerClient : Microsoft.Xna.Framework.Game { enum InputAction { ExitGame, PrintDebugInfo, Move, MoveCamera, MeleeAttack, RangedAttack, CastSpell } private readonly GraphicsDeviceManager mGraphicsDevice; private GameObject mPlayer; private bool mEnemySpawningEnabled = true; private Random mWorldRandom = new Random(); private IGameRenderer mRenderer; private DungeonCrawlerBlueprintFactory mGameObjectFactory; private GameScene mCurrentScene; private DungeonLevel mCurrentLevel; private readonly InputManager<InputAction> mInputManager = new InputManager<InputAction>(); int mEnemyCount = 0; bool mFirstSpawn = true; TimeSpan mNextSpawnTime = TimeSpan.Zero; public new IContentManager Content { get; private set; } /// <summary> /// Constructor. /// </summary> public DungeonCrawlerClient(IContentManager contentManager) { if (contentManager == null) { throw new ArgumentNullException(nameof(contentManager)); } Content = contentManager; // TODO: Provide game renderer as input to constructor. mGraphicsDevice = new GraphicsDeviceManager( this ); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // Set display size. mRenderer = new GameRenderer(mGraphicsDevice); mRenderer.Resize(800, 600); // Configure legacy XNA content loader. base.Content = new Microsoft.Xna.Framework.Content.ContentManager(Services); base.Content.RootDirectory = "Content"; // TODO: Make configurable via content container. Content.XnaContentManager = base.Content; // Initialize systems. var debugFont = Content.Load<SpriteFont>(Path.Combine("fonts", "System10.xnb")).Result; var debugOverlay = new StandardDebugOverlay(debugFont); Globals.Initialize( debugOverlay, new Forge.Settings.ForgeSettings()); Screen.Initialize( mGraphicsDevice.GraphicsDevice ); // Initialize input system with default settings. mInputManager.AddAction( InputAction.ExitGame, Keys.Escape ); mInputManager.AddAction( InputAction.PrintDebugInfo, Keys.F2 ); mInputManager.AddAction( InputAction.MeleeAttack, Keys.Space ); mInputManager.AddAction( InputAction.RangedAttack, Keys.E ); mInputManager.AddAction( InputAction.CastSpell, Keys.Q ); mInputManager.AddDirectionalAction( InputAction.Move, Keys.W, DirectionName.North ); mInputManager.AddDirectionalAction( InputAction.Move, Keys.D, DirectionName.East ); mInputManager.AddDirectionalAction( InputAction.Move, Keys.S, DirectionName.South ); mInputManager.AddDirectionalAction( InputAction.Move, Keys.A, DirectionName.West ); mInputManager.AddDirectionalAction(InputAction.MoveCamera, Keys.I, DirectionName.North); mInputManager.AddDirectionalAction(InputAction.MoveCamera, Keys.L, DirectionName.East); mInputManager.AddDirectionalAction(InputAction.MoveCamera, Keys.K, DirectionName.South); mInputManager.AddDirectionalAction(InputAction.MoveCamera, Keys.J, DirectionName.West); // Let XNA engine initialize last. base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new level. mCurrentLevel = GenerateMap(100, 100); mCurrentScene = new GameScene(mCurrentLevel.TileMap); mGameObjectFactory = new DungeonCrawlerBlueprintFactory(Content, mCurrentScene); // Spawn player into level. var position = mCurrentLevel.TileMap.GetWorldPositionForTile(mCurrentLevel.StairsUpPoint); mPlayer = mGameObjectFactory.Spawn(BlueprintNames.Player, "Player", position).Result; // TODO: async support. // Spawn a bunch of skeletons to get started. for (int i = 0; i < 100; i++) { SpawnSkeleton(); } // Create a follow camera to follow the player. mCurrentScene.MainCamera = new FollowCamera(new SizeF(Screen.Width, Screen.Height), mPlayer); // Now that we have loaded the game's contents, we should force a garbage collection // before proceeding to play mode. GC.Collect(); } /// <summary> /// TEMP HACK /// </summary> private DungeonLevel GenerateMap(int cols, int rows) { const int TileSize = 32; // Load tileset. // TODO: Load this as a content item. var tileAtlas = Content.Load<Texture2D>("tiles/dg_dungeon32.png").Result; var tileset = new TileSet(tileAtlas, TileSize, TileSize); tileset.Add(new TileDefinition(0, "void", 5 * TileSize, 6 * TileSize)); tileset.Add(new TileDefinition(1, "wall", 0 * TileSize, 3 * TileSize)); tileset.Add(new TileDefinition(2, "floor", 6 * TileSize, 5 * TileSize)); tileset.Add(new TileDefinition(3, "door", 3 * TileSize, 0 * TileSize)); tileset[0].SetIsVoid(true); tileset[1].SetIsWall(true); tileset[2].SetIsFloor(true); // Random generate a map. var generator = new DungeonGenerator(tileset); generator.Void = tileset[0]; generator.Wall = tileset[1]; generator.Floor = tileset[2]; generator.Doorway = tileset[3]; generator.RoomGenerators.Add(new RoomGenerator() { FloorTile = generator.Floor, WallTile = generator.Wall, MinWidth = 4, MaxWidth = 16, MinHeight = 4, MaxHeight = 16 }); return generator.Generate(cols, rows); } private void SpawnSkeleton() { // Pick a spot to place the skeleton enemy. // TODO: Check if location is clear before spawning! var mapWidth = mCurrentScene.Tilemap.Width - 128; var mapHeight = mCurrentScene.Tilemap.Height - 128; var spawnIndex = mEnemyCount % mCurrentLevel.SpawnPoints.Count; var position = mCurrentLevel.TileMap.GetWorldPositionForTile(mCurrentLevel.SpawnPoints[spawnIndex]); // Spawn the skeleton enemy. var skeleton = mGameObjectFactory.Spawn(BlueprintNames.Skeleton, "Skeleton", position); // Add the newly spawned skeleton to our list of enemies. // TODO: Temp hack, should not be tracked this way. mEnemyCount += 1; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update( GameTime gameTime ) { // Allow game play systems to perform any pre-update logic that might be needed Globals.Debug.PreUpdate(gameTime); // Perform any requested actions based on user input. mInputManager.Update(gameTime.TotalGameTime.TotalSeconds, gameTime.ElapsedGameTime.TotalSeconds); if ( mInputManager.WasTriggered( InputAction.ExitGame ) ) { Exit(); } // Player movement. var playerActor = mPlayer.Get<ActorComponent>(); var playerMovement = mInputManager.GetAxis(InputAction.Move); if (playerMovement.LengthSquared > 0.01) { playerActor.Move(playerMovement, 125.0f); } // Camera movement. var cameraMovement = mInputManager.GetAxis(InputAction.MoveCamera); if (cameraMovement.LengthSquared > 0.01) { mCurrentScene.MainCamera.Translate(cameraMovement * 8.0f); } // Player actions. if ( mInputManager.WasTriggered( InputAction.MeleeAttack ) ) { playerActor.Perform( new ActionSlashAttack() ); } else if ( mInputManager.WasTriggered( InputAction.RangedAttack ) ) { playerActor.Perform( new ActionRangedAttack() ); } else if ( mInputManager.WasTriggered( InputAction.CastSpell ) ) { playerActor.Perform(new ActionCastSpell()); } // Spawn some stuff if ( mNextSpawnTime <= gameTime.TotalGameTime && mEnemyCount < 32 ) { if ((mWorldRandom.NextDouble() < 0.75 || mFirstSpawn) && mEnemySpawningEnabled) { //SpawnSkeleton(); mFirstSpawn = false; } mNextSpawnTime = gameTime.TotalGameTime.Add( TimeSpan.FromSeconds( 1.0 ) ); } mCurrentScene.Update(gameTime); base.Update( gameTime ); // Post update mInputManager.ClearState(); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { mRenderer.StartDrawing(clearScreen: true); mCurrentScene.Draw(gameTime, mRenderer); mRenderer.FinishDrawing(); Globals.Debug.Draw(gameTime, mRenderer); base.Draw(gameTime); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** Class: Stack ** ** Purpose: Represents a simple last-in-first-out (LIFO) ** non-generic collection of objects. ** ** =============================================================================*/ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections { // A simple stack of objects. Internally it is implemented as an array, // so Push can be O(n). Pop is O(1). [DebuggerTypeProxy(typeof(System.Collections.Stack.StackDebugView))] [DebuggerDisplay("Count = {Count}")] public class Stack : ICollection { private Object[] _array; // Storage for stack elements [ContractPublicPropertyName("Count")] private int _size; // Number of items in the stack. private int _version; // Used to keep enumerator in sync w/ collection. private Object _syncRoot; private const int _defaultCapacity = 10; public Stack() { _array = new Object[_defaultCapacity]; _size = 0; _version = 0; } // Create a stack with a specific initial capacity. The initial capacity // must be a non-negative number. public Stack(int initialCapacity) { if (initialCapacity < 0) throw new ArgumentOutOfRangeException("initialCapacity", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (initialCapacity < _defaultCapacity) initialCapacity = _defaultCapacity; // Simplify doubling logic in Push. _array = new Object[initialCapacity]; _size = 0; _version = 0; } // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. // public Stack(ICollection col) : this((col == null ? 32 : col.Count)) { if (col == null) throw new ArgumentNullException("col"); Contract.EndContractBlock(); IEnumerator en = col.GetEnumerator(); while (en.MoveNext()) Push(en.Current); } public virtual int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return _size; } } public virtual bool IsSynchronized { get { return false; } } public virtual Object SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all Objects from the Stack. public virtual void Clear() { Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; _version++; } public virtual Object Clone() { Contract.Ensures(Contract.Result<Object>() != null); Stack s = new Stack(_size); s._size = _size; Array.Copy(_array, 0, s._array, 0, _size); s._version = _version; return s; } public virtual bool Contains(Object obj) { int count = _size; while (count-- > 0) { if (obj == null) { if (_array[count] == null) return true; } else if (_array[count] != null && _array[count].Equals(obj)) { return true; } } return false; } // Copies the stack into an array. public virtual void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException("array"); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0) throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < _size) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); int i = 0; object[] objArray = array as object[]; if (objArray != null) { while (i < _size) { objArray[i + index] = _array[_size - i - 1]; i++; } } else { while (i < _size) { array.SetValue(_array[_size - i - 1], i + index); i++; } } } // Returns an IEnumerator for this Stack. public virtual IEnumerator GetEnumerator() { Contract.Ensures(Contract.Result<IEnumerator>() != null); return new StackEnumerator(this); } // Returns the top object on the stack without removing it. If the stack // is empty, Peek throws an InvalidOperationException. public virtual Object Peek() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); Contract.EndContractBlock(); return _array[_size - 1]; } // Pops an item from the top of the stack. If the stack is empty, Pop // throws an InvalidOperationException. public virtual Object Pop() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); //Contract.Ensures(Count == Contract.OldValue(Count) - 1); Contract.EndContractBlock(); _version++; Object obj = _array[--_size]; _array[_size] = null; // Free memory quicker. return obj; } // Pushes an item to the top of the stack. // public virtual void Push(Object obj) { //Contract.Ensures(Count == Contract.OldValue(Count) + 1); if (_size == _array.Length) { Object[] newArray = new Object[2 * _array.Length]; Array.Copy(_array, 0, newArray, 0, _size); _array = newArray; } _array[_size++] = obj; _version++; } // Returns a synchronized Stack. // public static Stack Synchronized(Stack stack) { if (stack == null) throw new ArgumentNullException("stack"); Contract.Ensures(Contract.Result<Stack>() != null); Contract.EndContractBlock(); return new SyncStack(stack); } // Copies the Stack to an array, in the same order Pop would return the items. public virtual Object[] ToArray() { Contract.Ensures(Contract.Result<Object[]>() != null); if (_size == 0) return Array.Empty<Object>(); Object[] objArray = new Object[_size]; int i = 0; while (i < _size) { objArray[i] = _array[_size - i - 1]; i++; } return objArray; } private class SyncStack : Stack { private Stack _s; private Object _root; internal SyncStack(Stack stack) { _s = stack; _root = stack.SyncRoot; } public override bool IsSynchronized { get { return true; } } public override Object SyncRoot { get { return _root; } } public override int Count { get { lock (_root) { return _s.Count; } } } public override bool Contains(Object obj) { lock (_root) { return _s.Contains(obj); } } public override Object Clone() { lock (_root) { return new SyncStack((Stack)_s.Clone()); } } public override void Clear() { lock (_root) { _s.Clear(); } } public override void CopyTo(Array array, int arrayIndex) { lock (_root) { _s.CopyTo(array, arrayIndex); } } public override void Push(Object value) { lock (_root) { _s.Push(value); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10. public override Object Pop() { lock (_root) { return _s.Pop(); } } public override IEnumerator GetEnumerator() { lock (_root) { return _s.GetEnumerator(); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition public override Object Peek() { lock (_root) { return _s.Peek(); } } public override Object[] ToArray() { lock (_root) { return _s.ToArray(); } } } private class StackEnumerator : IEnumerator { private Stack _stack; private int _index; private int _version; private Object _currentElement; internal StackEnumerator(Stack stack) { _stack = stack; _version = _stack._version; _index = -2; _currentElement = null; } public virtual bool MoveNext() { bool retval; if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index == -2) { // First call to enumerator. _index = _stack._size - 1; retval = (_index >= 0); if (retval) _currentElement = _stack._array[_index]; return retval; } if (_index == -1) { // End of enumeration. return false; } retval = (--_index >= 0); if (retval) _currentElement = _stack._array[_index]; else _currentElement = null; return retval; } public virtual Object Current { get { if (_index == -2) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); if (_index == -1) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); return _currentElement; } } public virtual void Reset() { if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = -2; _currentElement = null; } } internal class StackDebugView { private Stack _stack; public StackDebugView(Stack stack) { if (stack == null) throw new ArgumentNullException("stack"); Contract.EndContractBlock(); _stack = stack; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public Object[] Items { get { return _stack.ToArray(); } } } } }
// 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.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SolutionSize; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Storage { /// <summary> /// A service that enables storing and retrieving of information associated with solutions, /// projects or documents across runtime sessions. /// </summary> internal abstract partial class AbstractPersistentStorageService : IPersistentStorageService { protected readonly IOptionService OptionService; private readonly SolutionSizeTracker _solutionSizeTracker; private readonly object _lookupAccessLock; private readonly Dictionary<string, AbstractPersistentStorage> _lookup; private readonly bool _testing; private string _lastSolutionPath; private SolutionId _primarySolutionId; private AbstractPersistentStorage _primarySolutionStorage; protected AbstractPersistentStorageService( IOptionService optionService, SolutionSizeTracker solutionSizeTracker) { OptionService = optionService; _solutionSizeTracker = solutionSizeTracker; _lookupAccessLock = new object(); _lookup = new Dictionary<string, AbstractPersistentStorage>(); _lastSolutionPath = null; _primarySolutionId = null; _primarySolutionStorage = null; } protected AbstractPersistentStorageService(IOptionService optionService, bool testing) : this(optionService, solutionSizeTracker: null) { _testing = true; } protected abstract string GetDatabaseFilePath(string workingFolderPath); protected abstract AbstractPersistentStorage OpenDatabase(Solution solution, string workingFolderPath, string databaseFilePath); protected abstract bool ShouldDeleteDatabase(Exception exception); public IPersistentStorage GetStorage(Solution solution) { if (!ShouldUseDatabase(solution)) { return NoOpPersistentStorage.Instance; } // can't use cached information if (!string.Equals(solution.FilePath, _lastSolutionPath, StringComparison.OrdinalIgnoreCase)) { // check whether the solution actually exist on disk if (!File.Exists(solution.FilePath)) { return NoOpPersistentStorage.Instance; } } // cache current result. _lastSolutionPath = solution.FilePath; // get working folder path var workingFolderPath = GetWorkingFolderPath(solution); if (workingFolderPath == null) { // we don't have place to save db file. don't use db return NoOpPersistentStorage.Instance; } return GetStorage(solution, workingFolderPath); } private IPersistentStorage GetStorage(Solution solution, string workingFolderPath) { lock (_lookupAccessLock) { // see whether we have something we can use if (_lookup.TryGetValue(solution.FilePath, out var storage)) { // previous attempt to create db storage failed. if (storage == null && !SolutionSizeAboveThreshold(solution)) { return NoOpPersistentStorage.Instance; } // everything seems right, use what we have if (storage?.WorkingFolderPath == workingFolderPath) { storage.AddRefUnsafe(); return storage; } } // either this is the first time, or working folder path has changed. // remove existing one _lookup.Remove(solution.FilePath); var dbFile = GetDatabaseFilePath(workingFolderPath); if (!File.Exists(dbFile) && !SolutionSizeAboveThreshold(solution)) { _lookup.Add(solution.FilePath, storage); return NoOpPersistentStorage.Instance; } // try create new one storage = TryCreatePersistentStorage(solution, workingFolderPath); _lookup.Add(solution.FilePath, storage); if (storage != null) { RegisterPrimarySolutionStorageIfNeeded(solution, storage); storage.AddRefUnsafe(); return storage; } return NoOpPersistentStorage.Instance; } } private bool ShouldUseDatabase(Solution solution) { if (_testing) { return true; } // we only use database for primary solution. (Ex, forked solution will not use database) if (solution.BranchId != solution.Workspace.PrimaryBranchId || solution.FilePath == null) { return false; } return true; } private bool SolutionSizeAboveThreshold(Solution solution) { if (_testing) { return true; } if (_solutionSizeTracker == null) { return false; } var size = _solutionSizeTracker.GetSolutionSize(solution.Workspace, solution.Id); var threshold = this.OptionService.GetOption(StorageOptions.SolutionSizeThreshold); return size >= threshold; } private void RegisterPrimarySolutionStorageIfNeeded(Solution solution, AbstractPersistentStorage storage) { if (_primarySolutionStorage != null || solution.Id != _primarySolutionId) { return; } // hold onto the primary solution when it is used the first time. _primarySolutionStorage = storage; storage.AddRefUnsafe(); } private string GetWorkingFolderPath(Solution solution) { if (_testing) { return Path.Combine(Path.GetDirectoryName(solution.FilePath), ".vs", Path.GetFileNameWithoutExtension(solution.FilePath)); } var locationService = solution.Workspace.Services.GetService<IPersistentStorageLocationService>(); return locationService?.GetStorageLocation(solution); } private AbstractPersistentStorage TryCreatePersistentStorage(Solution solution, string workingFolderPath) { // Attempt to create the database up to two times. The first time we may encounter // some sort of issue (like DB corruption). We'll then try to delete the DB and can // try to create it again. If we can't create it the second time, then there's nothing // we can do and we have to store things in memory. if (TryCreatePersistentStorage(solution, workingFolderPath, out var persistentStorage) || TryCreatePersistentStorage(solution, workingFolderPath, out persistentStorage)) { return persistentStorage; } // okay, can't recover, then use no op persistent service // so that things works old way (cache everything in memory) return null; } private bool TryCreatePersistentStorage( Solution solution, string workingFolderPath, out AbstractPersistentStorage persistentStorage) { persistentStorage = null; AbstractPersistentStorage database = null; var databaseFilePath = GetDatabaseFilePath(workingFolderPath); try { database = OpenDatabase(solution, workingFolderPath, databaseFilePath); database.Initialize(solution); persistentStorage = database; return true; } catch (Exception ex) { StorageDatabaseLogger.LogException(ex); if (database != null) { database.Close(); } if (ShouldDeleteDatabase(ex)) { // this was not a normal exception that we expected during DB open. // Report this so we can try to address whatever is causing this. FatalError.ReportWithoutCrash(ex); IOUtilities.PerformIO(() => Directory.Delete(Path.GetDirectoryName(databaseFilePath), recursive: true)); } return false; } } protected void Release(AbstractPersistentStorage storage) { lock (_lookupAccessLock) { if (storage.ReleaseRefUnsafe()) { _lookup.Remove(storage.SolutionFilePath); storage.Close(); } } } public void RegisterPrimarySolution(SolutionId solutionId) { // don't create database storage file right away. it will be // created when first C#/VB project is added lock (_lookupAccessLock) { Contract.ThrowIfTrue(_primarySolutionStorage != null); // just reset solutionId as long as there is no storage has created. _primarySolutionId = solutionId; } } public void UnregisterPrimarySolution(SolutionId solutionId, bool synchronousShutdown) { AbstractPersistentStorage storage = null; lock (_lookupAccessLock) { if (_primarySolutionId == null) { // primary solution is never registered or already unregistered Contract.ThrowIfTrue(_primarySolutionStorage != null); return; } Contract.ThrowIfFalse(_primarySolutionId == solutionId); _primarySolutionId = null; if (_primarySolutionStorage == null) { // primary solution is registered but no C#/VB project was added return; } storage = _primarySolutionStorage; _primarySolutionStorage = null; } if (storage != null) { if (synchronousShutdown) { // dispose storage outside of the lock storage.Dispose(); } else { // make it to shutdown asynchronously Task.Run(() => storage.Dispose()); } } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Threading.Tasks; using Rimss.GraphicsProcessing.Palette.ColorCaches.Common; using Rimss.GraphicsProcessing.Palette.Ditherers; using Rimss.GraphicsProcessing.Palette.Extensions; using Rimss.GraphicsProcessing.Palette.PathProviders; using Rimss.GraphicsProcessing.Palette.Quantizers; namespace Rimss.GraphicsProcessing.Palette.Helpers { public class ImageBuffer : IDisposable { #region | Fields | private Int32[] fastBitX; private Int32[] fastByteX; private Int32[] fastY; private readonly Bitmap bitmap; private readonly BitmapData bitmapData; private readonly ImageLockMode lockMode; private List<Color> cachedPalette; #endregion #region | Delegates | public delegate Boolean ProcessPixelFunction(Pixel pixel); public delegate Boolean ProcessPixelAdvancedFunction(Pixel pixel, ImageBuffer buffer); public delegate Boolean TransformPixelFunction(Pixel sourcePixel, Pixel targetPixel); public delegate Boolean TransformPixelAdvancedFunction(Pixel sourcePixel, Pixel targetPixel, ImageBuffer sourceBuffer, ImageBuffer targetBuffer); #endregion #region | Properties | public Int32 Width { get; private set; } public Int32 Height { get; private set; } public Int32 Size { get; private set; } public Int32 Stride { get; private set; } public Int32 BitDepth { get; private set; } public Int32 BytesPerPixel { get; private set; } public Boolean IsIndexed { get; private set; } public PixelFormat PixelFormat { get; private set; } #endregion #region | Calculated properties | /// <summary> /// Gets a value indicating whether this buffer can be read. /// </summary> /// <value> /// <c>true</c> if this instance can read; otherwise, <c>false</c>. /// </value> public Boolean CanRead { get { return lockMode == ImageLockMode.ReadOnly || lockMode == ImageLockMode.ReadWrite; } } /// <summary> /// Gets a value indicating whether this buffer can written to. /// </summary> /// <value> /// <c>true</c> if this instance can write; otherwise, <c>false</c>. /// </value> public Boolean CanWrite { get { return lockMode == ImageLockMode.WriteOnly || lockMode == ImageLockMode.ReadWrite; } } /// <summary> /// Gets or sets the palette. /// </summary> public List<Color> Palette { get { return UpdatePalette(); } set { bitmap.SetPalette(value); cachedPalette = value; } } #endregion #region | Constructors | /// <summary> /// Initializes a new instance of the <see cref="ImageBuffer"/> class. /// </summary> public ImageBuffer(Image bitmap, ImageLockMode lockMode) : this((Bitmap) bitmap, lockMode) { } /// <summary> /// Initializes a new instance of the <see cref="ImageBuffer"/> class. /// </summary> public ImageBuffer(Bitmap bitmap, ImageLockMode lockMode) { // locks the image data this.bitmap = bitmap; this.lockMode = lockMode; // gathers the informations Width = bitmap.Width; Height = bitmap.Height; PixelFormat = bitmap.PixelFormat; IsIndexed = PixelFormat.IsIndexed(); BitDepth = PixelFormat.GetBitDepth(); BytesPerPixel = Math.Max(1, BitDepth >> 3); // determines the bounds of an image, and locks the data in a specified mode Rectangle bounds = Rectangle.FromLTRB(0, 0, Width, Height); // locks the bitmap data lock (bitmap) bitmapData = bitmap.LockBits(bounds, lockMode, PixelFormat); // creates internal buffer Stride = bitmapData.Stride < 0 ? -bitmapData.Stride : bitmapData.Stride; Size = Stride*Height; // precalculates the offsets Precalculate(); } #endregion #region | Maintenance methods | private void Precalculate() { fastBitX = new Int32[Width]; fastByteX = new Int32[Width]; fastY = new Int32[Height]; // precalculates the x-coordinates for (Int32 x = 0; x < Width; x++) { fastBitX[x] = x*BitDepth; fastByteX[x] = fastBitX[x] >> 3; fastBitX[x] = fastBitX[x] % 8; } // precalculates the y-coordinates for (Int32 y = 0; y < Height; y++) { fastY[y] = y * bitmapData.Stride; } } public Int32 GetBitOffset(Int32 x) { return fastBitX[x]; } public Byte[] Copy() { // transfers whole image to a working memory Byte[] result = new Byte[Size]; Marshal.Copy(bitmapData.Scan0, result, 0, Size); // returns the backup return result; } public void Paste(Byte[] buffer) { // commits the data to a bitmap Marshal.Copy(buffer, 0, bitmapData.Scan0, Size); } #endregion #region | Pixel read methods | public void ReadPixel(Pixel pixel, Byte[] buffer = null) { // determines pixel offset at [x, y] Int32 offset = fastByteX[pixel.X] + fastY[pixel.Y]; // reads the pixel from a bitmap if (buffer == null) { pixel.ReadRawData(bitmapData.Scan0 + offset); } else // reads the pixel from a buffer { pixel.ReadData(buffer, offset); } } public Int32 GetIndexFromPixel(Pixel pixel) { Int32 result; // determines whether the format is indexed if (IsIndexed) { result = pixel.Index; } else // not possible to get index from a non-indexed format { String message = string.Format("Cannot retrieve index for a non-indexed format. Please use Color (or Value) property instead."); throw new NotSupportedException(message); } return result; } public Color GetColorFromPixel(Pixel pixel) { Color result; // determines whether the format is indexed if (pixel.IsIndexed) { Int32 index = pixel.Index; result = pixel.Parent.GetPaletteColor(index); } else // gets color from a non-indexed format { result = pixel.Color; } // returns the found color return result; } public Int32 ReadIndexUsingPixel(Pixel pixel, Byte[] buffer = null) { // reads the pixel from bitmap/buffer ReadPixel(pixel, buffer); // returns the found color return GetIndexFromPixel(pixel); } public Color ReadColorUsingPixel(Pixel pixel, Byte[] buffer = null) { // reads the pixel from bitmap/buffer ReadPixel(pixel, buffer); // returns the found color return GetColorFromPixel(pixel); } public Int32 ReadIndexUsingPixelFrom(Pixel pixel, Int32 x, Int32 y, Byte[] buffer = null) { // redirects pixel -> [x, y] pixel.Update(x, y); // reads index from a bitmap/buffer using pixel, and stores it in the pixel return ReadIndexUsingPixel(pixel, buffer); } public Color ReadColorUsingPixelFrom(Pixel pixel, Int32 x, Int32 y, Byte[] buffer = null) { // redirects pixel -> [x, y] pixel.Update(x, y); // reads color from a bitmap/buffer using pixel, and stores it in the pixel return ReadColorUsingPixel(pixel, buffer); } #endregion #region | Pixel write methods | private void WritePixel(Pixel pixel, Byte[] buffer = null) { // determines pixel offset at [x, y] Int32 offset = fastByteX[pixel.X] + fastY[pixel.Y]; // writes the pixel to a bitmap if (buffer == null) { pixel.WriteRawData(bitmapData.Scan0 + offset); } else // writes the pixel to a buffer { pixel.WriteData(buffer, offset); } } public void SetIndexToPixel(Pixel pixel, Int32 index, Byte[] buffer = null) { // determines whether the format is indexed if (IsIndexed) { pixel.Index = (Byte) index; } else // cannot write color to an indexed format { String message = string.Format("Cannot set index for a non-indexed format. Please use Color (or Value) property instead."); throw new NotSupportedException(message); } } public void SetColorToPixel(Pixel pixel, Color color, IColorQuantizer quantizer) { // determines whether the format is indexed if (pixel.IsIndexed) { // last chance if quantizer is provided, use it if (quantizer != null) { Byte index = (Byte)quantizer.GetPaletteIndex(color, pixel.X, pixel.Y); pixel.Index = index; } else // cannot write color to an index format { String message = string.Format("Cannot retrieve color for an indexed format. Use GetPixelIndex() instead."); throw new NotSupportedException(message); } } else // sets color to a non-indexed format { pixel.Color = color; } } public void WriteIndexUsingPixel(Pixel pixel, Int32 index, Byte[] buffer = null) { // sets index to pixel (pixel's index is updated) SetIndexToPixel(pixel, index, buffer); // writes pixel to a bitmap/buffer WritePixel(pixel, buffer); } public void WriteColorUsingPixel(Pixel pixel, Color color, IColorQuantizer quantizer, Byte[] buffer = null) { // sets color to pixel (pixel is updated with color) SetColorToPixel(pixel, color, quantizer); // writes pixel to a bitmap/buffer WritePixel(pixel, buffer); } public void WriteIndexUsingPixelAt(Pixel pixel, Int32 x, Int32 y, Int32 index, Byte[] buffer = null) { // redirects pixel -> [x, y] pixel.Update(x, y); // writes color to bitmap/buffer using pixel WriteIndexUsingPixel(pixel, index, buffer); } public void WriteColorUsingPixelAt(Pixel pixel, Int32 x, Int32 y, Color color, IColorQuantizer quantizer, Byte[] buffer = null) { // redirects pixel -> [x, y] pixel.Update(x, y); // writes color to bitmap/buffer using pixel WriteColorUsingPixel(pixel, color, quantizer, buffer); } #endregion #region | Generic methods | private void ProcessInParallel(ICollection<Point> path, Action<LineTask> process, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(process, "process"); // updates the palette UpdatePalette(); // prepares parallel processing Double pointsPerTask = (1.0*path.Count)/parallelTaskCount; LineTask[] lineTasks = new LineTask[parallelTaskCount]; Double pointOffset = 0.0; // creates task for each batch of rows for (Int32 index = 0; index < parallelTaskCount; index++) { lineTasks[index] = new LineTask((Int32) pointOffset, (Int32) (pointOffset + pointsPerTask)); pointOffset += pointsPerTask; } // process the image in a parallel manner Parallel.ForEach(lineTasks, process); } #endregion #region | Processing methods | private void ProcessPerPixelBase(IList<Point> path, Delegate processingAction, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(path, "path"); Guard.CheckNull(processingAction, "processPixelFunction"); // determines mode Boolean isAdvanced = processingAction is ProcessPixelAdvancedFunction; // prepares the per pixel task Action<LineTask> processPerPixel = lineTask => { // initializes variables per task Pixel pixel = new Pixel(this); for (Int32 pathOffset = lineTask.StartOffset; pathOffset < lineTask.EndOffset; pathOffset++) { Point point = path[pathOffset]; Boolean allowWrite; // enumerates the pixel, and returns the control to the outside pixel.Update(point.X, point.Y); // when read is allowed, retrieves current value (in bytes) if (CanRead) ReadPixel(pixel); // process the pixel by custom user operation if (isAdvanced) { ProcessPixelAdvancedFunction processAdvancedFunction = (ProcessPixelAdvancedFunction) processingAction; allowWrite = processAdvancedFunction(pixel, this); } else // use simplified version with pixel parameter only { ProcessPixelFunction processFunction = (ProcessPixelFunction) processingAction; allowWrite = processFunction(pixel); } // when write is allowed, copies the value back to the row buffer if (CanWrite && allowWrite) WritePixel(pixel); } }; // processes image per pixel ProcessInParallel(path, processPerPixel, parallelTaskCount); } public void ProcessPerPixel(IList<Point> path, ProcessPixelFunction processPixelFunction, Int32 parallelTaskCount = 4) { ProcessPerPixelBase(path, processPixelFunction, parallelTaskCount); } public void ProcessPerPixelAdvanced(IList<Point> path, ProcessPixelAdvancedFunction processPixelAdvancedFunction, Int32 parallelTaskCount = 4) { ProcessPerPixelBase(path, processPixelAdvancedFunction, parallelTaskCount); } #endregion #region | Transformation functions | private void TransformPerPixelBase(ImageBuffer target, IList<Point> path, Delegate transformAction, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(path, "path"); Guard.CheckNull(target, "target"); Guard.CheckNull(transformAction, "transformAction"); // updates the palette UpdatePalette(); target.UpdatePalette(); // checks the dimensions if (Width != target.Width || Height != target.Height) { const String message = "Both images have to have the same dimensions."; throw new ArgumentOutOfRangeException(message); } // determines mode Boolean isAdvanced = transformAction is TransformPixelAdvancedFunction; // process the image in a parallel manner Action<LineTask> transformPerPixel = lineTask => { // creates individual pixel structures per task Pixel sourcePixel = new Pixel(this); Pixel targetPixel = new Pixel(target); // enumerates the pixels row by row for (Int32 pathOffset = lineTask.StartOffset; pathOffset < lineTask.EndOffset; pathOffset++) { Point point = path[pathOffset]; Boolean allowWrite; // enumerates the pixel, and returns the control to the outside sourcePixel.Update(point.X, point.Y); targetPixel.Update(point.X, point.Y); // when read is allowed, retrieves current value (in bytes) if (CanRead) ReadPixel(sourcePixel); if (target.CanRead) target.ReadPixel(targetPixel); // process the pixel by custom user operation if (isAdvanced) { TransformPixelAdvancedFunction transformAdvancedFunction = (TransformPixelAdvancedFunction) transformAction; allowWrite = transformAdvancedFunction(sourcePixel, targetPixel, this, target); } else // use simplified version with pixel parameters only { TransformPixelFunction transformFunction = (TransformPixelFunction) transformAction; allowWrite = transformFunction(sourcePixel, targetPixel); } // when write is allowed, copies the value back to the row buffer if (target.CanWrite && allowWrite) target.WritePixel(targetPixel); } }; // transforms image per pixel ProcessInParallel(path, transformPerPixel, parallelTaskCount); } public void TransformPerPixel(ImageBuffer target, IList<Point> path, TransformPixelFunction transformPixelFunction, Int32 parallelTaskCount = 4) { TransformPerPixelBase(target, path, transformPixelFunction, parallelTaskCount); } public void TransformPerPixelAdvanced(ImageBuffer target, IList<Point> path, TransformPixelAdvancedFunction transformPixelAdvancedFunction, Int32 parallelTaskCount = 4) { TransformPerPixelBase(target, path, transformPixelAdvancedFunction, parallelTaskCount); } #endregion #region | Scan colors methods | public void ScanColors(IColorQuantizer quantizer, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(quantizer, "quantizer"); // determines which method of color retrieval to use IList<Point> path = quantizer.GetPointPath(Width, Height); // use different scanning method depending whether the image format is indexed ProcessPixelFunction scanColors = pixel => { quantizer.AddColor(GetColorFromPixel(pixel), pixel.X, pixel.Y); return false; }; // performs the image scan, using a chosen method ProcessPerPixel(path, scanColors, parallelTaskCount); } public static void ScanImageColors(Image sourceImage, IColorQuantizer quantizer, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { source.ScanColors(quantizer, parallelTaskCount); } } #endregion #region | Synthetize palette methods | public List<Color> SynthetizePalette(IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(quantizer, "quantizer"); // Step 1 - prepares quantizer for another round quantizer.Prepare(this); // Step 2 - scans the source image for the colors ScanColors(quantizer, parallelTaskCount); // Step 3 - synthetises the palette, and returns the result return quantizer.GetPalette(colorCount); } public static List<Color> SynthetizeImagePalette(Image sourceImage, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { return source.SynthetizePalette(quantizer, colorCount, parallelTaskCount); } } #endregion #region | Quantize methods | public void Quantize(ImageBuffer target, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // performs the pure quantization wihout dithering Quantize(target, quantizer, null, colorCount, parallelTaskCount); } public void Quantize(ImageBuffer target, IColorQuantizer quantizer, IColorDitherer ditherer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(target, "target"); Guard.CheckNull(quantizer, "quantizer"); // initializes quantization parameters Boolean isTargetIndexed = target.PixelFormat.IsIndexed(); // step 1 - prepares the palettes List<Color> targetPalette = isTargetIndexed ? SynthetizePalette(quantizer, colorCount, parallelTaskCount) : null; // step 2 - updates the bitmap palette target.bitmap.SetPalette(targetPalette); target.UpdatePalette(true); // step 3 - prepares ditherer (optional) if (ditherer != null) ditherer.Prepare(quantizer, colorCount, this, target); // step 4 - prepares the quantization function TransformPixelFunction quantize = (sourcePixel, targetPixel) => { // reads the pixel color Color color = GetColorFromPixel(sourcePixel); // converts alpha to solid color color = QuantizationHelper.ConvertAlpha(color); // quantizes the pixel SetColorToPixel(targetPixel, color, quantizer); // marks pixel as processed by default Boolean result = true; // preforms inplace dithering (optional) if (ditherer != null && ditherer.IsInplace) { result = ditherer.ProcessPixel(sourcePixel, targetPixel); } // returns the result return result; }; // step 5 - generates the target image IList<Point> path = quantizer.GetPointPath(Width, Height); TransformPerPixel(target, path, quantize, parallelTaskCount); // step 6 - preforms non-inplace dithering (optional) if (ditherer != null && !ditherer.IsInplace) { Dither(target, ditherer, quantizer, colorCount, 1); } // step 7 - finishes the dithering (optional) if (ditherer != null) ditherer.Finish(); // step 8 - clean-up quantizer.Finish(); } public static Image QuantizeImage(ImageBuffer source, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // performs the pure quantization wihout dithering return QuantizeImage(source, quantizer, null, colorCount, parallelTaskCount); } public static Image QuantizeImage(ImageBuffer source, IColorQuantizer quantizer, IColorDitherer ditherer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); // creates a target bitmap in an appropriate format PixelFormat targetPixelFormat = Extend.GetFormatByColorCount(colorCount); Image result = new Bitmap(source.Width, source.Height, targetPixelFormat); // lock mode ImageLockMode lockMode = ditherer == null ? ImageLockMode.WriteOnly : ImageLockMode.ReadWrite; // wraps target image to a buffer using (ImageBuffer target = new ImageBuffer(result, lockMode)) { source.Quantize(target, quantizer, ditherer, colorCount, parallelTaskCount); return result; } } public static Image QuantizeImage(Image sourceImage, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // performs the pure quantization wihout dithering return QuantizeImage(sourceImage, quantizer, null, colorCount, parallelTaskCount); } public static Image QuantizeImage(Image sourceImage, IColorQuantizer quantizer, IColorDitherer ditherer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // lock mode ImageLockMode lockMode = ditherer == null ? ImageLockMode.ReadOnly : ImageLockMode.ReadWrite; // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, lockMode)) { return QuantizeImage(source, quantizer, ditherer, colorCount, parallelTaskCount); } } #endregion #region | Calculate mean error methods | public Double CalculateMeanError(ImageBuffer target, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(target, "target"); // initializes the error Int64 totalError = 0; // prepares the function TransformPixelFunction calculateMeanError = (sourcePixel, targetPixel) => { Color sourceColor = GetColorFromPixel(sourcePixel); Color targetColor = GetColorFromPixel(targetPixel); totalError += ColorModelHelper.GetColorEuclideanDistance(ColorModel.RedGreenBlue, sourceColor, targetColor); return false; }; // performs the image scan, using a chosen method IList<Point> standardPath = new StandardPathProvider().GetPointPath(Width, Height); TransformPerPixel(target, standardPath, calculateMeanError, parallelTaskCount); // returns the calculates RMSD return Math.Sqrt(totalError/(3.0*Width*Height)); } public static Double CalculateImageMeanError(ImageBuffer source, ImageBuffer target, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); // use other override to calculate error return source.CalculateMeanError(target, parallelTaskCount); } public static Double CalculateImageMeanError(ImageBuffer source, Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateMeanError(target, parallelTaskCount); } } public static Double CalculateImageMeanError(Image sourceImage, ImageBuffer target, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateMeanError(target, parallelTaskCount); } } public static Double CalculateImageMeanError(Image sourceImage, Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateMeanError(target, parallelTaskCount); } } #endregion #region | Calculate normalized mean error methods | public Double CalculateNormalizedMeanError(ImageBuffer target, Int32 parallelTaskCount = 4) { return CalculateMeanError(target, parallelTaskCount) / 255.0; } public static Double CalculateImageNormalizedMeanError(ImageBuffer source, Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateNormalizedMeanError(target, parallelTaskCount); } } public static Double CalculateImageNormalizedMeanError(Image sourceImage, ImageBuffer target, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateNormalizedMeanError(target, parallelTaskCount); } } public static Double CalculateImageNormalizedMeanError(ImageBuffer source, ImageBuffer target, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); // use other override to calculate error return source.CalculateNormalizedMeanError(target, parallelTaskCount); } public static Double CalculateImageNormalizedMeanError(Image sourceImage, Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateNormalizedMeanError(target, parallelTaskCount); } } #endregion #region | Change pixel format methods | public void ChangeFormat(ImageBuffer target, IColorQuantizer quantizer, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(target, "target"); Guard.CheckNull(quantizer, "quantizer"); // gathers some information about the target format Boolean hasSourceAlpha = PixelFormat.HasAlpha(); Boolean hasTargetAlpha = target.PixelFormat.HasAlpha(); Boolean isTargetIndexed = target.PixelFormat.IsIndexed(); Boolean isSourceDeepColor = PixelFormat.IsDeepColor(); Boolean isTargetDeepColor = target.PixelFormat.IsDeepColor(); // step 1 to 3 - prepares the palettes if (isTargetIndexed) SynthetizePalette(quantizer, target.PixelFormat.GetColorCount(), parallelTaskCount); // prepares the quantization function TransformPixelFunction changeFormat = (sourcePixel, targetPixel) => { // if both source and target formats are deep color formats, copies a value directly if (isSourceDeepColor && isTargetDeepColor) { //UInt64 value = sourcePixel.Value; //targetPixel.SetValue(value); } else { // retrieves a source image color Color color = GetColorFromPixel(sourcePixel); // if alpha is not present in the source image, but is present in the target, make one up if (!hasSourceAlpha && hasTargetAlpha) { Int32 argb = 255 << 24 | color.R << 16 | color.G << 8 | color.B; color = Color.FromArgb(argb); } // sets the color to a target pixel SetColorToPixel(targetPixel, color, quantizer); } // allows to write (obviously) the transformed pixel return true; }; // step 5 - generates the target image IList<Point> standardPath = new StandardPathProvider().GetPointPath(Width, Height); TransformPerPixel(target, standardPath, changeFormat, parallelTaskCount); } public static void ChangeFormat(ImageBuffer source, PixelFormat targetFormat, IColorQuantizer quantizer, out Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); // creates a target bitmap in an appropriate format targetImage = new Bitmap(source.Width, source.Height, targetFormat); // wraps target image to a buffer using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.WriteOnly)) { source.ChangeFormat(target, quantizer, parallelTaskCount); } } public static void ChangeFormat(Image sourceImage, PixelFormat targetFormat, IColorQuantizer quantizer, out Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { ChangeFormat(source, targetFormat, quantizer, out targetImage, parallelTaskCount); } } #endregion #region | Dithering methods | public void Dither(ImageBuffer target, IColorDitherer ditherer, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(target, "target"); Guard.CheckNull(ditherer, "ditherer"); Guard.CheckNull(quantizer, "quantizer"); // prepares ditherer for another round ditherer.Prepare(quantizer, colorCount, this, target); // processes the image via the ditherer IList<Point> path = ditherer.GetPointPath(Width, Height); TransformPerPixel(target, path, ditherer.ProcessPixel, parallelTaskCount); } public static void DitherImage(ImageBuffer source, ImageBuffer target, IColorDitherer ditherer, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); // use other override to calculate error source.Dither(target, ditherer, quantizer, colorCount, parallelTaskCount); } public static void DitherImage(ImageBuffer source, Image targetImage, IColorDitherer ditherer, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error source.Dither(target, ditherer, quantizer, colorCount, parallelTaskCount); } } public static void DitherImage(Image sourceImage, ImageBuffer target, IColorDitherer ditherer, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { // use other override to calculate error source.Dither(target, ditherer, quantizer, colorCount, parallelTaskCount); } } public static void DitherImage(Image sourceImage, Image targetImage, IColorDitherer ditherer, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error source.Dither(target, ditherer, quantizer, colorCount, parallelTaskCount); } } #endregion #region | Gamma correction | public void CorrectGamma(Single gamma, IColorQuantizer quantizer, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(quantizer, "quantizer"); // determines which method of color retrieval to use IList<Point> path = quantizer.GetPointPath(Width, Height); // calculates gamma ramp Int32[] gammaRamp = new Int32[256]; for (Int32 index = 0; index < 256; ++index) { gammaRamp[index] = Clamp((Int32) ((255.0f*Math.Pow(index/255.0f, 1.0f/gamma)) + 0.5f)); } // use different scanning method depending whether the image format is indexed ProcessPixelFunction correctGamma = pixel => { Color oldColor = GetColorFromPixel(pixel); Int32 red = gammaRamp[oldColor.R]; Int32 green = gammaRamp[oldColor.G]; Int32 blue = gammaRamp[oldColor.B]; Color newColor = Color.FromArgb(red, green, blue); SetColorToPixel(pixel, newColor, quantizer); return true; }; // performs the image scan, using a chosen method ProcessPerPixel(path, correctGamma, parallelTaskCount); } public static void CorrectImageGamma(Image sourceImage, Single gamma, IColorQuantizer quantizer, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { source.CorrectGamma(gamma, quantizer, parallelTaskCount); } } #endregion #region | Palette methods | public static Int32 Clamp(Int32 value, Int32 minimum = 0, Int32 maximum = 255) { if (value < minimum) value = minimum; if (value > maximum) value = maximum; return value; } private List<Color> UpdatePalette(Boolean forceUpdate = false) { if (IsIndexed && (cachedPalette == null || forceUpdate)) { cachedPalette = bitmap.GetPalette(); } return cachedPalette; } public Color GetPaletteColor(Int32 paletteIndex) { return cachedPalette[paletteIndex]; } #endregion #region << IDisposable >> public void Dispose() { // releases the image lock lock (bitmap) bitmap.UnlockBits(bitmapData); } #endregion #region | Sub-classes | private class LineTask { /// <summary> /// Gets or sets the start offset. /// </summary> public Int32 StartOffset { get; private set; } /// <summary> /// Gets or sets the end offset. /// </summary> public Int32 EndOffset { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="SimplePaletteQuantizer.Helpers.ImageBuffer.LineTask"/> class. /// </summary> public LineTask(Int32 startOffset, Int32 endOffset) { StartOffset = startOffset; EndOffset = endOffset; } } #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; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Runtime.ExceptionServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Threading; namespace System.Net.Mail { internal partial class SmtpConnection { private static readonly ContextCallback s_AuthenticateCallback = new ContextCallback(AuthenticateCallback); private BufferBuilder _bufferBuilder = new BufferBuilder(); private bool _isConnected; private bool _isClosed; private bool _isStreamOpen; private EventHandler _onCloseHandler; internal SmtpTransport _parent; private SmtpClient _client; private NetworkStream _networkStream; internal TcpClient _tcpClient; internal string _host = null; internal int _port = 0; private SmtpReplyReaderFactory _responseReader; private ICredentialsByHost _credentials; private int _timeout = 100000; private string[] _extensions; private ChannelBinding _channelBindingToken = null; private bool _enableSsl; private X509CertificateCollection _clientCertificates; internal SmtpConnection(SmtpTransport parent, SmtpClient client, ICredentialsByHost credentials, ISmtpAuthenticationModule[] authenticationModules) { _client = client; _credentials = credentials; _authenticationModules = authenticationModules; _parent = parent; _tcpClient = new TcpClient(); _onCloseHandler = new EventHandler(OnClose); } internal BufferBuilder BufferBuilder => _bufferBuilder; internal bool IsConnected => _isConnected; internal bool IsStreamOpen => _isStreamOpen; internal SmtpReplyReaderFactory Reader => _responseReader; internal bool EnableSsl { get { return _enableSsl; } set { _enableSsl = value; } } internal int Timeout { get { return _timeout; } set { _timeout = value; } } internal X509CertificateCollection ClientCertificates { get { return _clientCertificates; } set { _clientCertificates = value; } } internal void InitializeConnection(string host, int port) { _tcpClient.Connect(host, port); _networkStream = _tcpClient.GetStream(); } internal IAsyncResult BeginInitializeConnection(string host, int port, AsyncCallback callback, object state) { return _tcpClient.BeginConnect(host, port, callback, state); } internal void EndInitializeConnection(IAsyncResult result) { _tcpClient.EndConnect(result); _networkStream = _tcpClient.GetStream(); } internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port) { ConnectAndHandshakeAsyncResult result = new ConnectAndHandshakeAsyncResult(this, host, port, outerResult, callback, state); result.GetConnection(); return result; } internal IAsyncResult BeginFlush(AsyncCallback callback, object state) { return _networkStream.BeginWrite(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length, callback, state); } internal void EndFlush(IAsyncResult result) { _networkStream.EndWrite(result); _bufferBuilder.Reset(); } internal void Flush() { _networkStream.Write(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length); _bufferBuilder.Reset(); } internal void ReleaseConnection() { if (!_isClosed) { lock (this) { if (!_isClosed && _tcpClient != null) { //free cbt buffer if (_channelBindingToken != null) { _channelBindingToken.Close(); } _networkStream.Close(); _tcpClient.Dispose(); } _isClosed = true; } } _isConnected = false; } internal void Abort() { if (!_isClosed) { lock (this) { if (!_isClosed && _tcpClient != null) { //free CBT buffer if (_channelBindingToken != null) { _channelBindingToken.Close(); } // must destroy manually since sending a QUIT here might not be // interpreted correctly by the server if it's in the middle of a // DATA command or some similar situation. This may send a RST // but this is ok in this situation. Do not reuse this connection _tcpClient.LingerState = new LingerOption(true, 0); _networkStream.Close(); _tcpClient.Dispose(); } _isClosed = true; } } _isConnected = false; } internal void GetConnection(string host, int port) { if (_isConnected) { throw new InvalidOperationException(SR.SmtpAlreadyConnected); } InitializeConnection(host, port); _responseReader = new SmtpReplyReaderFactory(_networkStream); LineInfo info = _responseReader.GetNextReplyReader().ReadLine(); switch (info.StatusCode) { case SmtpStatusCode.ServiceReady: break; default: throw new SmtpException(info.StatusCode, info.Line, true); } try { _extensions = EHelloCommand.Send(this, _client.clientDomain); ParseExtensions(_extensions); } catch (SmtpException e) { if ((e.StatusCode != SmtpStatusCode.CommandUnrecognized) && (e.StatusCode != SmtpStatusCode.CommandNotImplemented)) { throw; } HelloCommand.Send(this, _client.clientDomain); //if ehello isn't supported, assume basic login _supportedAuth = SupportedAuth.Login; } if (_enableSsl) { if (!_serverSupportsStartTls) { // Either TLS is already established or server does not support TLS if (!(_networkStream is TlsStream)) { throw new SmtpException(SR.MailServerDoesNotSupportStartTls); } } StartTlsCommand.Send(this); TlsStream tlsStream = new TlsStream(_networkStream, _tcpClient.Client, host, _clientCertificates); tlsStream.AuthenticateAsClient(); _networkStream = tlsStream; _responseReader = new SmtpReplyReaderFactory(_networkStream); // According to RFC 3207: The client SHOULD send an EHLO command // as the first command after a successful TLS negotiation. _extensions = EHelloCommand.Send(this, _client.clientDomain); ParseExtensions(_extensions); } // if no credentials were supplied, try anonymous // servers don't appear to anounce that they support anonymous login. if (_credentials != null) { for (int i = 0; i < _authenticationModules.Length; i++) { //only authenticate if the auth protocol is supported - chadmu if (!AuthSupported(_authenticationModules[i])) { continue; } NetworkCredential credential = _credentials.GetCredential(host, port, _authenticationModules[i].AuthenticationType); if (credential == null) continue; Authorization auth = SetContextAndTryAuthenticate(_authenticationModules[i], credential, null); if (auth != null && auth.Message != null) { info = AuthCommand.Send(this, _authenticationModules[i].AuthenticationType, auth.Message); if (info.StatusCode == SmtpStatusCode.CommandParameterNotImplemented) { continue; } while ((int)info.StatusCode == 334) { auth = _authenticationModules[i].Authenticate(info.Line, null, this, _client.TargetName, _channelBindingToken); if (auth == null) { throw new SmtpException(SR.SmtpAuthenticationFailed); } info = AuthCommand.Send(this, auth.Message); if ((int)info.StatusCode == 235) { _authenticationModules[i].CloseContext(this); _isConnected = true; return; } } } } } _isConnected = true; } private Authorization SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential credential, ContextAwareResult context) { // We may need to restore user thread token here if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials)) { #if DEBUG if (context != null && !context.IdentityRequested) { NetEventSource.Fail(this, "Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)"); } #endif try { ExecutionContext x = context == null ? null : context.ContextCopy; if (x != null) { AuthenticateCallbackContext authenticationContext = new AuthenticateCallbackContext(this, module, credential, _client.TargetName, _channelBindingToken); ExecutionContext.Run(x, s_AuthenticateCallback, authenticationContext); return authenticationContext._result; } else { return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken); } } catch { // Prevent the impersonation from leaking to upstack exception filters. throw; } } return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken); } private static void AuthenticateCallback(object state) { AuthenticateCallbackContext context = (AuthenticateCallbackContext)state; context._result = context._module.Authenticate(null, context._credential, context._thisPtr, context._spn, context._token); } private class AuthenticateCallbackContext { internal AuthenticateCallbackContext(SmtpConnection thisPtr, ISmtpAuthenticationModule module, NetworkCredential credential, string spn, ChannelBinding Token) { _thisPtr = thisPtr; _module = module; _credential = credential; _spn = spn; _token = Token; _result = null; } internal readonly SmtpConnection _thisPtr; internal readonly ISmtpAuthenticationModule _module; internal readonly NetworkCredential _credential; internal readonly string _spn; internal readonly ChannelBinding _token; internal Authorization _result; } internal void EndGetConnection(IAsyncResult result) { ConnectAndHandshakeAsyncResult.End(result); } internal Stream GetClosableStream() { ClosableStream cs = new ClosableStream(_networkStream, _onCloseHandler); _isStreamOpen = true; return cs; } private void OnClose(object sender, EventArgs args) { _isStreamOpen = false; DataStopCommand.Send(this); } private class ConnectAndHandshakeAsyncResult : LazyAsyncResult { private string _authResponse; private SmtpConnection _connection; private int _currentModule = -1; private int _port; private static AsyncCallback s_handshakeCallback = new AsyncCallback(HandshakeCallback); private static AsyncCallback s_sendEHelloCallback = new AsyncCallback(SendEHelloCallback); private static AsyncCallback s_sendHelloCallback = new AsyncCallback(SendHelloCallback); private static AsyncCallback s_authenticateCallback = new AsyncCallback(AuthenticateCallback); private static AsyncCallback s_authenticateContinueCallback = new AsyncCallback(AuthenticateContinueCallback); private string _host; private readonly ContextAwareResult _outerResult; internal ConnectAndHandshakeAsyncResult(SmtpConnection connection, string host, int port, ContextAwareResult outerResult, AsyncCallback callback, object state) : base(null, state, callback) { _connection = connection; _host = host; _port = port; _outerResult = outerResult; } private static void ConnectionCreatedCallback(object request, object state) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, request); ConnectAndHandshakeAsyncResult ConnectAndHandshakeAsyncResult = (ConnectAndHandshakeAsyncResult)request; if (state is Exception) { ConnectAndHandshakeAsyncResult.InvokeCallback((Exception)state); return; } try { lock (ConnectAndHandshakeAsyncResult._connection) { //if we were cancelled while getting the connection, we should close and return if (ConnectAndHandshakeAsyncResult._connection._isClosed) { ConnectAndHandshakeAsyncResult._connection.ReleaseConnection(); if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Connect was aborted: {request}"); ConnectAndHandshakeAsyncResult.InvokeCallback(null); return; } } ConnectAndHandshakeAsyncResult.Handshake(); } catch (Exception e) { ConnectAndHandshakeAsyncResult.InvokeCallback(e); } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, request); } internal static void End(IAsyncResult result) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result; object connectResult = thisPtr.InternalWaitForCompletion(); if (connectResult is Exception e) { ExceptionDispatchInfo.Capture(e).Throw(); } } internal void GetConnection() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); if (_connection._isConnected) { throw new InvalidOperationException(SR.SmtpAlreadyConnected); } InitializeConnection(); } private void InitializeConnection() { IAsyncResult result = _connection.BeginInitializeConnection(_host, _port, InitializeConnectionCallback, this); if (result.CompletedSynchronously) { _connection.EndInitializeConnection(result); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Connect returned"); try { Handshake(); } catch (Exception e) { InvokeCallback(e); } } } private static void InitializeConnectionCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; thisPtr._connection.EndInitializeConnection(result); if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Connect returned {thisPtr}"); try { thisPtr.Handshake(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private void Handshake() { _connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream); SmtpReplyReader reader = _connection.Reader.GetNextReplyReader(); IAsyncResult result = reader.BeginReadLine(s_handshakeCallback, this); if (!result.CompletedSynchronously) { return; } LineInfo info = reader.EndReadLine(result); if (info.StatusCode != SmtpStatusCode.ServiceReady) { throw new SmtpException(info.StatusCode, info.Line, true); } try { if (!SendEHello()) { return; } } catch { if (!SendHello()) { return; } } } private static void HandshakeCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { try { LineInfo info = thisPtr._connection.Reader.CurrentReader.EndReadLine(result); if (info.StatusCode != SmtpStatusCode.ServiceReady) { thisPtr.InvokeCallback(new SmtpException(info.StatusCode, info.Line, true)); return; } if (!thisPtr.SendEHello()) { return; } } catch (SmtpException) { if (!thisPtr.SendHello()) { return; } } } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private bool SendEHello() { IAsyncResult result = EHelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendEHelloCallback, this); if (result.CompletedSynchronously) { _connection._extensions = EHelloCommand.EndSend(result); _connection.ParseExtensions(_connection._extensions); // If we already have a TlsStream, this is the second EHLO cmd // that we sent after TLS handshake compelted. So skip TLS and // continue with Authenticate. if (_connection._networkStream is TlsStream) { Authenticate(); return true; } if (_connection.EnableSsl) { if (!_connection._serverSupportsStartTls) { // Either TLS is already established or server does not support TLS if (!(_connection._networkStream is TlsStream)) { throw new SmtpException(SR.Format(SR.MailServerDoesNotSupportStartTls)); } } SendStartTls(); } else { Authenticate(); } return true; } return false; } private static void SendEHelloCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { try { thisPtr._connection._extensions = EHelloCommand.EndSend(result); thisPtr._connection.ParseExtensions(thisPtr._connection._extensions); // If we already have a SSlStream, this is the second EHLO cmd // that we sent after TLS handshake compelted. So skip TLS and // continue with Authenticate. if (thisPtr._connection._networkStream is TlsStream) { thisPtr.Authenticate(); return; } } catch (SmtpException e) { if ((e.StatusCode != SmtpStatusCode.CommandUnrecognized) && (e.StatusCode != SmtpStatusCode.CommandNotImplemented)) { throw; } if (!thisPtr.SendHello()) { return; } } if (thisPtr._connection.EnableSsl) { if (!thisPtr._connection._serverSupportsStartTls) { // Either TLS is already established or server does not support TLS if (!(thisPtr._connection._networkStream is TlsStream)) { throw new SmtpException(SR.MailServerDoesNotSupportStartTls); } } thisPtr.SendStartTls(); } else { thisPtr.Authenticate(); } } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private bool SendHello() { IAsyncResult result = HelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendHelloCallback, this); //if ehello isn't supported, assume basic auth if (result.CompletedSynchronously) { _connection._supportedAuth = SupportedAuth.Login; HelloCommand.EndSend(result); Authenticate(); return true; } return false; } private static void SendHelloCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { HelloCommand.EndSend(result); thisPtr.Authenticate(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private bool SendStartTls() { IAsyncResult result = StartTlsCommand.BeginSend(_connection, SendStartTlsCallback, this); if (result.CompletedSynchronously) { StartTlsCommand.EndSend(result); TlsStreamAuthenticate(); return true; } return false; } private static void SendStartTlsCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { StartTlsCommand.EndSend(result); thisPtr.TlsStreamAuthenticate(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private bool TlsStreamAuthenticate() { _connection._networkStream = new TlsStream(_connection._networkStream, _connection._tcpClient.Client, _host, _connection._clientCertificates); IAsyncResult result = (_connection._networkStream as TlsStream).BeginAuthenticateAsClient(TlsStreamAuthenticateCallback, this); if (result.CompletedSynchronously) { (_connection._networkStream as TlsStream).EndAuthenticateAsClient(result); _connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream); SendEHello(); return true; } return false; } private static void TlsStreamAuthenticateCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { (thisPtr._connection._networkStream as TlsStream).EndAuthenticateAsClient(result); thisPtr._connection._responseReader = new SmtpReplyReaderFactory(thisPtr._connection._networkStream); thisPtr.SendEHello(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private void Authenticate() { //if no credentials were supplied, try anonymous //servers don't appear to anounce that they support anonymous login. if (_connection._credentials != null) { while (++_currentModule < _connection._authenticationModules.Length) { //only authenticate if the auth protocol is supported ISmtpAuthenticationModule module = _connection._authenticationModules[_currentModule]; if (!_connection.AuthSupported(module)) { continue; } NetworkCredential credential = _connection._credentials.GetCredential(_host, _port, module.AuthenticationType); if (credential == null) continue; Authorization auth = _connection.SetContextAndTryAuthenticate(module, credential, _outerResult); if (auth != null && auth.Message != null) { IAsyncResult result = AuthCommand.BeginSend(_connection, _connection._authenticationModules[_currentModule].AuthenticationType, auth.Message, s_authenticateCallback, this); if (!result.CompletedSynchronously) { return; } LineInfo info = AuthCommand.EndSend(result); if ((int)info.StatusCode == 334) { _authResponse = info.Line; if (!AuthenticateContinue()) { return; } } else if ((int)info.StatusCode == 235) { module.CloseContext(_connection); _connection._isConnected = true; break; } } } } _connection._isConnected = true; InvokeCallback(); } private static void AuthenticateCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { LineInfo info = AuthCommand.EndSend(result); if ((int)info.StatusCode == 334) { thisPtr._authResponse = info.Line; if (!thisPtr.AuthenticateContinue()) { return; } } else if ((int)info.StatusCode == 235) { thisPtr._connection._authenticationModules[thisPtr._currentModule].CloseContext(thisPtr._connection); thisPtr._connection._isConnected = true; thisPtr.InvokeCallback(); return; } thisPtr.Authenticate(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private bool AuthenticateContinue() { for (;;) { // We don't need credential on the continued auth assuming they were captured on the first call. // That should always work, otherwise what if a new credential has been returned? Authorization auth = _connection._authenticationModules[_currentModule].Authenticate(_authResponse, null, _connection, _connection._client.TargetName, _connection._channelBindingToken); if (auth == null) { throw new SmtpException(SR.Format(SR.SmtpAuthenticationFailed)); } IAsyncResult result = AuthCommand.BeginSend(_connection, auth.Message, s_authenticateContinueCallback, this); if (!result.CompletedSynchronously) { return false; } LineInfo info = AuthCommand.EndSend(result); if ((int)info.StatusCode == 235) { _connection._authenticationModules[_currentModule].CloseContext(_connection); _connection._isConnected = true; InvokeCallback(); return false; } else if ((int)info.StatusCode != 334) { return true; } _authResponse = info.Line; } } private static void AuthenticateContinueCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { LineInfo info = AuthCommand.EndSend(result); if ((int)info.StatusCode == 235) { thisPtr._connection._authenticationModules[thisPtr._currentModule].CloseContext(thisPtr._connection); thisPtr._connection._isConnected = true; thisPtr.InvokeCallback(); return; } else if ((int)info.StatusCode == 334) { thisPtr._authResponse = info.Line; if (!thisPtr.AuthenticateContinue()) { return; } } thisPtr.Authenticate(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } } } }
using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Microsoft.Internal.Web.Utils; using NuGet.Resources; namespace NuGet { public class PackageManager : IPackageManager { private ILogger _logger; private event EventHandler<PackageOperationEventArgs> _packageInstalling; private event EventHandler<PackageOperationEventArgs> _packageInstalled; private event EventHandler<PackageOperationEventArgs> _packageUninstalling; private event EventHandler<PackageOperationEventArgs> _packageUninstalled; public PackageManager(IPackageRepository sourceRepository, string path) : this(sourceRepository, new DefaultPackagePathResolver(path), new PhysicalFileSystem(path)) { } public PackageManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IFileSystem fileSystem) : this(sourceRepository, pathResolver, fileSystem, new LocalPackageRepository(pathResolver, fileSystem)) { } public PackageManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IFileSystem fileSystem, IPackageRepository localRepository) { if (sourceRepository == null) { throw new ArgumentNullException("sourceRepository"); } if (pathResolver == null) { throw new ArgumentNullException("pathResolver"); } if (fileSystem == null) { throw new ArgumentNullException("fileSystem"); } if (localRepository == null) { throw new ArgumentNullException("localRepository"); } SourceRepository = sourceRepository; PathResolver = pathResolver; FileSystem = fileSystem; LocalRepository = localRepository; } public event EventHandler<PackageOperationEventArgs> PackageInstalled { add { _packageInstalled += value; } remove { _packageInstalled -= value; } } public event EventHandler<PackageOperationEventArgs> PackageInstalling { add { _packageInstalling += value; } remove { _packageInstalling -= value; } } public event EventHandler<PackageOperationEventArgs> PackageUninstalling { add { _packageUninstalling += value; } remove { _packageUninstalling -= value; } } public event EventHandler<PackageOperationEventArgs> PackageUninstalled { add { _packageUninstalled += value; } remove { _packageUninstalled -= value; } } public IFileSystem FileSystem { get; set; } public IPackageRepository SourceRepository { get; private set; } public IPackageRepository LocalRepository { get; private set; } public IPackagePathResolver PathResolver { get; private set; } public ILogger Logger { get { return _logger ?? NullLogger.Instance; } set { _logger = value; } } public void InstallPackage(string packageId) { InstallPackage(packageId, version: null, ignoreDependencies: false); } public void InstallPackage(string packageId, Version version) { InstallPackage(packageId, version, ignoreDependencies: false); } public virtual void InstallPackage(string packageId, Version version, bool ignoreDependencies) { IPackage package = PackageHelper.ResolvePackage(SourceRepository, LocalRepository, packageId, version); InstallPackage(package, ignoreDependencies); } public virtual void InstallPackage(IPackage package, bool ignoreDependencies) { Execute(package, new InstallWalker(LocalRepository, SourceRepository, Logger, ignoreDependencies)); } private void Execute(IPackage package, IPackageOperationResolver resolver) { var operations = resolver.ResolveOperations(package); if (operations.Any()) { foreach (PackageOperation operation in operations) { Execute(operation); } } else if (LocalRepository.Exists(package)) { Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageAlreadyInstalled, package.GetFullName()); } } protected void Execute(PackageOperation operation) { bool packageExists = LocalRepository.Exists(operation.Package); if (operation.Action == PackageAction.Install) { // If the package is already installed, then skip it if (packageExists) { Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageAlreadyInstalled, operation.Package.GetFullName()); } else { ExecuteInstall(operation.Package); } } else { if (packageExists) { ExecuteUninstall(operation.Package); } } } private void ExecuteInstall(IPackage package) { PackageOperationEventArgs args = CreateOperation(package); OnInstalling(args); if (args.Cancel) { return; } ExpandFiles(package); LocalRepository.AddPackage(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageInstalledSuccessfully, package.GetFullName()); OnInstalled(args); } private void ExpandFiles(IPackage package) { string packageDirectory = PathResolver.GetPackageDirectory(package); // Add files files FileSystem.AddFiles(package.GetFiles(), packageDirectory); } public void UninstallPackage(string packageId) { UninstallPackage(packageId, version: null, forceRemove: false, removeDependencies: false); } public void UninstallPackage(string packageId, Version version) { UninstallPackage(packageId, version: version, forceRemove: false, removeDependencies: false); } public void UninstallPackage(string packageId, Version version, bool forceRemove) { UninstallPackage(packageId, version: version, forceRemove: forceRemove, removeDependencies: false); } public virtual void UninstallPackage(string packageId, Version version, bool forceRemove, bool removeDependencies) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage package = LocalRepository.FindPackage(packageId, version: version); if (package == null) { throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, NuGetResources.UnknownPackage, packageId)); } UninstallPackage(package, forceRemove, removeDependencies); } public void UninstallPackage(IPackage package) { UninstallPackage(package, forceRemove: false, removeDependencies: false); } public void UninstallPackage(IPackage package, bool forceRemove) { UninstallPackage(package, forceRemove: forceRemove, removeDependencies: false); } public virtual void UninstallPackage(IPackage package, bool forceRemove, bool removeDependencies) { Execute(package, new UninstallWalker(LocalRepository, new DependentsWalker(LocalRepository), Logger, removeDependencies, forceRemove)); } protected virtual void ExecuteUninstall(IPackage package) { PackageOperationEventArgs args = CreateOperation(package); OnUninstalling(args); if (args.Cancel) { return; } RemoveFiles(package); // Remove package to the repository LocalRepository.RemovePackage(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyUninstalledPackage, package.GetFullName()); OnUninstalled(args); } private void RemoveFiles(IPackage package) { string packageDirectory = PathResolver.GetPackageDirectory(package); // Remove resource files FileSystem.DeleteFiles(package.GetFiles(), packageDirectory); } private void OnInstalling(PackageOperationEventArgs e) { if (_packageInstalling != null) { _packageInstalling(this, e); } } protected virtual void OnInstalled(PackageOperationEventArgs e) { if (_packageInstalled != null) { _packageInstalled(this, e); } } protected virtual void OnUninstalled(PackageOperationEventArgs e) { if (_packageUninstalled != null) { _packageUninstalled(this, e); } } private void OnUninstalling(PackageOperationEventArgs e) { if (_packageUninstalling != null) { _packageUninstalling(this, e); } } private PackageOperationEventArgs CreateOperation(IPackage package) { return new PackageOperationEventArgs(package, PathResolver.GetInstallPath(package)); } public void UpdatePackage(string packageId, bool updateDependencies) { UpdatePackage(packageId, version: null, updateDependencies: updateDependencies); } public void UpdatePackage(string packageId, Version version, bool updateDependencies) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage oldPackage = LocalRepository.FindPackage(packageId); // Check to see if this package is installed if (oldPackage == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.UnknownPackage, packageId)); } Logger.Log(MessageLevel.Debug, NuGetResources.Debug_LookingForUpdates, packageId); IPackage newPackage = SourceRepository.FindPackage(packageId, version: version); if (newPackage != null && oldPackage.Version != newPackage.Version) { UpdatePackage(oldPackage, newPackage, updateDependencies); } else { Logger.Log(MessageLevel.Info, NuGetResources.Log_NoUpdatesAvailable, packageId); } } public void UpdatePackage(IPackage oldPackage, IPackage newPackage, bool updateDependencies) { // Install the new package InstallPackage(newPackage, !updateDependencies); // Remove the old one UninstallPackage(oldPackage, updateDependencies); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Xml; using Microsoft.Win32; using WebsitePanel.Providers; using WebsitePanel.Providers.FTP; using WebsitePanel.Providers.Utils; using WebsitePanel.Server.Utils; namespace WebsitePanel.Providers.FTP { public class ServU : HostingServiceProviderBase, IFtpServer { #region Constants private const string SERVU_PATH_REG = @"SYSTEM\CurrentControlSet\Services\Serv-U"; private const string SERVU_DAEMON_CONFIG_FILE = "ServUDaemon.ini"; #endregion #region Properties protected string SERVU_DOMAINS_REG { get { return (IntPtr.Size == 8) ? @"SOFTWARE\Wow6432Node\Cat Soft\Serv-U\Domains\DomainList" // x64 : @"SOFTWARE\Cat Soft\Serv-U\Domains\DomainList"; // x86 } } protected virtual string ServUFolder { get { RegistryKey key = Registry.LocalMachine.OpenSubKey(SERVU_PATH_REG); if (key == null) throw new Exception("Serv-U service registry key was not found: " + SERVU_PATH_REG); return Path.GetDirectoryName((string)key.GetValue("ImagePath")); } } protected virtual string DomainId { get { return ProviderSettings["DomainId"]; } } #endregion #region Sites public virtual FtpSite[] GetSites() { List<FtpSite> sites = new List<FtpSite>(); RegistryKey key = Registry.LocalMachine.OpenSubKey(SERVU_DOMAINS_REG); if (key == null) return sites.ToArray(); foreach (string domainId in key.GetValueNames()) { string[] parts = key.GetValue(domainId).ToString().Split('|'); FtpSite site = new FtpSite(); site.SiteId = domainId; site.Name = parts[3]; sites.Add(site); } return sites.ToArray(); } public virtual void ChangeSiteState(string siteId, ServerState state) { // not implemented } public virtual string CreateSite(FtpSite site) { // not implemented return null; } public virtual void DeleteSite(string siteId) { // not implemented } public virtual FtpSite GetSite(string siteId) { // not implemented return null; } public virtual bool SiteExists(string siteId) { // not implemented return false; } public virtual ServerState GetSiteState(string siteId) { // not implemented return ServerState.Started; } public virtual void UpdateSite(FtpSite site) { // not implemented } #endregion #region Accounts public virtual bool AccountExists(string accountName) { string keyName = @"SOFTWARE\Cat Soft\Serv-U\Domains\" + DomainId + @"\UserList"; RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName); if (key == null) return false; return (key.GetValue(accountName) != null); } public virtual FtpAccount[] GetAccounts() { List<FtpAccount> accounts = new List<FtpAccount>(); string keyName = @"SOFTWARE\Cat Soft\Serv-U\Domains\" + DomainId + @"\UserList"; RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName); if (key == null) return accounts.ToArray(); foreach (string name in key.GetValueNames()) { string[] parts = key.GetValue(name).ToString().Split('|'); FtpAccount acc = new FtpAccount(); acc.Name = name; acc.Enabled = (parts[0] == "1"); accounts.Add(acc); } return accounts.ToArray(); } public virtual FtpAccount GetAccount(string accountName) { string keyName = @"SOFTWARE\Cat Soft\Serv-U\Domains\" + DomainId + @"\UserSettings\" + accountName; RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName); if (key == null) return null; FtpAccount account = new FtpAccount(); account.Name = accountName; // status RegistryKey usersKey = Registry.LocalMachine.OpenSubKey( @"SOFTWARE\Cat Soft\Serv-U\Domains\" + DomainId + @"\UserList"); string[] parts = usersKey.GetValue(accountName).ToString().Split('|'); account.Enabled = (parts[0] == "1"); // path and permissions string path = (string)key.GetValue("Access1"); if (path != null) { parts = path.Split('|'); account.Folder = parts[0]; account.CanRead = (parts[1].IndexOf("R") != -1); account.CanWrite = (parts[1].IndexOf("W") != -1); } // password account.Password = (string)key.GetValue("Password"); return account; } public virtual void CreateAccount(FtpAccount account) { // add user to the list if (AccountExists(account.Name)) return; RegistryKey domainKey = Registry.LocalMachine.OpenSubKey( @"SOFTWARE\Cat Soft\Serv-U\Domains\" + DomainId, true); RegistryKey usersKey = domainKey.OpenSubKey("UserList", true); if (usersKey == null) usersKey = domainKey.CreateSubKey("UserList"); usersKey.SetValue(account.Name, BoolToString(account.Enabled) + "|0"); // user details RegistryKey settingsKey = domainKey.OpenSubKey("UserSettings", true); if(settingsKey == null) settingsKey = domainKey.CreateSubKey("UserSettings"); RegistryKey user = settingsKey.CreateSubKey(account.Name); // folder and permissions user.SetValue("Access1", account.Folder + "|" + BuildPermissionsString(account.CanRead, account.CanWrite)); // enable if (!account.Enabled) user.SetValue("Enable", "0"); // home folder user.SetValue("HomeDir", account.Folder); // password user.SetValue("Password", HashPassword(account.Password)); user.SetValue("PasswordLastChange", "1170889819"); // other props user.SetValue("RelPaths", "1"); user.SetValue("SKEYValues", ""); user.SetValue("TimeOut", "600"); // reload config ReloadServUConfig(); } public virtual void UpdateAccount(FtpAccount account) { // edit status in the list RegistryKey usersKey = Registry.LocalMachine.OpenSubKey( @"SOFTWARE\Cat Soft\Serv-U\Domains\" + DomainId + @"\UserList", true); usersKey.SetValue(account.Name, BoolToString(account.Enabled) + "|0"); // edit details RegistryKey user = Registry.LocalMachine.OpenSubKey( @"SOFTWARE\Cat Soft\Serv-U\Domains\" + DomainId + @"\UserSettings\" + account.Name, true); if (user == null) return; // folder and permissions user.SetValue("Access1", account.Folder + "|" + BuildPermissionsString(account.CanRead, account.CanWrite)); if (user.GetValue("Enable") != null) user.DeleteValue("Enable"); // enable if (!account.Enabled) user.SetValue("Enable", "0"); // home folder user.SetValue("HomeDir", account.Folder); // password if (!String.IsNullOrEmpty(account.Password)) { user.SetValue("Password", HashPassword(account.Password)); user.SetValue("PasswordLastChange", "1170889819"); } // reload config ReloadServUConfig(); } public virtual void DeleteAccount(string accountName) { // remove settings RegistryKey key = Registry.LocalMachine.OpenSubKey( @"SOFTWARE\Cat Soft\Serv-U\Domains\" + DomainId + @"\UserSettings", true); key.DeleteSubKey(accountName); // remove from the list RegistryKey usersKey = Registry.LocalMachine.OpenSubKey( @"SOFTWARE\Cat Soft\Serv-U\Domains\" + DomainId + @"\UserList", true); usersKey.DeleteValue(accountName); // reload config ReloadServUConfig(); } #endregion public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled) { foreach (ServiceProviderItem item in items) { if (item is FtpAccount) { try { // change FTP account state FtpAccount account = GetAccount(item.Name); account.Enabled = enabled; UpdateAccount(account); } catch (Exception ex) { Log.WriteError(String.Format("Error switching '{0}' {1}", item.Name, item.GetType().Name), ex); } } } } public override void DeleteServiceItems(ServiceProviderItem[] items) { foreach (ServiceProviderItem item in items) { if (item is FtpAccount) { try { // delete FTP account DeleteAccount(item.Name); } catch (Exception ex) { Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex); } } } } #region Private Helpers private string BoolToString(bool val) { return val ? "1" : "0"; } private string BuildPermissionsString(bool read, bool write) { string perms = read ? "R" : ""; perms += write ? "WAM" : ""; perms += read ? "L" : ""; perms += write ? "CD" : ""; perms += "P"; return perms; } private string HashPassword(string str) { string chrs = "abcdefghijklmnopqrstuvwxyz"; Random r = new Random(); string prefix = chrs.Substring(r.Next(25), 1) + chrs.Substring(r.Next(25), 1); str = prefix + str; System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding(); byte[] bytes = ue.GetBytes(str); // encrypt bytes System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hashBytes = md5.ComputeHash(bytes); // Convert the encrypted bytes back to a string (base 16) string hashString = ""; for (int i = 0; i < hashBytes.Length; i++) hashString += Convert.ToString(hashBytes[i], 16).PadLeft(2, '0'); return prefix + hashString.PadLeft(32, '0'); } private void ReloadServUConfig() { string path = GetServUConfigPath(); if (!File.Exists(path)) throw new Exception("Can not find Serv-U config file: " + path); List<string> lines = new List<string>(); lines.AddRange(File.ReadAllLines(path)); for (int i = 0; i < lines.Count; i++) { if (lines[i].ToLower() == "[global]") { lines.Insert(i + 1, "reloadsettings=true"); break; } } // save file File.WriteAllLines(path, lines.ToArray()); } private string GetServUConfigPath() { return Path.Combine(ServUFolder, SERVU_DAEMON_CONFIG_FILE); } #endregion public override bool IsInstalled() { string name = null; string versionNumber = null; RegistryKey HKLM = Registry.LocalMachine; RegistryKey key = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Serv-U_is1"); if (key != null) { name = (string)key.GetValue("DisplayName"); string[] parts = name.Split(new char[] { ' ' }); versionNumber = parts[1]; } else { key = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Serv-U_is1"); if (key != null) { name = (string)key.GetValue("DisplayName"); string[] parts = name.Split(new char[] { ' ' }); versionNumber = parts[1]; } else { return false; } } string[] split = versionNumber.Split(new char[] { '.' }); return split[0].Equals("6"); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands { /// <summary> /// /// Implements the start-transcript cmdlet /// /// </summary> [Cmdlet(VerbsLifecycle.Start, "Transcript", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113408")] [OutputType(typeof(String))] public sealed class StartTranscriptCommand : PSCmdlet { /// <summary> /// /// The name of the file in which to write the transcript. If not provided, the file indicated by the variable /// $TRANSCRIPT is used. If neither the filename is supplied or $TRANSCRIPT is not set, the filename shall be $HOME/My /// Documents/PowerShell_transcript.YYYYMMDDmmss.txt /// /// </summary> /// <value></value> [Parameter(Position = 0, ParameterSetName = "ByPath")] [ValidateNotNullOrEmpty] public string Path { get { return _outFilename; } set { _isFilenameSet = true; _outFilename = value; } } /// <summary> /// The literal name of the file in which to write the transcript. /// </summary> [Parameter(Position = 0, ParameterSetName = "ByLiteralPath")] [Alias("PSPath")] [ValidateNotNullOrEmpty] public string LiteralPath { get { return _outFilename; } set { _isFilenameSet = true; _outFilename = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// The literal name of the file in which to write the transcript. /// </summary> [Parameter(Position = 0, ParameterSetName = "ByOutputDirectory")] [ValidateNotNullOrEmpty] public string OutputDirectory { get; set; } /// <summary> /// /// Describes the current state of the activity. /// /// </summary> /// <value></value> [Parameter] public SwitchParameter Append { get { return _shouldAppend; } set { _shouldAppend = value; } } /// <summary> /// Property that sets force parameter. This will reset the read-only /// attribute on an existing file. /// </summary> /// <remarks> /// The read-only attribute will not be replaced when the transcript is done. /// </remarks> [Parameter()] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// Property that prevents file overwrite. /// </summary> [Parameter()] [Alias("NoOverwrite")] public SwitchParameter NoClobber { get { return _noclobber; } set { _noclobber = value; } } private bool _noclobber; /// <summary> /// Whether to include command invocation time headers between commands. /// </summary> [Parameter()] public SwitchParameter IncludeInvocationHeader { get; set; } /// <summary> /// /// Starts the transcription /// </summary> protected override void BeginProcessing() { // If they haven't specified a path, figure out the correct output path. if (!_isFilenameSet) { // read the filename from $TRANSCRIPT object value = this.GetVariableValue("global:TRANSCRIPT", null); // $TRANSCRIPT is not set, so create a file name (the default: $HOME/My Documents/PowerShell_transcript.YYYYMMDDmmss.txt) if (value == null) { // If they've specified an output directory, use it. Otherwise, use "My Documents" if (OutputDirectory != null) { _outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(OutputDirectory, false); _isLiteralPath = true; } else { _outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(); } } else { _outFilename = (string)value; } } // Normalize outFilename here in case it is a relative path try { string effectiveFilePath = ResolveFilePath(Path, _isLiteralPath); if (!ShouldProcess(effectiveFilePath)) return; if (System.IO.File.Exists(effectiveFilePath)) { if (NoClobber && !Append) { string message = StringUtil.Format(TranscriptStrings.TranscriptFileExistsNoClobber, effectiveFilePath, "NoClobber"); // prevents localization Exception uae = new UnauthorizedAccessException(message); ErrorRecord errorRecord = new ErrorRecord( uae, "NoClobber", ErrorCategory.ResourceExists, effectiveFilePath); // NOTE: this call will throw ThrowTerminatingError(errorRecord); } System.IO.FileInfo fInfo = new System.IO.FileInfo(effectiveFilePath); if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // Save some disk write time by checking whether file is readonly.. if (Force) { //Make sure the file is not read only // Note that we will not clear the ReadOnly flag later fInfo.Attributes &= ~(FileAttributes.ReadOnly); } else { Exception innerException = PSTraceSource.NewArgumentException(effectiveFilePath, TranscriptStrings.TranscriptFileReadOnly, effectiveFilePath); ThrowTerminatingError(new ErrorRecord(innerException, "FileReadOnly", ErrorCategory.InvalidArgument, effectiveFilePath)); } } // If they didn't specify -Append, delete the file if (!_shouldAppend) { System.IO.File.Delete(effectiveFilePath); } } System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = this.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo; Host.UI.StartTranscribing(effectiveFilePath, psSenderInfo, IncludeInvocationHeader.ToBool()); // ch.StartTranscribing(effectiveFilePath, Append); // NTRAID#Windows Out Of Band Releases-931008-2006/03/21 // Previous behavior was to write this even if ShouldProcess // returned false. Why would we want that? PSObject outputObject = new PSObject( StringUtil.Format(TranscriptStrings.TranscriptionStarted, Path)); outputObject.Properties.Add(new PSNoteProperty("Path", Path)); WriteObject(outputObject); } catch (Exception e) { try { Host.UI.StopTranscribing(); } catch { CommandProcessorBase.CheckForSevereException(e); } ErrorRecord er = new ErrorRecord( PSTraceSource.NewInvalidOperationException(e, TranscriptStrings.CannotStartTranscription), "CannotStartTranscription", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } } /// resolve a user provided file name or path (including globbing characters) /// to a fully qualified file path, using the file system provider private string ResolveFilePath(string filePath, bool isLiteralPath) { string path = null; try { if (isLiteralPath) { path = SessionState.Path.GetUnresolvedProviderPathFromPSPath(filePath); } else { ProviderInfo provider = null; Collection<string> filePaths = SessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider); if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { ReportWrongProviderType(provider.FullName); } if (filePaths.Count > 1) { ReportMultipleFilesNotSupported(); } path = filePaths[0]; } } catch (ItemNotFoundException) { path = null; } if (string.IsNullOrEmpty(path)) { CmdletProviderContext cmdletProviderContext = new CmdletProviderContext(this); ProviderInfo provider = null; PSDriveInfo drive = null; path = SessionState.Path.GetUnresolvedProviderPathFromPSPath( filePath, cmdletProviderContext, out provider, out drive); cmdletProviderContext.ThrowFirstErrorOrDoNothing(); if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { ReportWrongProviderType(provider.FullName); } } return path; } private void ReportWrongProviderType(string providerId) { ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewInvalidOperationException(TranscriptStrings.ReadWriteFileNotFileSystemProvider, providerId), "ReadWriteFileNotFileSystemProvider", ErrorCategory.InvalidArgument, null); ThrowTerminatingError(errorRecord); } private void ReportMultipleFilesNotSupported() { ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewInvalidOperationException(TranscriptStrings.MultipleFilesNotSupported), "MultipleFilesNotSupported", ErrorCategory.InvalidArgument, null); ThrowTerminatingError(errorRecord); } private bool _shouldAppend; private string _outFilename; private bool _isFilenameSet; } }
namespace Petstore { using Models; using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for SwaggerPetstore. /// </summary> public static partial class SwaggerPetstoreExtensions { /// <summary> /// Fake endpoint to test byte array in body parameter for adding a new pet to /// the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object in the form of byte array /// </param> public static void AddPetUsingByteArray(this ISwaggerPetstore operations, string body = default(string)) { operations.AddPetUsingByteArrayAsync(body).GetAwaiter().GetResult(); } /// <summary> /// Fake endpoint to test byte array in body parameter for adding a new pet to /// the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object in the form of byte array /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddPetUsingByteArrayAsync(this ISwaggerPetstore operations, string body = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.AddPetUsingByteArrayWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Add a new pet to the store /// </summary> /// <remarks> /// Adds a new pet to the store. You may receive an HTTP invalid input if your /// pet is invalid. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static void AddPet(this ISwaggerPetstore operations, Pet body = default(Pet)) { operations.AddPetAsync(body).GetAwaiter().GetResult(); } /// <summary> /// Add a new pet to the store /// </summary> /// <remarks> /// Adds a new pet to the store. You may receive an HTTP invalid input if your /// pet is invalid. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddPetAsync(this ISwaggerPetstore operations, Pet body = default(Pet), CancellationToken cancellationToken = default(CancellationToken)) { await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static void UpdatePet(this ISwaggerPetstore operations, Pet body = default(Pet)) { operations.UpdatePetAsync(body).GetAwaiter().GetResult(); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetAsync(this ISwaggerPetstore operations, Pet body = default(Pet), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> public static IList<Pet> FindPetsByStatus(this ISwaggerPetstore operations, IList<string> status = default(IList<string>)) { return operations.FindPetsByStatusAsync(status).GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstore operations, IList<string> status = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> public static IList<Pet> FindPetsByTags(this ISwaggerPetstore operations, IList<string> tags = default(IList<string>)) { return operations.FindPetsByTagsAsync(tags).GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstore operations, IList<string> tags = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Fake endpoint to test byte array return by 'Find pet by ID' /// </summary> /// <remarks> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API /// error conditions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> public static string FindPetsWithByteArray(this ISwaggerPetstore operations, long petId) { return operations.FindPetsWithByteArrayAsync(petId).GetAwaiter().GetResult(); } /// <summary> /// Fake endpoint to test byte array return by 'Find pet by ID' /// </summary> /// <remarks> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API /// error conditions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> FindPetsWithByteArrayAsync(this ISwaggerPetstore operations, long petId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsWithByteArrayWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find pet by ID /// </summary> /// <remarks> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API /// error conditions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> public static Pet GetPetById(this ISwaggerPetstore operations, long petId) { return operations.GetPetByIdAsync(petId).GetAwaiter().GetResult(); } /// <summary> /// Find pet by ID /// </summary> /// <remarks> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API /// error conditions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Pet> GetPetByIdAsync(this ISwaggerPetstore operations, long petId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> public static void UpdatePetWithForm(this ISwaggerPetstore operations, string petId, string name = default(string), string status = default(string)) { operations.UpdatePetWithFormAsync(petId, name, status).GetAwaiter().GetResult(); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetWithFormAsync(this ISwaggerPetstore operations, string petId, string name = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, name, status, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> public static void DeletePet(this ISwaggerPetstore operations, long petId, string apiKey = default(string)) { operations.DeletePetAsync(petId, apiKey).GetAwaiter().GetResult(); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeletePetAsync(this ISwaggerPetstore operations, long petId, string apiKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// uploads an image /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet to update /// </param> /// <param name='additionalMetadata'> /// Additional data to pass to server /// </param> /// <param name='file'> /// file to upload /// </param> public static void UploadFile(this ISwaggerPetstore operations, long petId, string additionalMetadata = default(string), Stream file = default(Stream)) { operations.UploadFileAsync(petId, additionalMetadata, file).GetAwaiter().GetResult(); } /// <summary> /// uploads an image /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet to update /// </param> /// <param name='additionalMetadata'> /// Additional data to pass to server /// </param> /// <param name='file'> /// file to upload /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UploadFileAsync(this ISwaggerPetstore operations, long petId, string additionalMetadata = default(string), Stream file = default(Stream), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UploadFileWithHttpMessagesAsync(petId, additionalMetadata, file, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IDictionary<string, int?> GetInventory(this ISwaggerPetstore operations) { return operations.GetInventoryAsync().GetAwaiter().GetResult(); } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstore operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> public static Order PlaceOrder(this ISwaggerPetstore operations, Order body = default(Order)) { return operations.PlaceOrderAsync(body).GetAwaiter().GetResult(); } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> PlaceOrderAsync(this ISwaggerPetstore operations, Order body = default(Order), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find purchase order by ID /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of pet that needs to be fetched /// </param> public static Order GetOrderById(this ISwaggerPetstore operations, string orderId) { return operations.GetOrderByIdAsync(orderId).GetAwaiter().GetResult(); } /// <summary> /// Find purchase order by ID /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> GetOrderByIdAsync(this ISwaggerPetstore operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete purchase order by ID /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of the order that needs to be deleted /// </param> public static void DeleteOrder(this ISwaggerPetstore operations, string orderId) { operations.DeleteOrderAsync(orderId).GetAwaiter().GetResult(); } /// <summary> /// Delete purchase order by ID /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of the order that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteOrderAsync(this ISwaggerPetstore operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> public static void CreateUser(this ISwaggerPetstore operations, User body = default(User)) { operations.CreateUserAsync(body).GetAwaiter().GetResult(); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUserAsync(this ISwaggerPetstore operations, User body = default(User), CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithArrayInput(this ISwaggerPetstore operations, IList<User> body = default(IList<User>)) { operations.CreateUsersWithArrayInputAsync(body).GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstore operations, IList<User> body = default(IList<User>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithListInput(this ISwaggerPetstore operations, IList<User> body = default(IList<User>)) { operations.CreateUsersWithListInputAsync(body).GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstore operations, IList<User> body = default(IList<User>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> public static string LoginUser(this ISwaggerPetstore operations, string username = default(string), string password = default(string)) { return operations.LoginUserAsync(username, password).GetAwaiter().GetResult(); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> LoginUserAsync(this ISwaggerPetstore operations, string username = default(string), string password = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void LogoutUser(this ISwaggerPetstore operations) { operations.LogoutUserAsync().GetAwaiter().GetResult(); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task LogoutUserAsync(this ISwaggerPetstore operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> public static User GetUserByName(this ISwaggerPetstore operations, string username) { return operations.GetUserByNameAsync(username).GetAwaiter().GetResult(); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<User> GetUserByNameAsync(this ISwaggerPetstore operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> public static void UpdateUser(this ISwaggerPetstore operations, string username, User body = default(User)) { operations.UpdateUserAsync(username, body).GetAwaiter().GetResult(); } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateUserAsync(this ISwaggerPetstore operations, string username, User body = default(User), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> public static void DeleteUser(this ISwaggerPetstore operations, string username) { operations.DeleteUserAsync(username).GetAwaiter().GetResult(); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteUserAsync(this ISwaggerPetstore operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G11_City_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="G11_City_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="G10_City"/> collection. /// </remarks> [Serializable] public partial class G11_City_ReChild : BusinessBase<G11_City_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="City_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name"); /// <summary> /// Gets or sets the CityRoads Child Name. /// </summary> /// <value>The CityRoads Child Name.</value> public string City_Child_Name { get { return GetProperty(City_Child_NameProperty); } set { SetProperty(City_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G11_City_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="G11_City_ReChild"/> object.</returns> internal static G11_City_ReChild NewG11_City_ReChild() { return DataPortal.CreateChild<G11_City_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="G11_City_ReChild"/> object, based on given parameters. /// </summary> /// <param name="city_ID2">The City_ID2 parameter of the G11_City_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="G11_City_ReChild"/> object.</returns> internal static G11_City_ReChild GetG11_City_ReChild(int city_ID2) { return DataPortal.FetchChild<G11_City_ReChild>(city_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G11_City_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G11_City_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G11_City_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G11_City_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="city_ID2">The City ID2.</param> protected void Child_Fetch(int city_ID2) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetG11_City_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID2", city_ID2).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, city_ID2); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="G11_City_ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(City_Child_NameProperty, dr.GetString("City_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="G11_City_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G10_City parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddG11_City_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="G11_City_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(G10_City parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateG11_City_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="G11_City_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(G10_City parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteG11_City_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic; using System.Dynamic.Utils; using System.Linq.Expressions; using System.Threading; using System.Reflection; namespace System.Runtime.CompilerServices { /// <summary> /// Class responsible for runtime binding of the dynamic operations on the dynamic call site. /// </summary> public abstract class CallSiteBinder { private static readonly LabelTarget s_updateLabel = Expression.Label("CallSiteBinder.UpdateLabel"); /// <summary> /// The Level 2 cache - all rules produced for the same binder. /// </summary> internal Dictionary<Type, object> Cache; /// <summary> /// Initializes a new instance of the <see cref="CallSiteBinder"/> class. /// </summary> protected CallSiteBinder() { } /// <summary> /// Gets a label that can be used to cause the binding to be updated. It /// indicates that the expression's binding is no longer valid. /// This is typically used when the "version" of a dynamic object has /// changed. /// </summary> public static LabelTarget UpdateLabel { get { return s_updateLabel; } } private sealed class LambdaSignature<T> where T : class { private static LambdaSignature<T> s_instance; internal static LambdaSignature<T> Instance { get { if (s_instance == null) { s_instance = new LambdaSignature<T>(); } return s_instance; } } internal readonly ReadOnlyCollection<ParameterExpression> Parameters; internal readonly LabelTarget ReturnLabel; private LambdaSignature() { Type target = typeof(T); if (!target.IsSubclassOf(typeof(MulticastDelegate))) { throw Error.TypeParameterIsNotDelegate(target); } MethodInfo invoke = target.GetMethod("Invoke"); ParameterInfo[] pis = invoke.GetParametersCached(); if (pis[0].ParameterType != typeof(CallSite)) { throw Error.FirstArgumentMustBeCallSite(); } var @params = new ParameterExpression[pis.Length - 1]; for (int i = 0; i < @params.Length; i++) { @params[i] = Expression.Parameter(pis[i + 1].ParameterType, "$arg" + i); } Parameters = new TrueReadOnlyCollection<ParameterExpression>(@params); ReturnLabel = Expression.Label(invoke.GetReturnType()); } } /// <summary> /// Performs the runtime binding of the dynamic operation on a set of arguments. /// </summary> /// <param name="args">An array of arguments to the dynamic operation.</param> /// <param name="parameters">The array of <see cref="ParameterExpression"/> instances that represent the parameters of the call site in the binding process.</param> /// <param name="returnLabel">A LabelTarget used to return the result of the dynamic binding.</param> /// <returns> /// An Expression that performs tests on the dynamic operation arguments, and /// performs the dynamic operation if the tests are valid. If the tests fail on /// subsequent occurrences of the dynamic operation, Bind will be called again /// to produce a new <see cref="Expression"/> for the new argument types. /// </returns> public abstract Expression Bind(object[] args, ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel); /// <summary> /// Provides low-level runtime binding support. Classes can override this and provide a direct /// delegate for the implementation of rule. This can enable saving rules to disk, having /// specialized rules available at runtime, or providing a different caching policy. /// </summary> /// <typeparam name="T">The target type of the CallSite.</typeparam> /// <param name="site">The CallSite the bind is being performed for.</param> /// <param name="args">The arguments for the binder.</param> /// <returns>A new delegate which replaces the CallSite Target.</returns> public virtual T BindDelegate<T>(CallSite<T> site, object[] args) where T : class { return null; } internal T BindCore<T>(CallSite<T> site, object[] args) where T : class { // // Try to find a precompiled delegate, and return it if found. // T result = BindDelegate(site, args); if (result != null) { return result; } // // Get the Expression for the binding // var signature = LambdaSignature<T>.Instance; Expression binding = Bind(args, signature.Parameters, signature.ReturnLabel); // // Check the produced rule // if (binding == null) { throw Error.NoOrInvalidRuleProduced(); } // // finally produce the new rule if we need to // Expression<T> e = Stitch(binding, signature); T newRule = e.Compile(); CacheTarget(newRule); return newRule; } /// <summary> /// Adds a target to the cache of known targets. The cached targets will /// be scanned before calling BindDelegate to produce the new rule. /// </summary> /// <typeparam name="T">The type of target being added.</typeparam> /// <param name="target">The target delegate to be added to the cache.</param> protected void CacheTarget<T>(T target) where T : class { GetRuleCache<T>().AddRule(target); } private static Expression<T> Stitch<T>(Expression binding, LambdaSignature<T> signature) where T : class { Type siteType = typeof(CallSite<T>); var body = new ReadOnlyCollectionBuilder<Expression>(3); body.Add(binding); var site = Expression.Parameter(typeof(CallSite), "$site"); var @params = signature.Parameters.AddFirst(site); Expression updLabel = Expression.Label(CallSiteBinder.UpdateLabel); #if DEBUG // put the AST into the constant pool for debugging purposes updLabel = Expression.Block( Expression.Constant(binding, typeof(Expression)), updLabel ); #endif body.Add(updLabel); body.Add( Expression.Label( signature.ReturnLabel, Expression.Condition( Expression.Call( typeof(CallSiteOps).GetMethod("SetNotMatched"), @params.First() ), Expression.Default(signature.ReturnLabel.Type), Expression.Invoke( Expression.Property( Expression.Convert(site, siteType), typeof(CallSite<T>).GetProperty("Update") ), new TrueReadOnlyCollection<Expression>(@params) ) ) ) ); return Expression.Lambda<T>( Expression.Block(body), "CallSite.Target", true, // always compile the rules with tail call optimization new TrueReadOnlyCollection<ParameterExpression>(@params) ); } internal RuleCache<T> GetRuleCache<T>() where T : class { // make sure we have cache. if (Cache == null) { Interlocked.CompareExchange(ref Cache, new Dictionary<Type, object>(), null); } object ruleCache; var cache = Cache; lock (cache) { if (!cache.TryGetValue(typeof(T), out ruleCache)) { cache[typeof(T)] = ruleCache = new RuleCache<T>(); } } RuleCache<T> result = ruleCache as RuleCache<T>; Debug.Assert(result != null); return result; } } }